> For the complete documentation index, see [llms.txt](https://docs.durohub.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.durohub.com/core-concepts/documents.md).

# Documents

Learn how to manage technical documentation and files through the Duro API.

### What a Document Is

A document in Duro is a **component** whose category has type `DOCUMENT`, with an uploaded file attached through its `fileId`. There is no fixed list of document types: each library configures its own document categories — drawings, specifications, test reports, CAD exports, or whatever the library defines. Find them by reading the library's categories and keeping those with `type: DOCUMENT`:

```graphql
query DocumentCategories {
  category {
    findAll {
      id
      name
      code
      type
    }
  }
}
```

Because documents are components, they have CPNs, revisions, statuses, and history like any other component, and they are attached to other components through **document links**.

### Reading a Component's Documents

`documentLink.getDocumentLinks` returns the links on one component, each with the document component and its file:

```graphql
query ComponentDocuments {
  documentLink {
    getDocumentLinks(componentId: "123e4567-e89b-12d3-a456-426614174000") {
      id
      documentId
      documentHistoryId
      document {
        id
        name
        revisionValue
        file {
          id
          fileName
          mimeType
          size
        }
      }
    }
  }
}
```

To read the documents of several components in one call, use `documentLink.getDocumentsForComponents(componentIds: [...])`, which returns each component with its `documents`.

To download a document's file, exchange its file ID for a short-lived URL:

```graphql
query DownloadDocument {
  file {
    getDownloadUrls(input: { fileIds: ["uploaded-file-uuid"] }) {
      fileId
      fileName
      url
      expiresAt
    }
  }
}
```

### Downloading a File with Your API Key

`getDownloadUrls` returns a pre-signed storage URL. Those URLs run to about 2,200 characters, which is longer than some HTTP clients accept: Google Apps Script's `UrlFetchApp`, for one, refuses URLs past about 2,000. Any client can instead download the file from the API with a short URL and the same API key it uses for GraphQL:

```bash
curl -fOJ \
  -H "x-api-key: $DURO_API_KEY" \
  -H "x-organization: @your-org" \
  "https://api.durohub.com/files/<file id>/content"
```

The response is the file itself, with its `Content-Type`, `Content-Length`, and a `Content-Disposition` carrying the file name. In the EU or GovCloud region, use your region's API host — see [Endpoints](https://docs.durohub.com/readme.md#endpoints) — with `/files/<file id>/content` in place of `/graphql`.

| Status | `error.code`          | Meaning                                                                                                                                                                                       |
| ------ | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `200`  |                       | The file.                                                                                                                                                                                     |
| `401`  | `UNAUTHENTICATED`     | No API key, or one that is expired, revoked or not valid.                                                                                                                                     |
| `404`  | `FILE_NOT_FOUND`      | No file with that ID that your key can read. A file in another organization answers the same way as one that doesn't exist.                                                                   |
| `429`  |                       | The [`file-download`](https://docs.durohub.com/rate-limits/budgets.md#imports-exports-and-files) budget is spent. See [Handling 429s](https://docs.durohub.com/rate-limits/handling-429s.md). |
| `502`  | `STORAGE_UNAVAILABLE` | File storage did not answer. Retry with backoff.                                                                                                                                              |

Errors other than `429` have a JSON body: `{ "error": { "code": "...", "message": "..." } }`.

### The Released File

A document's `file` is its current file, which may be a working edit or the file a draft change order proposes. To download the file that was actually released, read `releasedFile`:

```graphql
query ReleasedFile {
  component {
    findOne(id: "550e8400-e29b-41d4-a716-446655440000") {
      revisionValue
      lastReleasedRevision
      releasedFile {
        id
      }
      releasedAtB: releasedFile(revision: "B") {
        id
      }
    }
  }
}
```

* With no argument, `releasedFile` is the file at the component's latest release.
* With `revision`, it is the file at the most recent release of that revision. The value is matched exactly: case-sensitive, with surrounding spaces ignored.
* It is `null` when there is no such release, when that release recorded no file, and on a historical copy of a component (a history snapshot or a pinned BOM child) rather than the component itself.

Reading `releasedFile` on a list of components costs one lookup for the whole list, so it is safe to select in `findAll` or `filter` results.

#### Example: Google Apps Script

The released file of one document, as a `Blob` you can save to Drive or attach to an email:

```javascript
const API = 'https://api.durohub.com';
const KEY = PropertiesService.getScriptProperties().getProperty('DURO_API_KEY');
const HEADERS = {
  'x-api-key': KEY,
  'x-organization': '@your-org',
  'x-library': '@your-org/your-library',
};

function releasedFileBlob(componentId) {
  const res = UrlFetchApp.fetch(`${API}/graphql`, {
    method: 'post',
    contentType: 'application/json',
    headers: HEADERS,
    payload: JSON.stringify({
      query:
        'query($id: ID!) { component { findOne(id: $id) { releasedFile { id } } } }',
      variables: { id: componentId },
    }),
  });
  const file = JSON.parse(res.getContentText()).data.component.findOne.releasedFile;
  if (!file) return null; // never released, or released without a file
  return UrlFetchApp.fetch(`${API}/files/${file.id}/content`, {
    headers: HEADERS,
  }).getBlob();
}
```

`UrlFetchApp` limits a response to 50 MB.

### Uploading a File and Linking It as a Document

Adding a document takes three steps: upload the file, confirm the upload, then create the document component and link it to a component.

**1. Request upload URLs.** `file.getUploadUrls` creates a pending file record and returns presigned URLs to upload its bytes to:

```graphql
mutation RequestUpload {
  file {
    getUploadUrls(input: [{
      fileName: "housing-drawing.pdf"
      mimeType: "application/pdf"
      size: 482133
    }]) {
      fileId
      multipartUploadId
      partSize
      parts {
        partNumber
        url
        expiresAt
      }
    }
  }
}
```

`fileName`, `mimeType` and `size` (in bytes) are required. A small file gets a single part; a large file gets several, and `multipartUploadId` is set. Split the file into chunks of `partSize` bytes — part 1 is the first chunk, and the last part may be shorter. Each part URL expires at its `expiresAt`.

**2. Upload each part and confirm.** `PUT` each chunk's bytes to its part URL and keep the `ETag` response header (without its surrounding quotes). Parts can be uploaded in any order and in parallel. Then confirm the upload with every part's number and ETag:

```bash
curl -X PUT --upload-file part-1.bin "<parts[0].url>" -D - | grep -i etag
```

```graphql
mutation ConfirmUpload {
  file {
    confirmUploads(input: [{
      fileId: "uploaded-file-uuid"
      uploadId: "multipart-upload-id"
      parts: [{ partNumber: 1, etag: "9b2cf535f27731c974343645a3985328" }]
    }]) {
      id
      fileName
      uploadConfirmedAt
      hash
    }
  }
}
```

Pass `multipartUploadId` as `uploadId`; for a single-part upload, where `multipartUploadId` is `null`, send an empty string. A file is not usable until it is confirmed. Confirming also computes the file's checksum, `hash`; see [File Checksums](#file-checksums).

**3. Create the document and link it.** The simplest way is `item.update` with `documents`, which creates the document component from the file and links it to the component in one transaction — see [Creating and Linking Documents with Item Mutations](#creating-and-linking-documents-with-item-mutations):

```graphql
mutation AttachDrawing {
  item {
    update(inputs: [{
      id: "123e4567-e89b-12d3-a456-426614174000"
      expectedVersion: 3
      documents: [
        { fileId: "uploaded-file-uuid", name: "housing-drawing.pdf", categoryId: "document-category-uuid" }
      ]
    }]) {
      id
      version
    }
  }
}
```

To link a document component that already exists, use `documentLink.create`:

```graphql
mutation LinkExistingDocument {
  documentLink {
    create(inputs: [{
      componentId: "123e4567-e89b-12d3-a456-426614174000"
      documentId: "existing-document-component-uuid"
    }]) {
      id
      componentId
      documentId
    }
  }
}
```

A new link is [synced](#synced-and-pinned-links) to the document's latest version unless you pass `documentHistoryId` to pin it. Remove a link with `documentLink.delete(id: ...)`.

***

## Organization Context for Uploads

Every file Duro stores records the organization that owns it, taken from the `x-organization` header of the `getUploadUrls` request. Change order export packaging reads the organization on the file record, so a file recorded against the wrong organization, or none, surfaces there as an export that fails to build.

### Selecting the organization

Send the organization you are uploading into with the `x-organization` header, the same way you do for every other API request. Uploads accept either form of the value:

* Organization UUID: `550e8400-e29b-41d4-a716-446655440000`
* Organization slug: `@acme-corp`

```bash
curl -X POST https://api.durohub.com/graphql \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: YOUR_API_TOKEN' \
  -H 'x-organization: @acme-corp' \
  -H 'x-library: @acme-corp/hardware-library' \
  -d '{"query": "..."}'
```

{% hint style="info" %}
Using the EU or GovCloud region? Use your region's host — see [Endpoints](https://docs.durohub.com/readme.md#endpoints).
{% endhint %}

The header is validated against the caller's memberships — you cannot tag a file with an organization you are not a member of. Duro does not infer the organization from `x-library`: an upload sent without `x-organization` (or the deprecated `orgId`) is stored with no organization. See [Selecting an Organization](https://docs.durohub.com/getting-started/authentication.md#selecting-an-organization) for how organization selection is resolved and validated.

### `UploadRequest` fields

| Field                | Status         | Notes                                                                                                                                                                                                                                                                                    |
| -------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `orgId: String`      | **Deprecated** | Used only as a fallback when no `x-organization` header is sent, and checked against the caller's memberships. Send the `x-organization` header instead.                                                                                                                                 |
| `omitOrgId: Boolean` | Optional       | Set to `true` for an upload that should not be associated with any organization. Leave it unset (or `false`) for normal, organization-scoped uploads such as component and change order documents. It is read from the first entry of the `input` list and applies to the whole request. |
| `userId: String`     | **Deprecated** | Optional and **ignored**. The uploader is always the user the API key acts as. Omit this field; a value you send cannot select or impersonate another uploader.                                                                                                                          |

{% hint style="warning" %}
Only set `omitOrgId: true` when you genuinely want an unscoped file. An organization-scoped feature that later reads the file — change order export packaging, for example — has no organization to work with and will not be able to include it.
{% endhint %}

### Who the uploader is

Every file records the user who uploaded it as `uploadedByUserId`. Duro derives that user **server-side** from the authenticated caller — the user the API key making the `getUploadUrls` call acts as — never from the request body, so the deprecated `userId` input has no effect. This applies to organization-less uploads (`omitOrgId: true`) as well. A request with no caller identity is rejected before any file record is created.

Confirming an upload is restricted to the user who started it, in addition to the organization and read checks. `confirmUploads` treats a pending file uploaded by a different user as **not found**, even for a member of the same organization and even for organization-less files.

{% hint style="warning" %}
Initiate and confirm an upload with the **same identity**. An integration that calls `getUploadUrls` with one API key or user and `confirmUploads` with another will not be able to confirm the upload. If an integration acts on behalf of several people, the file is attributed to the credential that made the request, not to any user named in the request.
{% endhint %}

{% hint style="info" %}
Some older files carry an organization that does not match the library they live in. The document itself is in the right library; only the stored organization is wrong. If a change order export package fails to generate for a document that otherwise looks correct, contact Duro support so the file record can be corrected.
{% endhint %}

***

## File Checksums

Every `File` has a nullable `hash: String`. Duro computes it **server-side** when an upload is confirmed: the file service reads the stored bytes back and hashes the whole file with CRC32C. This covers every stored file, including files Duro takes in on its own side rather than through `getUploadUrls` / `confirmUploads`. The value never comes from the uploading client or from a checksum the storage provider reports.

### Encoding

`hash` is the base64 encoding of the four big-endian bytes of the CRC32C, the same encoding S3 uses for `x-amz-checksum-crc32c` and the Duro CAD plugins compute locally. To compare against a file you hold, compute CRC32C over the whole file, pack the 32-bit result as four big-endian bytes, and base64-encode them:

```python
import base64

import google_crc32c  # pip install google-crc32c

checksum = google_crc32c.Checksum()
with open("bracket.sldprt", "rb") as f:
    # Read in 1 MiB chunks so large files never load into memory at once.
    for chunk in iter(lambda: f.read(1 << 20), b""):
        checksum.update(chunk)

# digest() is already the four big-endian bytes of the CRC32C.
local_hash = base64.b64encode(checksum.digest()).decode()
# compare local_hash with the `hash` selected on the File
```

Select `hash` wherever a `File` is returned: the `confirmUploads` result, or a document's file.

### What the checksum is for

Use `hash` for **integrity checks and change detection**: confirming a download matches what Duro holds, or skipping an upload because the bytes you have are identical to the stored version.

{% hint style="warning" %}
`hash` is **not** a content identity. CRC32C is a 32-bit checksum, so two different files can share a value. Don't use it to deduplicate content, to look files up by content, or as proof that two files are the same. A mismatch is a definite difference; a match is a strong but not conclusive signal.
{% endhint %}

### When the value is available

Files of 10 MiB or less are hashed during the `confirmUploads` call, up to 10 MiB of inline hashing per call. Everything else is hashed by a background job, and `hash` is `null` until it finishes:

* files larger than 10 MiB;
* smaller files in a call whose 10 MiB of inline hashing is already spent; once one file doesn't fit, it and every later file in the call go to the job;
* files whose inline hashing failed.

A hashing failure never fails the confirmation: the file is confirmed and usable either way. Re-query the file later to read the value.

{% hint style="info" %}
Don't treat a `null` hash as an error, and don't assume it will always be filled in. If the background job can't be scheduled, the file stays confirmed with a `null` hash. Code that depends on the checksum should handle `null` by falling back to a full comparison or a re-upload rather than waiting.
{% endhint %}

### Older files

| File                                                     | `hash` value                                               |
| -------------------------------------------------------- | ---------------------------------------------------------- |
| Confirmed through the API before Duro computed checksums | `null`                                                     |
| Migrated from Duro V1                                    | The migration's MD5, 32 hexadecimal characters             |
| Every other confirmed file                               | Base64 CRC32C as above, or `null` while the job is pending |

A 32-character hexadecimal value is an MD5, not a CRC32C, so it never matches a CRC32C you computed locally. Check the shape of the value before comparing.

***

## What a Document Depicts

A document can record the component it is *of* — a drawing of a part, rather than a file merely attached to it. That relationship lives on the document component itself, in `depictsComponentId`:

```graphql
type Component {
  "The component this document depicts, if any."
  depictsComponentId: ID

  "The depicted component, resolved. null when the document depicts nothing or the depicted component no longer exists."
  depicts: Component
}

input CreateComponentInput {
  depictsComponentId: ID
}

input UpdateComponentInput {
  depictsComponentId: ID
}
```

It is nullable and optional on both inputs. A document with `depictsComponentId: null` behaves exactly as documents always have — attached to whatever links to it, depicting nothing. Nothing changes for integrations that never set it.

A document depicts at most one component, while any number of components can attach it. Set it when you create the document, or later with the `component.update` mutation:

```graphql
mutation SetDepicts {
  component {
    update(inputs: [{
      id: "123e4567-e89b-12d3-a456-426614174000"
      depictsComponentId: "987fcdeb-51a2-43d1-9f12-426614174999"
      expectedVersion: 1
    }]) {
      id
      depictsComponentId
    }
  }
}
```

{% hint style="info" %}
`depictsComponentId` answers "which component is this document about, *now*". It is a live pointer, so it follows the component through a renumber. If you need the CPN and revision that were stamped into the artifact when it was generated, read those from the document's own recorded values — after a renumber the two legitimately differ, and the stamped value is what is true of the paper.
{% endhint %}

### Reading the depicted component

`depicts` resolves `depictsComponentId` to the component itself, so you can render "Drawing of PART-123" without a second query:

```graphql
query DocumentDepicts {
  component {
    findOne(id: "123e4567-e89b-12d3-a456-426614174000") {
      id
      name
      depictsComponentId
      depicts {
        id
        identifier {
          displayValue
        }
        revisionValue
        status {
          id
          name
        }
      }
    }
  }
}
```

`identifier.displayValue` is the depicted component's CPN. `depicts` is read-only — set the relationship through `depictsComponentId` on the create and update inputs. Because it is the same live pointer, it reflects the depicted component's *current* CPN, `revisionValue` and `status` rather than the values stamped into the document when it was generated. Compare the document's own `revisionValue` and `status` with those of `depicts` to explain a `generatedFromOlderRevision` result — see [Per-Link Staleness](#per-link-staleness).

`depicts` is `null` when `depictsComponentId` is `null`, and also when the depicted component has since been archived or no longer exists in the library. Do not assume a non-null `depictsComponentId` means a non-null `depicts`.

{% hint style="info" %}
Pointing a document at a component is a write to that component's documents. Setting or changing `depictsComponentId`, and any later update to a document that depicts a component, is checked against the depicted component's `documents` access scope — see [Who May Change a Component's Documents](#who-may-change-a-components-documents).
{% endhint %}

## Which Component Produced a Document

Alongside what a document depicts, a document can record the component it was **produced from** — the part a connector actually exported it from. That lives in `producedFromComponentId`, and it is accepted on every component write input:

```graphql
type Component {
  "The component this document was produced from. null when no producer was recorded."
  producedFromComponentId: ID
}

input CreateComponentInput { producedFromComponentId: ID }
input UpdateComponentInput { producedFromComponentId: ID }
input CreateItemInput      { producedFromComponentId: ID }
input UpdateItemInput      { producedFromComponentId: ID }
```

`null` means **unrecorded**. A document created before the field existed, or by a tool that does not set it, has no producer; it is not treated as produced from nothing in particular, and declarations handle it accordingly (see [Scoping a declaration to a producer](#scoping-a-declaration-to-a-producer)). Omitting the field on an update keeps the recorded producer; sending `null` clears it.

The producer must be an **active** component in the **same library** as the document, and cannot be the document **itself**. A write that violates any of these is rejected as a validation error.

```graphql
mutation CreateGeneratedStep {
  item {
    create(inputs: [{
      name: "housing.step"
      categoryId: "document-category-uuid"
      fileId: "uploaded-file-uuid"
      depictsComponentId: "housing-part-uuid"
      producedFromComponentId: "housing-part-uuid"
    }]) {
      id
      producedFromComponentId
    }
  }
}
```

### Producer versus depicts

The two pointers usually agree — a STEP exported from the housing both depicts and was produced from the housing — but they answer different questions:

|          | `depictsComponentId`                                                        | `producedFromComponentId`                                                               |
| -------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| Means    | What the document is *about*.                                               | Which component's save generated it.                                                    |
| Used for | Rendering "Drawing of PART-123"; [per-link staleness](#per-link-staleness). | Scoping a [document declaration](#scoping-a-declaration-to-a-producer) to one producer. |
| Set by   | Anyone who knows what the file shows.                                       | The tool that generated the file.                                                       |

An assembly drawing attached to several sub-assemblies depicts the assembly, but a connector that generated it from the top-level part records that part as the producer so a later declaration from the same part can retract it, while declarations from the sub-assemblies leave it alone.

Setting `producedFromComponentId` is a write to the document component's own fields. It does not create or change any document link; linking is still done through `documentComponentIds`, `documents`, or a declaration.

## Per-Link Staleness

`DocumentLink` reports whether the document is out of date on that particular link:

```graphql
type DocumentLink {
  "The link pins a document version older than the document's current version."
  pinnedDocumentOutdated: Boolean

  "The depicted component has moved on since the document was generated."
  generatedFromOlderRevision: Boolean
}
```

| Field                        | Meaning                                                                                                                                    | `null` when                                                         |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------- |
| `pinnedDocumentOutdated`     | The link pins a specific document version and the document has since advanced past it — the link points at v1 while the document is at v3. | The link does not pin a version, so there is nothing to compare.    |
| `generatedFromOlderRevision` | The document depicts a component whose revision or status has moved on since the document was generated from it.                           | The document depicts nothing, or the link is not the depicting one. |

Both values are **computed on read, never stored**. There is no flag to set and none to clear: re-uploading a file or advancing a revision changes the answer on the next query, because the answer is always a comparison against current state.

Staleness is **per link**. The same document can be current on one parent and out of date on another, and only the depicting link reports `generatedFromOlderRevision` — attachments of the same file elsewhere return `null` for it. Read both fields on each link you render rather than deriving a single verdict for the document.

{% hint style="warning" %}
Treat `null` as "not applicable", not as "up to date". A `null` means the comparison does not apply to that link — a link with no pinned version and no depicts relationship returns `null` for both fields.
{% endhint %}

## Who Created a Document Link

`DocumentLink` records which integration, if any, created it, and whether the principal making the current request is that creator:

```graphql
type DocumentLink {
  "The integration that created this link. null when it was created natively in Duro."
  createdByIntegrationId: ID

  "true when the principal making this request created this link: the acting integration, or native Duro when the request acts for none."
  authoredByActingIntegration: Boolean!
}
```

| Field                         | Meaning                                                                                                                                              | `null` when                                                                                                            |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `createdByIntegrationId`      | The integration that created the link — a drawing pushed by a CAD connector, for example. Written once when the link is created and never rewritten. | The link was created natively in Duro (web app, or an API call with no acting integration), or it predates this field. |
| `authoredByActingIntegration` | Whether the link's creator is the principal making this request.                                                                                     | Never. It is a non-null `Boolean`.                                                                                     |

How `authoredByActingIntegration` answers depends on who is asking:

| The request                                           | `true` for                      | `false` for                                                |
| ----------------------------------------------------- | ------------------------------- | ---------------------------------------------------------- |
| Acts for an integration (sends `x-integration-key`)   | Links that integration created. | Links created by another integration, or natively in Duro. |
| Acts for no integration (the web app, a user API key) | Links created natively in Duro. | Links created by any integration.                          |

A request with no acting integration is treated as native Duro, and native Duro is the creator of every link whose `createdByIntegrationId` is `null`. If Duro cannot resolve its own principal, the field answers `false` rather than guess.

This is the document counterpart of [`AssemblyLink.createdByIntegrationId`](https://docs.durohub.com/core-concepts/components.md#bom-line-authorship), and the same reading applies: `null` means *"not attributable to an integration"*, not *"unowned"*. Both values describe the **link**, not the document — the same document attached to two components can carry a different creator on each link.

The practical use is deciding which links are yours to manage. When a connector re-syncs a component's drawings, act only on the links where `authoredByActingIntegration` is `true` and leave documents uploaded in Duro, or by another integration, alone.

{% hint style="warning" %}
Links created before this field existed carry `createdByIntegrationId: null`, including links a connector created itself. To that connector they answer `authoredByActingIntegration: false`, exactly like a link made in Duro. A connector will not recognise its own older links from this field alone.
{% endhint %}

Select them wherever a `DocumentLink` is returned, alongside the staleness fields:

```graphql
fragment DocumentLinkProvenance on DocumentLink {
  id
  createdByIntegrationId
  authoredByActingIntegration
  pinnedDocumentOutdated
  generatedFromOlderRevision
}
```

{% hint style="warning" %}
These fields are **provenance, not authority**. They record who created the link; they do not grant or restrict access, and Duro does not refuse a write based on them. What a caller may do to a component's documents is decided by the `documents` access scope, described next.
{% endhint %}

## Who Changed a Document Link

A link's creator is written once. The link's **history** records who acted on it afterwards:

```graphql
type DocumentLinkHistory {
  "The integration acting when this history row was written. null for a native Duro action."
  actingIntegrationId: ID
}
```

`actingIntegrationId` is the integration performing the change recorded by that row — an update, such as a pin or unpin, or the removal. It is distinct from both the link's `createdByIntegrationId`, which never changes, and the row's `createdById`, which is the user. It is `null` when the action was native to Duro, and on every history row written before the field existed.

| Row                                                                                                                                | `actingIntegrationId` |
| ---------------------------------------------------------------------------------------------------------------------------------- | --------------------- |
| An update or removal performed by an integration — explicitly, or through a [per-type declaration](#declaring-documents-per-type). | That integration.     |
| An update or removal performed natively in Duro.                                                                                   | `null`                |
| Any row written before this field shipped.                                                                                         | `null`                |

Changing a link does not change its creator. A link a CAD connector created and a Duro user later unpinned still reports the connector in `createdByIntegrationId`; the unpin row reports `null` as the actor. Together the two fields tell "my link, which someone else has since changed" from "my link, which I changed last" — the document counterpart of [`AssemblyLinkHistory.actingIntegrationId`](https://docs.durohub.com/core-concepts/components.md#bom-line-authorship).

## Who May Change a Component's Documents

Writes to a component's documents answer to that component's `documents` access scope — the documents twin of the `BOM` scope that governs an assembly's lines. A library admin can designate an integration as the manager of the scope; with nothing configured the scope is open and every caller that could write before still can.

The writes the scope covers:

* Creating a document link on the component, removing one, or changing which version a link pins.
* Setting or changing `depictsComponentId` so that a document depicts the component.
* Any update to a document that already depicts the component.

Read the verdict before you write, from the component whose documents you intend to change:

```graphql
query DocumentsScope {
  component {
    findOne(id: "987fcdeb-51a2-43d1-9f12-426614174999") {
      scopeAccess(scopes: [DOCUMENTS]) {
        scope
        writable
        state
        managedBy {
          id
          name
        }
        managers {
          integration {
            id
            name
          }
          linked
        }
      }
    }
  }
}
```

The fields, the designation model and how a library configures a scope are described under [Access scopes](https://docs.durohub.com/core-concepts/components.md#access-scopes) on the components page; the `DOCUMENTS` scope works exactly like the `BOM` scope. `writable` depends on who is asking, so the same component can answer `true` to the managing connector and `false` to the web app in the same moment. A refused write returns one of the [access scope errors](https://docs.durohub.com/advanced-topics/error-handling.md#access-scope-errors).

## Synced and Pinned Links

A document link is either **synced** — it follows the document's latest version — or **pinned** to one specific version of that document. New links start synced; a link only becomes pinned when something explicitly pins it.

Change order snapshots report which of the two a link was in when the snapshot was taken:

```graphql
type DocumentLinkSnapshotItem {
  "The link follows the document's latest version rather than pinning one."
  synced: Boolean
}
```

`synced: true` and a pinned version are mutually exclusive, so a synced link never reports `pinnedDocumentOutdated` — see [Per-Link Staleness](#per-link-staleness). When `synced` is `true`, the snapshot's `documentHistoryId` is still set: it is the version the link resolved to when the snapshot was taken, not a pin. Read `synced`, not a non-null `documentHistoryId`, to tell a pinned link from a synced one.

### Pinning and unpinning

`documentHistoryId` on `UpdateDocumentLinkInput` carries the pin. It is nullable and optional, and the three cases are distinct:

```graphql
input UpdateDocumentLinkInput {
  "UUID pins that document version, null unpins, omitted leaves the pin as it is."
  documentHistoryId: String
}
```

| You send                | Result                                                                         |
| ----------------------- | ------------------------------------------------------------------------------ |
| A document history UUID | The link is pinned to that version of the document.                            |
| `null`                  | The link is unpinned and goes back to following the document's latest version. |
| Nothing (field omitted) | The current pin is preserved, whether the link is pinned or synced.            |

This is the same contract as assembly links: omitting a nullable field is not the same as sending `null` for it. Build the input so an untouched pin is left out rather than serialized as `null`, or an unrelated update will silently unpin the link.

```graphql
mutation UnpinDocumentLink {
  documentLink {
    update(
      id: "123e4567-e89b-12d3-a456-426614174000"
      input: { documentHistoryId: null }
    ) {
      id
      documentHistoryId
    }
  }
}
```

{% hint style="info" %}
Some older links created through the web app are pinned to the version the document had when the link was made. If a link you expected to be synced reports a pin, unpin it by sending `documentHistoryId: null`.
{% endhint %}

***

## Creating and Linking Documents with Item Mutations

The `item.create` and `item.update` mutations can create documents and link them to a component in the same transaction that writes the component itself — see [Item Mutations](https://docs.durohub.com/core-concepts/components.md#item-mutations-bom-and-documents-in-one-call). Three inputs cover it:

| Field                   | Type                              | On             | Description                                                                                                                                                |
| ----------------------- | --------------------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `documents`             | `[ComponentDocumentInput!]`       | create, update | Creates a DOCUMENT-category component from an uploaded file and links it to this component.                                                                |
| `documentComponentIds`  | `[ID!]`                           | create, update | Links document components that already exist.                                                                                                              |
| `removeDocumentLinkIds` | `[ID!]`                           | update only    | Removes the named document links.                                                                                                                          |
| `documentDeclaration`   | `[DocumentTypeDeclarationInput!]` | update only    | Per file type, the complete set of document links the caller holds for this component — see [Declaring documents per type](#declaring-documents-per-type). |

```graphql
input ComponentDocumentInput {
  "The file, already uploaded, that becomes the document."
  fileId: ID!
  name: String!
  categoryId: ID
}
```

Upload the file first through the normal [upload flow](#organization-context-for-uploads) and pass only its `fileId` here.

```graphql
mutation AddDocuments {
  item {
    update(inputs: [{
      id: "123e4567-e89b-12d3-a456-426614174000"
      expectedVersion: 3
      documents: [
        { fileId: "uploaded-file-uuid", name: "Housing Drawing" }
      ]
      documentComponentIds: ["existing-document-component-uuid"]
      removeDocumentLinkIds: ["stale-link-uuid"]
    }]) {
      id
      version
    }
  }
}
```

### Why `documents` takes a file rather than a document id

A document component inherits its CPN from the parent it is created under, so it cannot exist before that parent. `documents` therefore describes a document to *create* — Duro creates the document component and links it inside the same transaction, after the parent component is written. Use `documentComponentIds` for documents that already exist.

### Additive inputs, or a per-type declaration

Unlike [`children`](https://docs.durohub.com/core-concepts/components.md#bom-children-semantics), `documents` and `documentComponentIds` are **additive**: they only add links, and omitting a document never unlinks it. Removal through `removeDocumentLinkIds` is explicit and by link id.

This is deliberate: documents are routinely attached outside the calling tool — in the Duro web app, or by another integration — and a whole-component desired-state list would silently discard them.

{% hint style="info" %}
`removeDocumentLinkIds` is tolerant of ids that no longer exist. An already-removed link is skipped rather than failing the call, so a double-click or a concurrent removal does not roll back the rest of your save. It takes **document link** ids, not document component ids.
{% endhint %}

The additive inputs leave the retraction decision with the caller: to drop a PDF it no longer produces, a connector has to work out which link that was and name it. For a tool that regenerates a known set of files on every save, `documentDeclaration` moves that decision to the server. It is desired-state like `children`, but scoped two ways — to **one file type at a time**, and to **the links the caller itself created** — so it can never touch a document attached in Duro or by another integration.

### Declaring documents per type

`documentDeclaration` is available on `item.update` only — not on `item.create`, where there is nothing to retract, and not on `component.update`, which rejects every relation field.

```graphql
input UpdateItemInput {
  "Per file type, the complete set of document links the caller holds for this component."
  documentDeclaration: [DocumentTypeDeclarationInput!]
}

input DocumentTypeDeclarationInput {
  "A file extension, such as pdf or .step."
  type: String!

  "Document component ids (not link ids) that should be linked for this type."
  documentComponentIds: [ID!]!

  "Optional. When set, only unlisted documents of this type produced from this component are retracted."
  producedFromComponentId: ID
}
```

Each block says: *for this file type, these are all the documents I hold*. For every declared type, Duro compares the list against the component's active links of that type that the caller created, then:

* **adds** a link for each declared document that is not already linked, through the same path as `documentComponentIds` — the id must be an existing DOCUMENT-category component in the parent's library, and the new link is synced to the document's latest version;
* **removes** each caller-created link of that type whose document is not in the list. The link is archived; the document component itself is not deleted.

A document that is already linked — by the caller or by anyone else — is left exactly as it is: the link is not duplicated, not re-attributed, and an existing pin is kept.

| You send                                    | Result                                                                            |
| ------------------------------------------- | --------------------------------------------------------------------------------- |
| A block for a type with a list of ids       | The caller's links of that type become exactly that list.                         |
| `{ type: "pdf", documentComponentIds: [] }` | All of the caller's PDF links are removed. PDF links created by anyone else stay. |
| No block for a type                         | Links of that type are untouched, whoever created them.                           |
| `documentDeclaration: []`                   | Nothing is declared, so nothing changes.                                          |
| Field omitted                               | Nothing is declared, so nothing changes.                                          |

A connector regenerating a part's exports sends the complete set it now holds, per type. (The example omits `producedFromComponentId`; see [Scoping a declaration to a producer](#scoping-a-declaration-to-a-producer) for when to add it.)

```graphql
mutation DeclareGeneratedDocuments {
  item {
    update(inputs: [{
      id: "123e4567-e89b-12d3-a456-426614174000"
      expectedVersion: 7
      documentDeclaration: [
        { type: "pdf",  documentComponentIds: ["housing-drawing-pdf-uuid"] }
        { type: "step", documentComponentIds: ["housing-step-uuid", "housing-flat-step-uuid"] }
        { type: "dxf",  documentComponentIds: [] }
      ]
    }]) {
      id
      version
    }
  }
}
```

After this call the component carries, from this connector, exactly one PDF and two STEP files, and no DXF. A datasheet uploaded in the web app, or a PDF pushed by a different integration, is unaffected whether or not its type was declared.

#### How a type is matched

The type of an existing link is the part of the document component's **name** after its final dot, compared case-insensitively — `Housing.PDF` and `housing.pdf` are both `pdf`. On the input side, `type` is trimmed of surrounding whitespace and one leading dot is stripped, so `"pdf"`, `" PDF "` and `".pdf"` all declare the same type. A blank `type` is ignored. Two blocks that normalize to the same type are combined — their ids are linked once each, and their producer scopes are merged as described under [Scoping a declaration to a producer](#scoping-a-declaration-to-a-producer).

Documents whose names carry no usable extension — no dot at all, a leading-dot name such as `.gitignore`, or a trailing dot — have no type and so cannot be retracted by a declaration. They can still be removed through `removeDocumentLinkIds`.

Duro does not check that the ids you declare under a type actually have that extension. A document named `housing.step` declared under `pdf` is linked all the same, but it will then only ever be retracted by a later `step` declaration. Keep each block's ids to files of that type.

#### Whose links a declaration manages

The caller is the acting integration — the principal named by `x-integration-key`. A request with no acting integration acts as native Duro:

| The request                                     | Retracts                                 | Never touches                                             |
| ----------------------------------------------- | ---------------------------------------- | --------------------------------------------------------- |
| Acts for an integration                         | Unlisted links that integration created. | Links created natively in Duro or by another integration. |
| Acts for no integration (web app, user API key) | Unlisted links created natively in Duro. | Links created by any integration.                         |

This is the same identity that [`authoredByActingIntegration`](#who-created-a-document-link) reports, and the same rule as the author-scoped BOM apply described under [BOM line authorship](https://docs.durohub.com/core-concepts/components.md#bom-line-authorship).

{% hint style="warning" %}
Links created before `createdByIntegrationId` existed are native Duro, with no backfill — including links a connector created itself. A declaration from that connector will **not** retract them; it only sees its own links from the point the field started being written. A file the connector no longer produces may therefore stay linked from before that point. Remove it explicitly with `removeDocumentLinkIds` if you need it gone.
{% endhint %}

#### Scoping a declaration to a producer

Author scoping protects other principals' links. It does not, by itself, protect a connector's own links that came from a *different* part. A connector that attaches the STEP files it generated from several parts to one shared component — a bracket that carries exports from both the bracket and the weldment it belongs to, say — would, with a plain `{ type: "step" }` block, retract every STEP it ever linked there, including the ones it just generated from the other part.

`producedFromComponentId` on a block narrows the retraction to one producer. The comparison is made against each linked document's own [`producedFromComponentId`](#which-component-produced-a-document):

* **Adds** are unchanged — every listed id is linked if it is not already.
* **Retractions** apply only to the caller's unlisted links of that type whose document was produced from the given component. Documents produced from **another** component, and documents with **no recorded producer**, are preserved.

```graphql
mutation DeclareStepFromBracket {
  item {
    update(inputs: [{
      id: "bracket-uuid"
      expectedVersion: 8
      documentDeclaration: [
        {
          type: "step"
          documentComponentIds: ["bracket-step-uuid"]
          producedFromComponentId: "bracket-uuid"
        }
      ]
    }]) {
      id
      version
    }
  }
}
```

After this call the bracket still carries the weldment's STEP (produced from the weldment) and any STEP whose producer was never recorded; only the connector's stale STEPs produced from the bracket are gone.

Omitting `producedFromComponentId` keeps the per-type behavior described above: every unlisted caller link of that type is retracted, whatever its producer.

**Several blocks for one type are combined**, after type normalization, into a single declaration for that type:

| Blocks for the same type             | Links added                  | Links retracted                                                                                |
| ------------------------------------ | ---------------------------- | ---------------------------------------------------------------------------------------------- |
| All scoped, to one or more producers | The union of all listed ids. | The caller's unlisted links of that type produced from **any** of the listed producers.        |
| At least one unscoped                | The union of all listed ids. | The caller's unlisted links of that type, **across all producers**, including unrecorded ones. |

So a block with no producer is the broadest a block can be, and adding it to a set of scoped blocks for the same type widens the retraction to everything the caller holds of that type. Send scoped blocks only, or an unscoped block only, for a type unless you mean that.

{% hint style="info" %}
The producer is read from the **document component**, not the link, and it is only recorded if the tool that created the document set it. A connector that starts setting `producedFromComponentId` on new documents will find its older documents unscoped: a producer-scoped block will not retract them, because they have no producer to match. Either backfill the field with `component.update`, or remove them once with `removeDocumentLinkIds`.
{% endhint %}

#### Order, transaction and history

Within one `item.update`, the declaration runs **after** `documents`, `documentComponentIds` and `removeDocumentLinkIds` have been applied, so a document created by `documents` in the same call is already linked by the time its type is compared. All of it is one transaction with the component's own fields, writes a single consolidated history row on the parent, and is subject to the component's `DOCUMENTS` [access scope](#who-may-change-a-components-documents) and change-order guards exactly like a single-link write.

Each document component created this way gets exactly one history row, and the parent component still gets only one — the links do not write separate entries.

***

## Documents on Change Orders

Documents reach a change order in two separate ways:

* **As supporting reference material**, attached with `submitDraft` `documents` — see [Attaching Documents to a Change Order](https://docs.durohub.com/core-concepts/change-orders.md#attaching-documents-to-a-change-order).
* **As items**, added automatically when you add a component whose documents are linked to it. These items carry `isAutoAdded: true` — see [Auto-Added Documents](https://docs.durohub.com/core-concepts/change-orders.md#auto-added-documents).

### Querying Documents on a Change Order

```graphql
query GetCODocuments {
  changeOrders {
    get(filter: { ids: ["123e4567-e89b-12d3-a456-426614174000"] }) {
      connection {
        edges {
          node {
            id
            name
            documents {
              id
              componentId
              componentVersion
            }
          }
        }
      }
    }
  }
}
```

### Next Steps

Learn about managing product changes with [Change Orders](https://docs.durohub.com/core-concepts/change-orders.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.durohub.com/core-concepts/documents.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
