# SDK reference (/docs/sdk-reference)

The TypeScript and Node.js SDK submits documents, retrieves their results, and searches retained content. Start with the [SDK quickstart](/docs/sdk-quickstart) for installation and a complete first example.

## Create a client [#create-a-client]

```js
import { Pagelet } from "@pagelet-ai/sdk"

const client = new Pagelet()
```

The client reads `PAGELET_API_KEY` from the process environment. To supply credentials directly, pass `apiKey` to the constructor. An explicit value takes precedence over the environment variable. The client does not load `.env` files itself; the quickstart uses Node's `--env-file` option.

The optional `environment` is `"production"` by default, selecting `https://api.pagelet.ai`; `"staging"` selects `https://api.staging.pagelet.ai`. Use a key issued for the target environment. Missing or blank credentials fail during client setup.

## Choose an operation [#choose-an-operation]

| Method                                             | Returns                              | Waits for processing? |
| -------------------------------------------------- | ------------------------------------ | --------------------- |
| `documents.create(input)`                          | Complete document result             | Yes                   |
| `documents.list(options?)`                         | One page of matching documents       | No                    |
| `documents.get(documentId, options?)`              | Document details and current status  | No                    |
| `documents.result(documentId, options?)`           | Available document result            | No                    |
| `documents.page(documentId, pageNumber, options?)` | One page and its source-image access | No                    |
| `documents.search(input)`                          | Ranked document or page matches      | No                    |
| `jobs.create(input)`                               | Job status after submission          | No                    |
| `jobs.get(jobId, options?)`                        | Current job status and progress      | No                    |
| `jobs.result(jobId, options?)`                     | Available document result            | No                    |
| `classifications.create(input)`                    | Classification ID and status         | No                    |
| `classifications.get(documentId, id, options?)`    | Classification status and result     | No                    |

## documents.create [#documentscreate]

Upload a file and wait for its complete result:

```js
const result = await client.documents.create({ file: "statement.pdf" })
```

| Option            | Purpose                                                                                                        |
| ----------------- | -------------------------------------------------------------------------------------------------------------- |
| `file`            | Required local path, `File`, `Blob`, `Uint8Array`, or `Buffer`                                                 |
| `filename`        | Override the inferred name; required for nameless `Blob` and byte inputs                                       |
| `classification`  | Category/criteria array; omit to inherit workspace defaults, or use `null` to skip classification              |
| `externalId`      | Your application's reference for this submission                                                               |
| `externalGroupId` | Your application's reference shared by related submissions                                                     |
| `webhookUrl`      | HTTPS destination; omit to inherit the workspace default or set `null` to disable delivery for this submission |
| `idempotencyKey`  | Stable key for replaying the same submission; generated when omitted                                           |
| `timeoutMs`       | Completion deadline after submission, including result retrieval; default 600,000 ms                           |
| `signal`          | An `AbortSignal` to stop local work                                                                            |

The completion deadline does not apply to the file transfer. A timeout after submission does not cancel server processing. The `completion_timeout` error carries the job ID in `details.job_id` so you can inspect the existing job instead of submitting the file again.

The result includes `job`, `document`, `pages`, and `warnings`. Pages arrive in document order. A finalized result can contain failed pages; creation returns it when it is available. A terminal outcome without a result raises an error. See [Read and use results](/docs/results).

To classify the content as part of creation, supply your categories and criteria:

```js
const documentTypes = [{ category: "statement", criteria: ["Lists account transactions and balances."] }]
const classified = await client.documents.create({
  file: "statement.pdf",
  classification: documentTypes,
})
console.log(classified.classification?.categories)
```

