{"version":3,"file":"types-BKzpjXNm.cjs","names":[],"sources":["../src/uuid.ts","../src/collector/types.ts"],"sourcesContent":["/**\n * UUIDv7 via the Web Crypto API (Node ≥ 22, Bun, browsers, edge runtimes). A\n * UUIDv7 starts with a big-endian Unix-millisecond timestamp, so ids sort by\n * creation time. The API requires one as the id of every input.\n * @param now The Unix-millisecond time it starts with (default: now).\n * @returns A UUIDv7, lowercase.\n */\nexport function uuidv7(now: number = Date.now()): string {\n  const bytes = new Uint8Array(16);\n  globalThis.crypto.getRandomValues(bytes);\n  let ms = now;\n  for (let position = 5; position >= 0; position -= 1) {\n    bytes[position] = ms % 256;\n    ms = Math.floor(ms / 256);\n  }\n  bytes[6] = 0x70 + (bytes[6] % 0x10);\n  bytes[8] = 0x80 + (bytes[8] % 0x40);\n  const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/** Version nibble 7, RFC 9562 variant (10xx) — the same pattern the API validates. */\nconst UUID_V7 = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n/** True when `id` is a UUIDv7. */\nexport const isUuidV7 = (id: unknown): id is string => typeof id === 'string' && UUID_V7.test(id);\n","/**\n * What feeding a source takes: a collector's definition (the source, the\n * record types it produces, how it lists them and watches them), the ports a\n * run goes through, and what a finished snapshot reports. Everything is\n * camelCase; `ClientIngest` maps it to the wire.\n */\n\nimport type { DeletePolicy, Engine, RunStatus } from '../enums.js';\nimport type { FinalizeOptions, RunCounters, RunReconciliation } from '../types.js';\n\n/**\n * Where a run says what it does, by level: `console` will do, and so will any\n * logger with these four methods. A logger, not a trace: the run's steps and\n * outcomes are the API's runs.\n */\nexport interface Logger {\n  debug(message: string): void;\n  info(message: string): void;\n  warn(message: string): void;\n  error(message: string): void;\n}\n\n/**\n * How one record type becomes entities (evaluated by catalog-ingest-api), and\n * where they are written: a target (a backend the platform configured) and an\n * endpoint of it.\n */\nexport interface CollectorMapping {\n  engine: Engine;\n  /** Must yield `{ id, data }`, a list of them, or nothing (record filtered out). */\n  expression: string;\n  /**\n   * The target the entities are written to (`GET /targets`). Default\n   * `\"catalog\"`. It cannot change once the mapping exists: delete the mapping\n   * to move it.\n   */\n  target?: string;\n  /**\n   * Slug of the target's endpoint the entities are written to (for the\n   * catalog, a specification's slug). By slug, because a collector runs in\n   * many organizations and each has its own id for the same endpoint.\n   */\n  endpoint: string;\n  /**\n   * The switch of the destination that binds this mapping to its endpoint:\n   * `false` stops writing it, the mapping kept. Default `true`.\n   */\n  enabled?: boolean;\n}\n\n/** A source's snapshot settings; the ones left out take the API's defaults. */\nexport interface CollectorRunSettings {\n  /** Abort a snapshot that is not finished within this many seconds (6 hours). */\n  ttlSeconds?: number;\n  /** `DeletePolicy.SOFT_DELETE_STALE` (default): a finished snapshot deletes what it no longer saw. */\n  deletePolicy?: DeletePolicy;\n  /** Refuse a snapshot that would delete this share of the source or more (0.5). */\n  maxDeleteRatio?: number;\n  /** Refuse a snapshot that reported nothing (true). */\n  rejectEmpty?: boolean;\n  /**\n   * Record types left out of the guards above: a finished snapshot still\n   * deletes what it no longer saw of them, uncounted; for types that expire\n   * by design, like Kubernetes events (none).\n   */\n  unguardedTypes?: string[];\n}\n\n/** The source a collector feeds. */\nexport interface CollectorSource {\n  /** The source type's slug: what kind of system this is (`kubernetes`, `github`, …). */\n  type: string;\n  /** Display name. */\n  name: string;\n  description?: string;\n  /**\n   * The organization's own data about the source (`env`, `region`...), read\n   * by mappings as `$source.attributes`.\n   */\n  attributes?: Record<string, unknown>;\n  /**\n   * How the source's snapshots behave. Events never go through them: a\n   * delete event deletes at once.\n   */\n  runs?: CollectorRunSettings;\n}\n\n/** One raw record (or event payload) as the system of record returned it. */\nexport interface CollectedRecord {\n  /** A record type the collector declares (`recordTypes`, or a key of `mappings`). */\n  type: string;\n  payload: unknown;\n  /**\n   * When this state was observed. Defaults to the snapshot's start for\n   * snapshot records, to now for events. The newest observation of an entity\n   * wins, whatever order inputs reach the API in.\n   */\n  observedAt?: Date | string;\n  /** A UUIDv7 that makes a resend idempotent (unique in the organization); generated when omitted. */\n  id?: string;\n}\n\n/** When an event was observed, and its id. */\nexport type CollectedEventOptions = Pick<CollectedRecord, 'observedAt' | 'id'>;\n\n/** The changes a watch emits. */\nexport interface CollectorEvents {\n  upsert(type: string, payload: unknown, options?: CollectedEventOptions): void;\n  delete(type: string, payload: unknown, options?: CollectedEventOptions): void;\n  /** Send what is buffered now (events are otherwise batched for about a second). */\n  flush(): Promise<void>;\n}\n\n/**\n * What a snapshot and a watch are given. A collector's configuration is its\n * own code's: the runtime passes none.\n */\nexport interface CollectorContext {\n  /** The source it feeds: the id the API assigned it (what its calls take) and its slug. */\n  source: UpsertedSource;\n  log: Logger;\n  /** Aborted when the collector stops or the snapshot is cancelled: stop and return. */\n  signal: AbortSignal;\n}\n\nexport interface SnapshotContext extends CollectorContext {\n  /** When this snapshot started; the default `observedAt` of its records. */\n  observedAt: Date;\n}\n\nexport interface WatchContext extends CollectorContext {\n  events: CollectorEvents;\n}\n\n/** What a snapshot answers: records as it lists them, or all of them at once. */\nexport type SnapshotRecords =\n  AsyncIterable<CollectedRecord> | Iterable<CollectedRecord> | Promise<Iterable<CollectedRecord>>;\n\n/**\n * A collector: the source it feeds, the record types it produces, how it\n * lists everything (`snapshot`) and, when it can, how it watches changes\n * (`watch`).\n */\nexport interface CollectorDefinition {\n  source: CollectorSource;\n  /**\n   * The record types it produces, mapped by its source type's shared\n   * mappings: the organization binds them to its endpoints once, and only the\n   * types bound for the source are sent.\n   */\n  recordTypes?: string[];\n  /**\n   * Its own mappings, one per record type, for a type nothing shares\n   * mappings of: defined for its source and bound to the endpoint each names,\n   * before every snapshot. A collector declares `recordTypes`, `mappings`, or\n   * both.\n   */\n  mappings?: Record<string, CollectorMapping>;\n  /**\n   * Everything the system of record holds right now. Yield as you list;\n   * return to finish. Throwing aborts the snapshot: nothing is deleted for a\n   * snapshot that did not complete.\n   */\n  snapshot(ctx: SnapshotContext): SnapshotRecords;\n  /**\n   * The changes as they happen, until `ctx.signal` aborts. Restarted with a\n   * backoff when it throws or returns. Snapshots still reconcile anything it\n   * missed.\n   */\n  watch?(ctx: WatchContext): Promise<void>;\n}\n\n/** What a finished snapshot reports: the run as the API closed it. */\nexport interface SnapshotResult {\n  runId: string;\n  /** `completed`, `guard_tripped` (nothing deleted), or `aborted` (a dry run, closed once assessed). */\n  status: `${RunStatus}`;\n  /** Records the snapshot sent. */\n  records: number;\n  counters: RunCounters;\n  /** What the finalize assessed and did (`dryRun`: assessed only, nothing deleted). */\n  reconciliation: RunReconciliation | null;\n}\n\n/** The source to upsert: the definition's, under the deployment's slug. */\nexport interface SourceSpec extends CollectorSource {\n  /** Stable name, unique in the organization (lowercase letters, digits, `.`, `_`, `-`). */\n  slug: string;\n  /** Where the source lives (the organization's root unless given); never changed once it exists. */\n  nrn?: string;\n}\n\n/**\n * The source a run feeds, as its deployment says it: its slug (one per\n * deployment), its NRN, and a name over the definition's (one collector, many\n * deployments).\n */\nexport type RunSource = Pick<SourceSpec, 'slug' | 'nrn'> & Partial<Pick<SourceSpec, 'name'>>;\n\n/** A source as the API holds it. */\nexport interface UpsertedSource {\n  /** Assigned by the API (a UUID): every later call about the source takes it. */\n  id: string;\n  slug: string;\n}\n\n/**\n * A run of a source as a collector's schedule reads it: which one, and when\n * it started (by the API's clock). Every status counts: a run started then is\n * a snapshot attempted then.\n */\nexport interface LastRun {\n  id: string;\n  /** When the run was opened (ISO 8601). */\n  createdAt: string;\n}\n\n/** A collected record with its observation time set. */\nexport type ObservedRecord = CollectedRecord & { observedAt: Date | string };\n\n/** A snapshot run being fed. */\nexport interface RunPort {\n  readonly id: string;\n  add(record: ObservedRecord): void;\n  /** Send what is buffered and wait until the API accepted it (the backpressure point). */\n  flush(): Promise<void>;\n  /**\n   * Flush, finalize and wait for the reconciliation. A dry run is assessed and\n   * stays open (`reconciliation.dryRun`): abort it once reported. Throws when\n   * a batch failed: the run cannot be finalized; abort it.\n   */\n  finalize(options?: FinalizeOptions): Promise<SnapshotResult>;\n  /** Close without deleting anything. */\n  abort(): Promise<void>;\n}\n\n/** A source's event stream. */\nexport interface EventPort extends CollectorEvents {\n  close(): Promise<void>;\n}\n\n/**\n * How a collector reaches the API: `ClientIngest` (the real one, through an\n * `IngestClient`) or, in a test or a local run, `InMemoryIngest`\n * (`@nullplatform/ingest/testing`: records everything, never networks).\n */\nexport interface IngestPort {\n  /**\n   * The source of `source.slug`, looked for at `source.nrn`: created when\n   * missing (a deleted one is revived), otherwise patched where it differs.\n   */\n  upsertSource(source: SourceSpec): Promise<UpsertedSource>;\n  /**\n   * The source's own mappings and where each is written: created when\n   * missing, patched where they differ.\n   * @returns The record types whose mapping or destination was written (`[]` when nothing was).\n   */\n  upsertMappings(sourceId: string, mappings: Record<string, CollectorMapping>): Promise<string[]>;\n  /** Of `types`, those the source applies: an enabled destination binds a mapping of each. */\n  appliedTypes(sourceId: string, types: string[]): Promise<string[]>;\n  /**\n   * The source's newest run, whatever its status (open, completed, aborted,\n   * failed…): when the source last attempted a snapshot.\n   * @returns The run, or `null` when the source has none.\n   */\n  lastRun(sourceId: string): Promise<LastRun | null>;\n  /** Open a run covering `types`; an abandoned open run of the source is aborted first. */\n  openRun(sourceId: string, types: string[]): Promise<RunPort>;\n  events(sourceId: string): EventPort;\n}\n\n/** The target a mapping writes to when it names none. */\nexport const DEFAULT_MAPPING_TARGET = 'catalog';\n"],"mappings":";;;;;;;;AAOA,SAAgB,OAAO,MAAc,KAAK,IAAI,GAAW;CACvD,MAAM,wBAAQ,IAAI,WAAW,EAAE;CAC/B,WAAW,OAAO,gBAAgB,KAAK;CACvC,IAAI,KAAK;CACT,KAAK,IAAI,WAAW,GAAG,YAAY,GAAG,YAAY,GAAG;EACnD,MAAM,YAAY,KAAK;EACvB,KAAK,KAAK,MAAM,KAAK,GAAG;CAC1B;CACA,MAAM,KAAK,MAAQ,MAAM,KAAK;CAC9B,MAAM,KAAK,MAAQ,MAAM,KAAK;CAC9B,MAAM,MAAM,MAAM,KAAK,QAAQ,SAAS,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;CACnF,OAAO,GAAG,IAAI,MAAM,GAAG,CAAC,EAAE,GAAG,IAAI,MAAM,GAAG,EAAE,EAAE,GAAG,IAAI,MAAM,IAAI,EAAE,EAAE,GAAG,IAAI,MAAM,IAAI,EAAE,EAAE,GAAG,IAAI,MAAM,EAAE;AACzG;;AAGA,MAAM,UAAU;;AAGhB,MAAa,YAAY,OAA8B,OAAO,OAAO,YAAY,QAAQ,KAAK,EAAE;;;;ACuPhG,MAAa,yBAAyB"}