{"version":3,"file":"testing.cjs","names":["uuidv7"],"sources":["../src/testing/in-memory-ingest.ts"],"sourcesContent":["import { uuidv7 } from '../uuid.js';\nimport type { FinalizeOptions, RunCounters } from '../types.js';\nimport {\n  DEFAULT_MAPPING_TARGET,\n  type CollectedEventOptions,\n  type CollectedRecord,\n  type CollectorMapping,\n  type EventPort,\n  type IngestPort,\n  type LastRun,\n  type Logger,\n  type RunPort,\n  type SnapshotResult,\n  type SourceSpec,\n  type UpsertedSource,\n} from '../collector/types.js';\n\n/** A source's own mapping as the in-memory port keeps it: the definition only. */\nexport type RecordedMapping = Pick<CollectorMapping, 'engine' | 'expression'>;\n\n/** Where a mapping is written, as the in-memory port keeps it: one per record type, target and endpoint. */\nexport interface RecordedDestination {\n  recordType: string;\n  target: string;\n  endpoint: string;\n  enabled: boolean;\n}\n\n/** A run the in-memory port recorded. */\nexport interface RecordedRun {\n  id: string;\n  sourceId: string;\n  types: string[];\n  records: (CollectedRecord & { observedAt: string })[];\n  status: 'open' | 'completed' | 'aborted';\n  finalizeOptions?: FinalizeOptions;\n  /** Record count at each flush, to see where the listing paused. */\n  flushes: number[];\n  /** When it was opened (ISO 8601), as the API dates a run. */\n  createdAt: string;\n}\n\n/** An event the in-memory port recorded. */\nexport interface RecordedEvent {\n  sourceId: string;\n  op: 'upsert' | 'delete';\n  record: CollectedRecord & { observedAt: string };\n}\n\nexport interface InMemoryIngestOptions {\n  /**\n   * The record types its sources apply, as an organization's destinations\n   * would bind them. Default: every type asked about. The types of the\n   * mappings a source upserted apply always.\n   */\n  applied?: string[];\n  /** Told what the port does, at `info` (a local run's log). Default: silent. */\n  log?: Logger;\n}\n\nconst NO_COUNTERS: RunCounters = {\n  received: 0,\n  filtered: 0,\n  created: 0,\n  updated: 0,\n  unchanged: 0,\n  deleted: 0,\n  skipped: 0,\n  dropped: 0,\n  rejected: 0,\n  failed: 0,\n};\n\nconst destinationKey = (recordType: string, target: string, endpoint: string) =>\n  `${recordType}:${target}:${endpoint}`;\n\nconst iso = (value: Date | string | undefined): string | undefined => {\n  if (value === undefined) {\n    return undefined;\n  }\n  return value instanceof Date ? value.toISOString() : value;\n};\n\n/**\n * An `IngestPort` that records everything and never networks: what a test or\n * a local run feeds. Sources, mappings, destinations, runs and events are\n * kept in public fields to assert on.\n * @example\n * const ingest = new InMemoryIngest();\n * await runSnapshot(collector, ingest, { source: { slug: 'test' }, log: console });\n * ingest.runs[0].records; // what the snapshot sent\n */\nexport class InMemoryIngest implements IngestPort {\n  /** By slug, each with the id this port assigned it (a UUIDv7, standing in for the API's). */\n  readonly sources = new Map<string, SourceSpec & UpsertedSource>();\n\n  /** By source id, then record type: each mapping's definition. */\n  readonly mappings = new Map<string, Record<string, RecordedMapping>>();\n\n  /** By source id, then record type, target and endpoint: where each mapping is written. */\n  readonly destinations = new Map<string, Record<string, RecordedDestination>>();\n\n  readonly runs: RecordedRun[] = [];\n\n  readonly emitted: RecordedEvent[] = [];\n\n  readonly #options: InMemoryIngestOptions;\n\n  constructor(options: InMemoryIngestOptions = {}) {\n    this.#options = options;\n  }\n\n  async upsertSource(source: SourceSpec): Promise<UpsertedSource> {\n    const id = this.sources.get(source.slug)?.id ?? uuidv7();\n    this.sources.set(source.slug, { ...source, id });\n    this.#tell(`source ${source.slug} (${source.type}): ${id}`);\n    return { id, slug: source.slug };\n  }\n\n  /**\n   * Like the API's upserts: a mapping's definition is kept per record type; a\n   * destination per record type, target and endpoint, so another endpoint is\n   * another destination beside the first (a record type may go to several).\n   */\n  async upsertMappings(\n    sourceId: string,\n    mappings: Record<string, CollectorMapping>,\n  ): Promise<string[]> {\n    const definitions = { ...this.mappings.get(sourceId) };\n    const destinations = { ...this.destinations.get(sourceId) };\n    const changed = Object.entries(mappings).filter(([recordType, mapping]) => {\n      const definition = { engine: mapping.engine, expression: mapping.expression };\n      const target = mapping.target ?? DEFAULT_MAPPING_TARGET;\n      const key = destinationKey(recordType, target, mapping.endpoint);\n      const existing = destinations[key];\n      // What a spec leaves out is left as it is, as the API's upserts do.\n      const enabled = mapping.enabled ?? existing?.enabled ?? true;\n      const definitionChanged =\n        JSON.stringify(definitions[recordType]) !== JSON.stringify(definition);\n      const destinationChanged = !existing || existing.enabled !== enabled;\n      definitions[recordType] = definition;\n      destinations[key] = { recordType, target, endpoint: mapping.endpoint, enabled };\n      return definitionChanged || destinationChanged;\n    });\n    this.mappings.set(sourceId, definitions);\n    this.destinations.set(sourceId, destinations);\n    return changed.map(([recordType]) => recordType);\n  }\n\n  async appliedTypes(sourceId: string, types: string[]): Promise<string[]> {\n    const own = Object.values(this.destinations.get(sourceId) ?? {})\n      .filter((destination) => destination.enabled)\n      .map((destination) => destination.recordType);\n    const bound = this.#options.applied ?? types;\n    return types.filter((type) => own.includes(type) || bound.includes(type));\n  }\n\n  /** The source's newest run among `runs`, of any status: the latest opened (the last on a tie). */\n  async lastRun(sourceId: string): Promise<LastRun | null> {\n    const latest = this.runs\n      .filter((run) => run.sourceId === sourceId)\n      .reduce<RecordedRun | null>(\n        (newest, run) =>\n          !newest || Date.parse(run.createdAt) >= Date.parse(newest.createdAt) ? run : newest,\n        null,\n      );\n    return latest ? { id: latest.id, createdAt: latest.createdAt } : null;\n  }\n\n  async openRun(sourceId: string, types: string[]): Promise<RunPort> {\n    this.runs\n      .filter((open) => open.sourceId === sourceId && open.status === 'open')\n      .forEach((open) => {\n        Object.assign(open, { status: 'aborted' });\n      });\n    const run: RecordedRun = {\n      id: `run-${this.runs.length + 1}`,\n      sourceId,\n      types,\n      records: [],\n      status: 'open',\n      flushes: [],\n      createdAt: new Date().toISOString(),\n    };\n    this.runs.push(run);\n    this.#tell(`run ${run.id} opened (${types.join(', ')})`);\n    return {\n      id: run.id,\n      add: (record) => {\n        run.records.push({ ...record, observedAt: iso(record.observedAt) as string });\n      },\n      flush: async () => {\n        run.flushes.push(run.records.length);\n      },\n      finalize: async (options: FinalizeOptions = {}): Promise<SnapshotResult> => {\n        // A dry run is assessed and stays open, as the API's.\n        if (!options.dryRun) {\n          run.status = 'completed';\n        }\n        run.finalizeOptions = options;\n        this.#tell(\n          `run ${run.id} ${options.dryRun ? 'assessed (dry run)' : 'finalized'}: ` +\n            `${run.records.length} record(s), nothing sent (in-memory ingest)`,\n        );\n        return {\n          runId: run.id,\n          status: run.status,\n          records: run.records.length,\n          counters: { ...NO_COUNTERS, received: run.records.length },\n          reconciliation: {\n            seen: run.records.length,\n            stale: 0,\n            deleted: 0,\n            guardTripped: false,\n            guardReason: null,\n            dryRun: options.dryRun === true,\n          },\n        };\n      },\n      abort: async () => {\n        run.status = 'aborted';\n        this.#tell(`run ${run.id} aborted`);\n      },\n    };\n  }\n\n  events(sourceId: string): EventPort {\n    const push =\n      (op: 'upsert' | 'delete') =>\n      (type: string, payload: unknown, options: CollectedEventOptions = {}) => {\n        this.emitted.push({\n          sourceId,\n          op,\n          record: {\n            type,\n            payload,\n            id: options.id,\n            observedAt: iso(options.observedAt) ?? new Date().toISOString(),\n          },\n        });\n      };\n    return {\n      upsert: push('upsert'),\n      delete: push('delete'),\n      flush: async () => undefined,\n      close: async () => undefined,\n    };\n  }\n\n  #tell(line: string): void {\n    this.#options.log?.info(`[ingest:memory] ${line}`);\n  }\n}\n"],"mappings":";;;AA4DA,MAAM,cAA2B;CAC/B,UAAU;CACV,UAAU;CACV,SAAS;CACT,SAAS;CACT,WAAW;CACX,SAAS;CACT,SAAS;CACT,SAAS;CACT,UAAU;CACV,QAAQ;AACV;AAEA,MAAM,kBAAkB,YAAoB,QAAgB,aAC1D,GAAG,WAAW,GAAG,OAAO,GAAG;AAE7B,MAAM,OAAO,UAAyD;CACpE,IAAI,UAAU,KAAA,GACZ;CAEF,OAAO,iBAAiB,OAAO,MAAM,YAAY,IAAI;AACvD;;;;;;;;;;AAWA,IAAa,iBAAb,MAAkD;;CAEhD,0BAAmB,IAAI,IAAyC;;CAGhE,2BAAoB,IAAI,IAA6C;;CAGrE,+BAAwB,IAAI,IAAiD;CAE7E,OAA+B,CAAC;CAEhC,UAAoC,CAAC;C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