Creation waits for recovery and the classification returned by confirmation within the same completion deadline. Classification failure preserves recovered content. The returned classification is the newest result snapshot and can differ if another caller starts a new request. [Classification results](/docs/classify#understand-the-result) distinguish completed matches, no matches, and unfinished requests. Omitting `classification` inherits [workspace defaults](/docs/workspace-and-team#classification-defaults). Set `classification: null` to skip classification for this upload. Without supplied or saved criteria, only recovery runs.

## documents.list [#documentslist]

Find documents using the external identifiers you supplied when uploading:

```js
const matches = await client.documents.list({ filters: { externalGroupId: "account-42" } })

for (const document of matches.documents) {
  console.log(document.id, document.filename, document.status)
}
```

| Option                    | Purpose                                                                  |
| ------------------------- | ------------------------------------------------------------------------ |
| `filters.externalId`      | Match your external document ID exactly                                  |
| `filters.externalGroupId` | Match your external group ID exactly                                     |
| `filters.categories`      | Match any supplied category on the current classification, ignoring case |
| `order`                   | `"newest"` by default; `"active"` puts in-progress documents first       |
| `pageStart`               | One-based first item position; default 1                                 |
| `pageLimit`               | Maximum documents in this response; default 25, maximum 50               |
| `signal`                  | An `AbortSignal` to cancel the request                                   |

Surrounding whitespace is removed from external identifiers on upload and lookup. Matching preserves case, internal spaces, and punctuation. Each must contain 1–255 characters after trimming. They are not unique: several documents can share either identifier. If you supply both, a document must match both. Category filters further restrict that set. Omit filters to list all retained documents in your workspace.

The method returns one page, with `documents`, `categories`, and `pagination`. `categories` contains the available category names across your retained documents, independently of the filters. When `pagination.next_start` is not `null`, request the next page using that value as `pageStart` and keep the same filters:

```js
if (matches.pagination.next_start !== null) {
  const next = await client.documents.list({
    filters: { externalGroupId: "account-42" },
    pageStart: matches.pagination.next_start,
  })
  console.log(next.documents)
}
```

No match returns an empty `documents` array. Documents are listed after upload confirmation, including while processing. Expired documents are excluded. API keys need **Read results** permission; Search access is not required. Use [`documents.search`](#documentssearch) to find documents by an identifier, filename, or page content.

## documents.get [#documentsget]

Read a retained Document's details and current processing status:

```js
const document = await client.documents.get(result.document.id)
console.log(document.filename, document.status, document.progress)
```

The response also includes confidence, timestamps, retention expiry, original download access, and webhook delivery information. It is available while processing is underway. The optional second argument accepts `signal`. Use `documents.result` for recovered Page content.

## documents.result [#documentsresult]

Read an available result by document ID:

```js
const saved = await client.documents.result(result.document.id)
```

Here, `result` is the value returned by the creation example above. In your application, save the document ID and reuse it for later reads.

Without range options, this returns all pages. Pass `pageStart` or `pageLimit` to read one bounded window; omitted values use the API defaults of start 1 and limit 25:

```js
const firstPages = await client.documents.result(result.document.id, {
  pageStart: 1,
  pageLimit: 3,
})
```

Page numbers start at 1. `pageLimit` is at most 50. You can also pass `signal`. The return shape stays the same whether you request all pages or a range. The method raises an error with code `result_not_ready` if processing has not produced an available result.

## documents.page [#documentspage]

Read one page from an existing document:

```js
const page = await client.documents.page(result.document.id, 1)
console.log(page.markdown)
```

The response contains `page_number`, `markdown`, `confidence_score`, and `image`. When available, `image` contains a temporary `url` and its `expires_at` time; otherwise it is `null`. The optional third argument accepts `signal`.

## documents.search [#documentssearch]

Search across your workspace:

```js
const matches = await client.documents.search({ query: "monthly account fees" })
```

Use `filters` to restrict the search:

```js
const matches = await client.documents.search({
  query: "termination clauses",
  filters: { externalGroupId: "application-42" },
  limit: 5,
})
```

| Option                    | Purpose                                              |
| ------------------------- | ---------------------------------------------------- |
| `query`                   | Required text or a whole external identifier to find |
| `filters.documentId`      | Find pages within one document                       |
| `filters.externalId`      | Restrict results to this exact external document ID  |
| `filters.externalGroupId` | Restrict results to this exact external group ID     |
| `limit`                   | Maximum ranked hits; default 5, maximum 10           |
| `signal`                  | An `AbortSignal` to cancel the request               |

Every result must match all supplied filters. External IDs are trimmed and case-sensitive, just as in `documents.list`. The query is trimmed and accepts up to 500 characters.

The response is `{ hits }`. Each hit contains a `document` summary. An identifier match includes `identifier.field` (`external_id` or `external_group_id`) and `identifier.value`. A content match includes `page.page_number` and `page.excerpt`. Both `identifier` and `page` are nullable. A filename match has both set to `null`.

Workspace and group searches return each document once, with exact identifier matches first. Use `filters.documentId` to return matching pages within one document. To retrieve every document with an external ID, use [`documents.list`](#documentslist) and follow its pagination.

Search requires workspace Search access. See [Search documents](/docs/search) for ordinary-language queries, explicit syntax, and result interpretation.

## jobs.create [#jobscreate]

Submit a document and receive its job status without waiting for processing:

```js
const job = await client.jobs.create({ file: "statement.pdf" })
console.log(job.id)
```

Use the same submission options as `documents.create`, including `webhookUrl`. Only `documents.create` accepts `timeoutMs` for completion waiting. Save `job.id` to retrieve the result later.

## jobs.get [#jobsget]

Read the job's current status:

```js
const status = await client.jobs.get(job.id)
console.log(status.status, status.progress)
```

The optional second argument accepts `signal`. The response includes `id`, `status`, `document_id`, external references, progress, `result_available`, detail, and timestamps. `progress` and `document_id` can be `null` while the corresponding information is unavailable.

Check `result_available` before reading the recovered content. Requested classification has its own `classification.id` and `classification.status`; it may still be running when content becomes available. A status read never waits for processing to finish.

## jobs.result [#jobsresult]

Read the available result by job ID:

```js
if (status.result_available) {
  const result = await client.jobs.result(job.id)
  console.log(result.document.filename)
}
```

This uses `job` and `status` from the preceding examples. It accepts the same `pageStart`, `pageLimit`, and `signal` options as `documents.result` and returns the same result shape. It never waits for processing.

## classifications.create [#classificationscreate]

Classify an existing Document without uploading or recovering it again:

```js
const classification = await client.classifications.create({
  documentId: result.document.id,
  schema: documentTypes,
})
```

`schema` uses the same category/criteria array as the upload's `classification` option. Omit `schema` to use saved workspace defaults; criteria are required if no defaults exist. Recovery must have finished. This returns `{ id, status }` without waiting. It accepts `idempotencyKey` and `signal`; a stable key is generated when omitted and reused across automatic retries.

The API validates the criteria. Identical current criteria can reuse existing work; different criteria while classification is active return `classification_in_progress`. The API key needs `results:read` and `classifications:create`. Upload-time classification is covered by `uploads:create`.

## classifications.get [#classificationsget]

Read the status and result of a specific classification:

```js
const outcome = await client.classifications.get(result.document.id, classification.id)
console.log(outcome.status, outcome.categories, outcome.evaluated_pages)
```

The response contains the submitted schema, categories, evaluated page numbers, failure detail, and timestamps. Status is `pending`, `processing`, `completed`, or `failed`. The optional third argument accepts `signal`. Repeat the read with a delay while status is `pending` or `processing`; stop on `completed` or `failed`. A completed empty `categories` array is a no-match result, while `null` is not a completed result. [Classify](/docs/classify#understand-the-result) explains these outcomes in the portal.

This method reads the requested classification ID. Job status and Document/Job result reads show the newest classification instead, including when another caller submits new criteria. Recovery webhooks announce recovery completion; they do not announce classification completion.

## Errors and cancellation [#errors-and-cancellation]

API and SDK failures use `PageletError`, with `code`, `message`, and available `status`, `requestId`, and `details`. These fields let you distinguish an unavailable result from an authorization or request failure. Caller cancellation preserves the supplied signal's abort reason.

See [Errors and retries](/docs/errors-and-retries) for recovery by error code and automatic retry behavior.

Stopping local work does not cancel an admitted processing job. Keep its ID and [retrieve the result later](/docs/background-processing).
