<h2 align="center">
    <a href="https://nullplatform.com" target="_blank">
        <img height="100" alt="nullplatform" src="https://nullplatform.com/favicon/android-chrome-192x192.png" />
    </a>
    <br>
    <br>
    @nullplatform/ingest
    <br>
</h2>

Client SDK for the nullplatform ingest API: what a collector uses to push the
state of a system (snapshots) and its changes (delta events) into nullplatform
(the catalog, core entities, any target the platform configures), and to follow
up on what became of them. Zero runtime
dependencies; ESM + CJS; Node ≥ 22, Bun, or any runtime with `fetch` and
Web Crypto.

Runnable examples (one per scenario): [`examples/`](https://unpkg.com/@nullplatform/ingest@latest/examples/) — start with
[`01-snapshot.cjs`](https://unpkg.com/@nullplatform/ingest@latest/examples/01-snapshot.cjs); a Kubernetes collector's every request, in order:
[`05-kubernetes.cjs`](https://unpkg.com/@nullplatform/ingest@latest/examples/05-kubernetes.cjs).

## Using an AI coding agent

The package ships what an agent needs to write correct code against it:

- [`llms.txt`](https://unpkg.com/@nullplatform/ingest@latest/llms.txt): the
  complete current API, the rules that prevent the common mistakes, and the
  removed calls an agent must not generate.
- An Agent Skill
  ([`skills/nullplatform-ingest`](https://unpkg.com/@nullplatform/ingest@latest/skills/nullplatform-ingest/SKILL.md)),
  the short version, which an agent that supports skills loads on its own once
  it is in the project's skills directory (Claude Code's is `.claude/skills/`):

  ```sh
  cp -r node_modules/@nullplatform/ingest/skills/nullplatform-ingest .claude/skills/
  ```

- An `AGENTS.md` at the package root, for an agent reading `node_modules`.

Or add one line to your project's `AGENTS.md` / `CLAUDE.md`:

```md
Before writing code that uses @nullplatform/ingest, read node_modules/@nullplatform/ingest/llms.txt.
```

## Install

```sh
npm install @nullplatform/ingest
```

```ts
import { IngestClient } from '@nullplatform/ingest'; // ESM
const { IngestClient } = require('@nullplatform/ingest'); // CommonJS
```

Fields are camelCase (`recordType`, `observedAt`, `sourceId`): the SDK renames
them to and from the API's snake_case, and never touches what you own (a
record's `payload`, a source's `attributes`, mapped `data`). Every closed
vocabulary is an enum the package exports (`Engine.JSONATA`,
`OnConflict.ABORT`, `RunStatus.COMPLETED`, `OnDelete.SET_NULL`…):
use the enum, not the string.

## Quick start: a snapshot

A **source** is one system of record (a cluster, a cloud account, a CMDB), of a
**source type** (`kubernetes`, nullplatform's, or one of your organization's
own). A **mapping** turns one type of raw record into entities; a
**destination** binds it to an **endpoint** of a **target** (a backend the
platform configured: `catalog`, `core_entities`; for the catalog an endpoint is
a specification, for core entities a type such as `application`), for every
source of its type or for one source (see
[Source types, mappings and destinations](#source-types-mappings-and-destinations)).
A **run** is one
full snapshot of the source: on finalize, the entities the source reported
before but not in this run are soft-deleted — behind guards.

You name a source by its **slug** (unique in your organization); the API gives
it its **id** (a UUIDv7), and every other call takes that id. `sources.upsert`
finds each source by slug and returns it, so a collector keeps the id it
answers: it creates a missing one, and brings an existing one to the spec,
sending only what differs (nothing when it matches). What a collector sends is
set again on every start, over any change made in the console, so it sends only
what it owns. A source lives at an **NRN** (`nrn`, the organization's root unless
created deeper, e.g. `organization=1:account=2`): every action on it is
authorized there, so a key granted at an account reaches the sources of that
account only. Such a key passes the NRN to `upsert` and `find`. Runs, mappings, inputs and drift checks are likewise identified by
API-minted UUIDv7 ids — except an input's id, which you choose (see
[Idempotency](#idempotency-and-order)).

```ts
import { IngestClient, OnConflict, RunStatus } from '@nullplatform/ingest';

// The public API by default: an API key is all a collector configures.
const ingest = new IngestClient({
  apiKey: process.env.NULLPLATFORM_API_KEY ?? process.env.NP_API_KEY!,
});

// A collector of a global type (`kubernetes`) only upserts its source: what its
// records become is its organization's destinations of the type, bound once.
const [source] = await ingest.sources.upsert([
  { slug: 'k8s-prod', name: 'Production cluster', type: 'kubernetes' },
]);

const run = await ingest.runs.open(source.id, {
  types: ['deployment'],
  onConflict: OnConflict.ABORT,
});
const listedAt = new Date().toISOString(); // one observation time for the whole listing
(await listDeployments()).forEach((deployment) =>
  run.add({ type: 'deployment', observedAt: listedAt, payload: deployment }),
);
const done = await run.finalize(); // flush, finalize, wait for the reconciliation
// done.status: RunStatus.COMPLETED, or RunStatus.GUARD_TRIPPED when a guard refused to delete
// done.reconciliation: { seen, stale, deleted, guardTripped, guardReason, dryRun }
```

`types` limits the run (and what finalize may delete) to some record types;
all the source maps when omitted. `finalize({ dryRun: true })` reports what
would be deleted and keeps the run open; `maxDeleteRatio` (which needs
`ingest:source:write`: it changes the source's policy for the run),
`allowFailures` and `allowRejections` override the source's guards for one
call. The record types in a source's `runs.unguardedTypes` are left out of the
guards (`maxDeleteRatio`, `rejectEmpty`): finalize still deletes their stale
entities, uncounted, for types that expire by design, like Kubernetes events. A run with inputs that died, or that were rejected before naming their
entities (a record the mapping cannot map), deletes nothing unless told so. If something fails before finalize, `run.abort()` closes the run
without deleting anything.

## Targets and endpoints

A destination writes to a `target` and an `endpoint` of it, each named by slug
or by id (`targetId`, `endpointId`), exactly one of each, and kept by id. The targets are the platform's (its
operators define them through the API; a collector only reads them); a target's
endpoints are the ones it declares and, for the catalog, its specifications,
read from it with your token:

```ts
await ingest.targets.list(); // { results: [{ id, slug: 'catalog', name, description }] }
const catalog = await ingest.targets.find('catalog');
const {
  results: [summary],
} = await ingest.endpoints.listForTarget(catalog.id, {
  slug: 'k8s-deployment',
}); // EndpointSummary: { id, targetId, slug, name, declared, backendId }
const endpoint = await ingest.endpoints.get(catalog.id, summary.id); // Endpoint | null: as it runs
const written = await ingest.endpoints.get(catalog.id, summary.id, { effective: false }); // EndpointAsWritten | null
```

An endpoint's `id` is your organization's own, the one destinations and
entities hold as `endpointId`; for a discovered endpoint, the backend's id for
it (a catalog specification's) is `backendId`, an attribute you never pass as
an endpoint id.

`endpoints.get` answers the endpoint document as it runs (`Endpoint`): its
`model`, `identity` (`assignedBy`: `AssignedBy.SOURCE` or `AssignedBy.BACKEND`),
`calls` (each with an `HttpMethod`, named by `OperationName`), `fields`
(`FieldRule`, `FieldComparison`), `behavior` (`TargetDeletePolicy`,
`ClearSemantics`, `AdoptPolicy`, `gone`: an `EndpointGone`) and `errors`
(`EndpointErrorRule[]`, each with a `TargetErrorOutcome`), every key present.
With `{ effective: false }` (`EndpointReadOptions`) it answers the endpoint as
it was written (`EndpointAsWritten`): a declared endpoint's own sections only.

Slugs are the same in every organization, which is what code that runs in many
(a collector) knows; each organization has its own id for a catalog
specification. The API resolves both slugs when a destination is created or
changed (an unknown target or endpoint is a `404`) and keeps
the ids; a renamed endpoint still works.

## Source types, mappings and destinations

A **source type** is nullplatform's (such as `kubernetes`, shared by every
organization and read-only for them) or your organization's own; a source
names one by slug (`type`) or by id (`typeId`), exactly one,
and an unknown one is a `400`. A type holds the complete run settings (`runs`);
a source holds only those it sets, and answers the effective ones (a setting
updated to `null` is its type's again). A source also carries `attributes`,
your own data about it, which mappings read as `$source.attributes`.

```ts
await ingest.sourceTypes.list(); // the global ones and your own
const github = await ingest.sourceTypes.create({
  slug: 'github',
  name: 'GitHub organization',
  runs: { maxDeleteRatio: 0.2 },
});
```

A **mapping** is a definition only (`recordType`, `engine`, `expression`),
owned by a type (nullplatform's global ones, or your organization's: shared by
every source of the type) or by one source, and revised on every change. A
**destination** binds a mapping to a target's endpoint, for every source of the
mapping's type or for one source: its owner is the route it is created at
(`destinations.createForSourceType(sourceTypeId, …)` or
`createForSource(sourceId, …)`), never a field of the spec; it follows the
mapping's latest revision or pins one (`mappingRevision`), has the only switch
(`enabled`), and says what becomes of what it wrote when it stops applying
(`onDelete`: `OnDelete.RESTRICT` refuses, `OnDelete.CASCADE` leaves it to the
next full run, `OnDelete.SET_NULL`, the default, releases it: still in the
target, no longer owned).
What a source applies is `destinations.listForSource(sourceId)`: its own
destinations and its organization's of its type; a source's own of the same
record type, target and endpoint shadows the organization's, and a disabled one
removes it. `{ effective: false }` answers the source's own destinations only;
`destinations.listForSourceType(sourceTypeId)` the organization's, for every source of the
type. A record type goes to an endpoint once per scope and may go to
several endpoints; a record type nothing is bound to is refused.

```ts
// Once per organization: the type's mapping, bound for every source of the type.
// An upsert: running it again sends no write.
const type = await ingest.sourceTypes.find('kubernetes');
const [mapping] = (await ingest.mappings.listForSourceType(type.id, { recordType: 'deployment' }))
  .results;
await ingest.destinations.upsertForSourceType(type.id, [
  { mappingId: mapping.id, target: 'catalog', endpoint: 'k8s-deployment' },
]);
```

A collector of a global type defines no mappings: its organization binds them
once. A collector of its own kind of system defines its source's own mappings,
then binds them:

```ts
const mappings = await ingest.mappings.upsertForSource(source.id, [
  {
    recordType: 'repository',
    engine: Engine.JSONATA,
    expression: '{ "id": $source.slug & "/" & name, "data": { "stars": stargazers_count } }',
  },
]);
await ingest.destinations.upsertForSource(
  source.id,
  mappings.map((mapping) => ({
    mappingId: mapping.id,
    target: 'catalog', // a target, by slug
    endpoint: `github-${mapping.recordType}`, // an endpoint of it, by slug
  })),
);
```

Setup code is safe to run on every start: every resource you configure has an
upsert, and all of them follow one contract. Each takes specs in the create
format, finds each one by its natural key (asking the API for the specs' keys
only, never reading everything there is), creates what is missing, patches
only the fields that differ (a field a spec leaves out is left as it is), never
deletes, and answers the resources in the order of the specs, each with what
it did: `upserted` is `UpsertOutcome.CREATED`, `UPDATED` or `UNCHANGED`. Two
specs of one key are refused before anything is sent.

A list filter on a key takes one value or several (`recordType: ['pod',
'node']`, `mappingId: [a, b]`), any of them matching, at most
`MAX_FILTER_VALUES` (100) per request; the upserts split theirs.

| Call                                                                                 | Finds each by                                         | Patches where it differs                                            |
| ------------------------------------------------------------------------------------ | ----------------------------------------------------- | ------------------------------------------------------------------- |
| `sources.upsert(specs)`                                                              | `slug` (at its `nrn`); its type and NRN cannot change | `name`, `description`, `attributes` (whole), the `runs` named       |
| `sourceTypes.upsert(specs)`                                                          | `slug`                                                | `name`, `description`, the `runs` named                             |
| `mappings.upsertForSourceType(sourceTypeId, specs)` / `upsertForSource(sourceId, …)` | `slug` (the record type by default)                   | `engine`, `expression`                                              |
| `destinations.upsertForSourceType(sourceTypeId, specs)` / `upsertForSource(…)`       | `mappingId` + `target` + `endpoint`                   | `mappingRevision`, `enabled`, `onDelete` (the missing in one batch) |

A slug names one mapping of a type across nullplatform's and the
organization's: `mappings.upsertForSourceType` with the slug of one of nullplatform's
answers it when the spec matches, and is refused (`403`) when it differs. To
customize one, upsert the organization's own under another slug and bind it.

A mapping shared by every source of a type keys its entities with something
unique across them (`$source.slug`, or the object's own id): an entity a key
addresses has one owner.

## Mapping output and relations

A mapping produces `{ id, data }` (or a list of them, or nothing): `data` is
the entity for each endpoint a destination binds it to, checked against that
endpoint's model (for the catalog, its specification) before anything is
written. A preview shows the verdict on a sample before anything is stored:
`mappingPreviews.create({ mapping? | mappingId?, definition?, type? | typeId?, source? | sourceId?, sample })`
evaluates a stored mapping as it is (`mappingId`), a definition not written
yet (`definition` with its `recordType`), or a stored one changed by
`definition`, on `{ payload }` or a stored input as `{ inputId }`. It answers
what was evaluated, its output, its entities and their validation per
destination (`target`, `endpoint`, `valid`, `errors`). With `sourceId`,
`$source` (`{ id, slug, type, nrn, attributes }`) is that source and the
entities are validated against what it applies; without one, `$source`
names only the type (`{ id: null, slug: null, type, nrn: null, attributes: {} }`). A write's `{ dryRun: true }` checks it as it would be made and answers
the mapping as it would be, nothing more.

- **`belongs_to` / `has_one`**: put the target's external id under the
  relation's foreign-key alias, like any field.
- **`many_to_many`**: put the **whole** set of target external ids, as an array
  of strings, under the relation's `alias`. The ingest API takes it out of the
  document and links or unlinks only what changed; `null`, `[]` or a missing
  key mean "no links" and unlink whatever was linked. Duplicates collapse,
  order does not matter. Declare the relation with an explicit alias
  (conventionally `<relation>_ids`; the catalog otherwise names it after the
  relation) and `strict: false`, so a link can point at a target the source has
  not reported yet.

```json
"relations": {
  "configmaps": { "type": "many_to_many", "target": "k8s-configmap", "strict": false, "alias": "configmap_ids" }
}
```

```js
{ "id": metadata.namespace & "/" & metadata.name,
  "data": { "external_id": metadata.namespace & "/" & metadata.name, "name": metadata.name,
            "configmap_ids": [spec.volumes.configMap.($$.metadata.namespace & "/" & name)] } }
```

`entities.list` shows each entity's links next to its document (`links`, by
relation key).

## Quick start: events

Delta events (webhooks, watches, CDC) are sent as they happen, outside any run.
They never infer deletions: a delete is explicit, and only honoured for an
entity this source owns.

```ts
const events = ingest.events.batcher(source.id);
events.upsert('deployment', deployment, { observedAt: event.time });
events.delete('deployment', deployment, { observedAt: event.time });
await events.flush(); // or close() on shutdown
```

## A collector: `runSnapshot` and `runCollector`

A collector says what it feeds (its source, the record types it produces,
its own mappings when no source type shares them), how it lists everything
(`snapshot`) and, when it can, how it watches changes (`watch`). The SDK
drives it: `runSnapshot` takes one snapshot, `runCollector` keeps feeding
until a signal stops it.

```ts
import { ClientIngest, runCollector, type CollectorDefinition } from '@nullplatform/ingest';

const collector: CollectorDefinition = {
  source: { type: 'kubernetes', name: 'Production EU' },
  recordTypes: ['deployment'], // mapped by the source type's shared mappings
  async *snapshot(ctx) {
    for await (const deployment of listDeployments(ctx.signal)) {
      yield { type: 'deployment', payload: deployment };
    }
  },
  async watch(ctx) {
    for await (const change of watchDeployments(ctx.signal)) {
      ctx.events.upsert('deployment', change.object, { observedAt: change.time });
    }
  },
};

const ingest = ClientIngest.connect({ apiKey: process.env.NP_API_KEY });
const stop = new AbortController();
process.on('SIGTERM', () => stop.abort());
await runCollector(collector, ingest, {
  source: { slug: 'prod-eu' }, // one source per deployment; nrn and name optional
  log: console, // any logger with debug, info, warn and error
  signal: stop.signal,
  intervalSeconds: 86400, // a resync a day; the watch carries every change between
});
```

What it guarantees:

- **Every snapshot sets its source up first.** The source is upserted by slug
  (a deleted one is revived with its id), the collector's own mappings and
  their destinations are upserted, and only the record types the source
  applies are sent. A source that applies none fails before a run is opened.
- **A partial listing never deletes.** A snapshot that throws, yields a type
  the collector does not declare, or is cancelled is aborted, and so is one
  whose finalize fails. A dry run is reported, then closed.
- **The listing waits on the API.** It pauses on a flush every 500 records, so
  backpressure reaches the system of record instead of memory.
- **The watch is kept alive.** It runs beside the snapshots, is restarted
  with a backoff when it throws or ends, and sends only the types the source
  applies. Snapshots never overlap each other.
- **A restart snapshots only when one is due.** The schedule follows the
  source's runs in the API (nothing else is stored): the first snapshot runs
  at once when the source has no run or its last run, of any status, started
  more than `intervalSeconds` ago; otherwise it waits until
  `intervalSeconds` after that run started. From there it runs every
  `intervalSeconds` from each snapshot's start. A redeploy or a crash loop
  does not backfill again (a failed or aborted run counts), and a last run
  that cannot be read is logged and the snapshot runs at once. The watch
  starts at once either way, and `log.info` says when the next snapshot is
  (`next snapshot at 2026-10-28T11:00:00.000Z (last run … at …)`).
  `intervalSeconds: 0` takes one snapshot on start, whatever the history.
- **A watch that recovers from an outage makes a snapshot due.** A restarted
  watch sends what exists now, but nothing tells it what vanished while it was
  down; only a snapshot's finalize deletes that. So once a watch that failed
  has been up again for `retryMaxMs` (60 s by default), a snapshot runs at
  once, or as soon as the one running ends, and the schedule continues
  `intervalSeconds` from it. One per outage, however many restarts it took: a
  watch that keeps failing never triggers one, and a watch that ends without
  an error is no outage. `log.info` says so
  (`snapshot due now (watch recovered after 3 failure(s))`). Not with
  `intervalSeconds: 0`.

`ClientIngest.connect` takes the client's tuning beside its credentials
(`timeoutMs`, `maxRetries`, `retryBaseMs`, `retryMaxMs`, `backpressureMs`,
`batching`, `fetchImpl`: `IngestClientOptions`' own). `runCollector` takes the
finalize options of its scheduled snapshots as its fourth argument, as
`runSnapshot` does: `{ dryRun: true }` assesses each snapshot and closes it,
deleting nothing.

```ts
const tuned = ClientIngest.connect({ apiKey: process.env.NP_API_KEY, timeoutMs: 60_000 });
await runCollector(
  collector,
  tuned,
  {
    source: { slug: 'prod-eu' },
    log: console,
    signal: stop.signal,
    intervalSeconds: 86400,
  },
  { dryRun: true }, // every scheduled snapshot: assessed and closed, nothing deleted
);
```

`InMemoryIngest` is the same port without a network, for tests and local
runs. It is served apart, from `@nullplatform/ingest/testing`, so the main
entry is the real client only. It records sources, mappings, destinations,
runs and events in public fields; its reconciliation deletes nothing, so it
shows what a snapshot sends, never what a real one would delete.

```ts
import { InMemoryIngest } from '@nullplatform/ingest/testing';

const memory = new InMemoryIngest();
await runSnapshot(collector, memory, { source: { slug: 'test' }, log: console });
memory.runs[0].records; // what the snapshot sent
```

## Authentication

Provide **exactly one** of `apiKey`, `token` or `getToken`.

- **`apiKey`** (recommended): the SDK exchanges your nullplatform API key for a
  token at `POST {authBaseURL}/token`, caches it, refreshes it with the refresh
  token shortly before it expires (and once after a `401`), and starts over from
  the key if the refresh token is refused. Concurrent requests share one
  exchange. `authBaseURL` defaults to `https://api.nullplatform.com`.
- **`token`**: a ready bearer token (with or without `Bearer `). Nothing to
  refresh: a `401` surfaces to you.
- **`getToken`**: your own way to get one; it is called once, and again after a
  `401`.

Every call of the SDK reaches the public API; what a key may do is its grants'.
A collector's key holds `organization:machine:ingest`, granted at the NRN its
source lives at: its source (settings included), its own mappings and
destinations, runs, inputs, and reading what it wrote. An organization's setup
(its source types, the destinations of a type, for every source of it) needs a
key holding `organization:ingest_admin` at the organization's root.

`baseURL` is where the ingest API is reached: by default the public one,
`https://api.nullplatform.com/catalog/ingest` (`DEFAULT_BASE_URL`); set it
only to reach another installation. The SDK reads **no environment
variables**: read your own `process.env` and pass the values in.

## Batching and backpressure

`run.add()` and the event batcher's `upsert()` / `delete()` buffer inputs and
ship them in batches cut by count (500, the API's limit) and by **UTF-8 encoded
size** (6 MiB, under the API's 8 MiB body limit), with bounded concurrency (2),
and on a timer (every second). Tune it with `batching: { maxBatch, maxBytes,
flushIntervalMs, concurrency }` on the client or per batcher; each is checked
when the client or the batcher is created, and a value out of range is a
`RangeError` (`maxBatch` 1–500, `maxBytes` above the request's envelope,
`flushIntervalMs` 0 or more, `concurrency` 1 or more). An input that alone
exceeds `maxBytes` is refused by `add` with a `RangeError`.

**A batch that fails for good stops its batcher**: every later `add`, `flush`
and `close` throws that same error. For a run this is the safety: a snapshot
that lost a batch can never be finalized, so it can never delete what the lost
batch carried. Abort the run and take a new snapshot.

**Retries.** `5xx` (including `503`) and network failures are retried with
full-jitter exponential backoff (`maxRetries` 4, `retryBaseMs` 250,
`retryMaxMs` 10 000) for `GET`, `PATCH` and `DELETE`, and for the `POST`s a
resend cannot repeat: `inputs.create` (each input's id makes a resend a
duplicate; run handles, event batchers, `runs.sendRecords` and `events.send`
send through it), `mappingPreviews.create` (nothing is stored), and
`replays.create` with an `idempotencyKey`. Any other `POST` (a create) is sent
once, since a resend could create twice; the upserts read again and continue
when one of their creates answers `409` (another writer created it in
between). A failed token exchange (`apiKey`) is retried like a request and
surfaces as an `IngestError`. A `401` refreshes the token and retries once,
except for a `token`, which cannot be refreshed: its `401` surfaces. Any other
`4xx` is never retried.

**Backpressure.** A `429` means the source's backlog is at its quota (the API
has not applied what it already took). The SDK waits as `Retry-After` says and tries again, without
spending retries, for up to `backpressureMs` (15 minutes) per request, so a
large snapshot slows down to the pace the API applies it instead of failing.

## Idempotency and order

Every record and event carries an `id` that **must be a UUIDv7** — the API
requires it and uses it as the input's idempotency key. It is unique in the
organization: an id the source already sent (queued or settled) is counted as a
duplicate, not applied twice; an id another source already used is a `409` for
the whole batch. The SDK generates one when you omit it, and validates one you
give, before anything is sent:

```ts
import { uuidv7, isUuidV7 } from '@nullplatform/ingest';

const id = run.add({ id: uuidv7(), type: 'deployment', payload }); // returns the id
run.add({ id: 'not-a-v7', type: 'deployment', payload }); // TypeError: … is not a UUIDv7
```

Order is the collector's clock: every input carries an `observedAt` (default:
when it was added). The API applies the newest observation per entity, whatever
order batches arrive in, and drops an older one as `stale`.

## Waiting

The API stores what you send and applies it asynchronously. The handles and
helpers poll until it is applied (`intervalMs` 500, `timeoutMs` 10
minutes; a `TimeoutError` when it runs out, an `IngestError` 404 when what
they wait on does not exist):

```ts
await run.waitApplied(); // every record of the run applied
await ingest.inputs.wait(ids); // these inputs settled; returns them
await ingest.inputs.waitIdle(source.id); // nothing pending for the source
await ingest.driftChecks.createAndWait(source.id, DriftPolicy.REPORT); // create a drift check and wait for it
```

Every `get` (`sources`, `sourceTypes`, `mappings`, `destinations`,
`endpoints`, `runs`, `inputs`, `replays`, `entities`, `driftChecks`) answers
`null` when there is none, never a 404:

```ts
const input = await ingest.inputs.get(id); // Input (its payload included) | null
if (input === null) {
  // no such input
}
```

## Lists and paging

Every list answers a `Page<Item>`: `{ paging: { limit, offset }, results }`, and
takes `{ limit, offset }` (`limit` 1–1000, default 100). There is no total:
when a page comes back full, read the next one (`offset + limit`).

```ts
const page = await ingest.inputs.list(source.id, { status: InputStatus.REJECTED, limit: 50 });
page.results; // what was refused, and why (result.errors, error)
await ingest.sources.list({ limit: 20, offset: 40 });
const mapping = await ingest.mappings.findForSource(source.id, 'repository'); // a source's own, by slug
await ingest.mappings.revisions(mapping.id); // every change: who and when, the mapping it left under `snapshot`
await ingest.entities.list(source.id, { drifted: true }); // owned entities edited behind its back
await ingest.entities.list(source.id, { target: 'catalog', endpoint: 'k8s-deployment' }); // what an endpoint holds
await ingest.entities.list(source.id, { released: true }); // what a removed destination let go
```

A `limit` or `offset` that is not a valid integer is refused client-side with a
`RangeError`.

## Soft deletes

Source types, sources, mappings and destinations are soft-deleted: they carry
`deletedAt`, and `delete()` resolves to the deleted resource. A deleted source
keeps its input log, its entities and runs, and its slug: creating that slug again (or
`sources.upsert()`) revives it with the same id (as the same type: another is a
`409`). A mapping's slug (its record type by default) is unique under its
owner, and once per type across nullplatform's and the organization's (`409`);
creating it again after a delete (or an upsert) revives it
with the same id and record type, so its revisions read as one history; a
destination of the same key and scope revives likewise. What is in use cannot
be deleted (`409`): a mapping a live destination binds, a type a live source or
mapping uses. A live slug is a `409` on create. A source or a type created
without a slug gets the one its name gives (`Prod EU` → `prod_eu`, as the
catalog derives an entity specification's), and keeps it through any rename;
an upsert always names the slug, its key.

## Errors

Every call rejects with an **`IngestError`** when the API refuses it or cannot
be reached: `status` (0 when unreachable), `code`, `message` and the response
`body`. `retryable` is true for a transient failure (unreachable, `429`,
`5xx`): the SDK already retried it, unless the call is a `POST` it sends once
(see [Retries](#batching-and-backpressure)).

| Status | `code` (`IngestErrorCode`)                            | The SDK                                                                                   |
| ------ | ----------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| 400    | `FST_ERR_VALIDATION` (`VALIDATION`)                   | fails at once                                                                             |
| 401    | `FST_ERR_AUTHENTICATION` (`AUTHENTICATION`)           | refreshes the token once, then fails                                                      |
| 403    | `FST_ERR_AUTHORIZATION` (`AUTHORIZATION`)             | fails at once (not retryable)                                                             |
| 404    | `FST_ERR_NOT_FOUND` (`NOT_FOUND`)                     | fails at once; every `get` answers `null`; a wait helper throws it for a missing resource |
| 409    | `FST_ERR_CONFLICT` (`CONFLICT`)                       | fails at once (`runs.open` may abort)                                                     |
| 429    | `FST_ERR_TOO_MANY_REQUESTS` (`TOO_MANY_REQUESTS`)     | waits per `Retry-After`                                                                   |
| 502    | `FST_ERR_TARGET_REJECTED` (`TARGET_REJECTED`)         | a target refused what the API asked it on the call's behalf; retried as a `5xx`           |
| 503    | `FST_ERR_SERVICE_UNAVAILABLE` (`SERVICE_UNAVAILABLE`) | retries with backoff (see [Retries](#batching-and-backpressure))                          |

Client-side checks throw before anything is sent: a non-UUIDv7 input id
(`TypeError`), an input larger than a batch, a bad `limit`/`offset`, batching
options out of range, or an empty `types` for `runs.create` / `runs.open` (omit
it for every type) (`RangeError`). The wait helpers throw `TimeoutError`.

## Wire contract

This section is the HTTP API as it travels (snake_case JSON, bearer auth). The
SDK takes and answers the same fields in camelCase (`record_type` is
`recordType`) and leaves what you own as it is. The types in [`dist/index.d.ts`](https://unpkg.com/@nullplatform/ingest@latest/dist/index.d.ts) mirror the API's request and
response schemas. Request bodies and queries are closed: an undeclared property
is a `400`, so the SDK builds inputs from their declared fields only.

Resources are created and listed under their owner (a source, or a type's
mappings and destinations under the type, as GitHub lists a repository's
resources under the organization or the repository); a child (run, mapping,
destination, input, drift check, replay, entity) is read and acted on by its
own id only (`/runs/{run_id}`). Destinations are created in batches of `data`,
all or none, a refusal naming its item (`data[i]: …`). Records and events are both inputs, sent to
`POST /sources/{source_id}/inputs` as `{ data: [...] }`, each in the format
`GET /inputs/{input_id}` reads it: a record names its run (`run_id`), an event
names none.

| Endpoint                                                                                                                                                                                                                  | SDK                                                                                                                                                                                                                              |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `POST /sources` · `GET /sources` (`?slug=`, `?nrn=`)                                                                                                                                                                      | `sources.create` / `upsert` · `sources.list` / `find`                                                                                                                                                                            |
| `GET` · `PATCH` · `DELETE /sources/{source_id}`                                                                                                                                                                           | `sources.get` (a deleted one too) · `update` (not the slug or the NRN) · `delete` (200, the deleted source)                                                                                                                      |
| `GET /sources/{source_id}/stats`                                                                                                                                                                                          | `sources.stats` (backlog, last run, outcomes since a moment)                                                                                                                                                                     |
| `GET /sources/{source_id}/revisions`                                                                                                                                                                                      | `sources.revisions` (every write: who, when, its own settings then)                                                                                                                                                              |
| `POST /source_types` · `GET /source_types` (`?slug=`)                                                                                                                                                                     | `sourceTypes.create` (`runs`) / `upsert` · `sourceTypes.list` / `find`                                                                                                                                                           |
| `GET` · `PATCH` · `DELETE /source_types/{source_type_id}`                                                                                                                                                                 | `sourceTypes.get` · `update` (`name`, `description`, `runs`) · `delete` (409 while in use)                                                                                                                                       |
| `GET /source_types/{source_type_id}/revisions`                                                                                                                                                                            | `sourceTypes.revisions` (every write: who, when, what it became)                                                                                                                                                                 |
| `POST` · `GET /source_types/{source_type_id}/mappings` (`?record_type=`, `?slug=`)                                                                                                                                        | `mappings.createForSourceType` (`global`; 409 on a slug the other side holds) / `upsertForSourceType` · `mappings.listForSourceType` (the global ones and the organization's) / `findForSourceType`                              |
| `POST /sources/{source_id}/mappings` (`?dry_run=true`) · `GET …/mappings` (`?record_type=`, `?slug=`)                                                                                                                     | `mappings.createForSource` / `upsertForSource` · `mappings.listForSource` / `findForSource`                                                                                                                                      |
| `GET` · `PATCH` · `DELETE /mappings/{mapping_id}` (`?dry_run=true`: checked, nothing written)                                                                                                                             | `mappings.get` · `update` · `delete` (200, the deleted mapping; 409 while bound)                                                                                                                                                 |
| `POST /mapping_previews` (`{ mapping_id?, definition?, type_id?, source_id?, sample }`: nothing stored)                                                                                                                   | `mappingPreviews.create`                                                                                                                                                                                                         |
| `GET /mappings/{mapping_id}/revisions`                                                                                                                                                                                    | `mappings.revisions`                                                                                                                                                                                                             |
| `POST /source_types/{source_type_id}/destinations` (`{ data: [{ mapping_id, target, endpoint, mapping_revision?, enabled?, on_delete? }] }`, 201) · `GET …/destinations` (`?mapping_id=`, `?target_id=`, `?endpoint_id=`) | `destinations.createForSourceType` / `upsertForSourceType` · `destinations.listForSourceType` (the organization's, for every source of the type)                                                                                 |
| `POST /sources/{source_id}/destinations` (`{ data: [...] }`, 201) · `GET …/destinations` (what the source applies; `?effective=false`: its own only; `?mapping_id=`, `?target_id=`, `?endpoint_id=`)                      | `destinations.createForSource` / `upsertForSource` · `destinations.listForSource`                                                                                                                                                |
| `GET` · `PATCH` · `DELETE /destinations/{destination_id}` · `GET …/revisions`                                                                                                                                             | `destinations.get` · `update` (`endpoint`, `mapping_revision`, `enabled`, `on_delete`) · `delete` (its `on_delete` applies) · `revisions`                                                                                        |
| `GET /targets` (`?slug=`) · `GET /targets/{target_id}/endpoints` (`?id=`, `?slug=`; `limit` ≤ 100) · `GET /targets/{target_id}/endpoints/{endpoint_id}`                                                                   | `targets.list` / `find` · `endpoints.listForTarget` · `endpoints.get` (`null` when missing)                                                                                                                                      |
| `POST /sources/{source_id}/runs` · `GET /sources/{source_id}/runs` (`?status=`)                                                                                                                                           | `runs.create` / `open` (`types`) · `runs.list`                                                                                                                                                                                   |
| `GET /runs/{run_id}`                                                                                                                                                                                                      | `runs.get` and the `wait*` helpers                                                                                                                                                                                               |
| `PATCH /runs/{run_id}` (`status: finalizing` with `finalize: { … }`, `?dry_run=true` · `status: aborted`)                                                                                                                 | `runs.finalize` · `runs.abort`                                                                                                                                                                                                   |
| `POST /sources/{source_id}/inputs` (`{ data: [{ id, run_id?, type, op?, observed_at?, payload }] }`)                                                                                                                      | `inputs.create`; `runs.sendRecords(sourceId, runId, …)` (inputs naming the run; a `RunHandle` batches) and `events.send` (inputs naming none; an `EventBatcher` batches)                                                         |
| `GET /sources/{source_id}/inputs` · `GET /inputs/{input_id}`                                                                                                                                                              | `inputs.list` (no payloads; `type`, `sort: 'receivedAt:desc'`, `after` (an input id), `outcome`, `replayId`…) · `inputs.get` (with the payload) / `wait`                                                                         |
| `POST /sources/{source_id}/replays` · `GET …/replays` · `GET /replays/{replay_id}`                                                                                                                                        | `replays.create` (`types`, `since`, `until`; `idempotencyKey`: a resend answers the same replay) · `replays.list` · `replays.get` / `wait` (`progress`, `status`; its inputs carry its id)                                       |
| `GET /sources/{source_id}/entities` · `GET /entities/{entity_id}`                                                                                                                                                         | `entities.list` (no raw records; `target`, `endpoint` (slugs) or `target_id`, `endpoint_id`, `external_id`, `backend_id`, `drifted`, `sort`…; ≤ 200 a page) · `entities.get` (by `id`, with the raw record: `ingest:input:read`) |
| `POST` · `GET /sources/{source_id}/drift_checks` (`?status=`) · `GET /drift_checks/{check_id}`                                                                                                                            | `driftChecks.create` · `driftChecks.list` · `driftChecks.get`                                                                                                                                                                    |

Every id is a UUIDv7 minted by the API, except an input's (yours); a
discovered endpoint's id in its backend (a catalog specification's) is its
`backend_id`, an attribute. Targets and endpoints also have a slug, which is what a destination names them by. The
vocabulary is `type` (a source's type slug, beside its `type_id`; an
input's record type, a run's `types`) and `record_type` (a mapping's, a
destination's, an entity's). A destination writes to a `target` and an
`endpoint` (named by slug or by `target_id` and `endpoint_id`, kept by id); a
source's entities and an input's result entities carry `target`, `target_id`, `endpoint`,
`endpoint_id`, `backend_id` (the backend's own id for the entity, when it
answers one), and the `destination_id`, `mapping_id` and `mapping_revision`
that wrote it; an entity also says its `origin` (`EntityOrigin.CREATED` by
ingest, or `EntityOrigin.ADOPTED`: already in the target) and `released_at`
(let go by a destination whose `on_delete` is `OnDelete.SET_NULL`).
On an endpoint whose backend assigns ids (`identity.assignedBy` is `AssignedBy.BACKEND`) a mapping names a parent
by its key in the same source (`namespace_id: 'team-a'`) or by
`{ backend_id: … }`, and an entity whose parent is not written yet is
`waiting` (its input stays pending and is tried again). Every list answers
`{ paging: { limit, offset }, results }`; every input (`data[]`)
needs a UUIDv7 `id` (globally unique by construction; the API rejects its reuse
within the organization); errors are
`{ statusCode, code, error, message }`.
