@murumets-ee/imports 0.37.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runner-C-s6SD7t.mjs","names":[],"sources":["../src/streaming.ts","../src/read-feed.ts","../src/error-tracker.ts","../src/runner.ts"],"sourcesContent":["/**\n * Tab-delimited / CSV streaming reader. Generic over delimiter so the\n * same path handles `.txt` (tab), `.csv` (comma), and the rare `;`\n * European export dialect.\n *\n * Built on `csv-parse` per giga-test precedent — node-stream-based, low\n * memory, handles UTF-8 BOM (the carmaker feeds are Windows-exported\n * and ship with a BOM that breaks naive split-on-tab parsers).\n *\n * The reader yields `{ rowNumber, row }` pairs where:\n * - `rowNumber` is 1-based and counts the header as row 0.\n * - `row` is `Record<string, string>` keyed by header name. Empty cells\n * are the empty string, NOT `undefined` — feed transforms test with\n * `value === ''` consistently.\n *\n * Why this lives in a streaming reader and not inside the transform\n * itself: the transform sees one already-parsed row at a time, never\n * the file. That keeps transform implementations free of I/O concerns\n * and makes them trivially unit-testable with a fixture row map.\n */\n\nimport { createReadStream } from 'node:fs'\nimport { parse } from 'csv-parse'\n\n/**\n * Throw if two (non-empty) header names collide. Headers are the keys the mapping\n * engine matches a `source` against; after trimming, two columns differing only in\n * whitespace would collapse to one key and silently overwrite each other's data.\n * Fail fast instead — the operator fixes the feed or the mapping. Shared by the\n * csv/tsv reader (below) and the xlsx reader. Blank columns are ignored (unmapped).\n */\nexport function assertUniqueHeaders(header: readonly string[]): void {\n const seen = new Set<string>()\n for (const h of header) {\n if (h === '') continue\n if (seen.has(h)) {\n throw new Error(`Duplicate header \"${h}\" after trimming — column names must be unique`)\n }\n seen.add(h)\n }\n}\n\n/**\n * Pre-pass: count data rows in a delimited file (excluding the header\n * row when `hasHeader` is true; default `true` to match `streamFeed`).\n *\n * Implementation: stream the file as raw bytes and tally `\\n`. NOT a\n * full parse — escaped newlines inside quoted fields would over-count.\n * That's acceptable for the supplier-feed use case because we default\n * `quote: false` (every `\\n` IS a row boundary). For genuine RFC-4180\n * CSV inputs with embedded newlines, treat the result as an upper\n * bound; the actual parsed row count from `streamFeed` is authoritative.\n *\n * Why bytes-only and not csv-parse: a 16 MB feed counts in ~50 ms with\n * `\\n` tally vs ~500 ms with csv-parse parsing. For 500 MB the gap\n * matters — pre-pass needs to be a small fraction of the actual import\n * or the operator perceives the run as \"stuck on pre-pass\" with no UI.\n *\n * Returns the number of DATA rows (header excluded when present).\n * Empty trailing lines (no `\\n` after the final row, or a single\n * trailing `\\n`) are handled identically to how csv-parse treats them\n * with `skip_empty_lines: true`.\n */\nexport async function countDataRows(\n filePath: string,\n options: { hasHeader?: boolean } = {},\n): Promise<number> {\n const { hasHeader = true } = options\n const stream = createReadStream(filePath)\n let count = 0\n let lastByte = 0\n for await (const chunk of stream as AsyncIterable<Buffer>) {\n for (let i = 0; i < chunk.length; i += 1) {\n if (chunk[i] === 0x0a /* \\n */) count += 1\n }\n if (chunk.length > 0) lastByte = chunk[chunk.length - 1] ?? 0\n }\n // If the file doesn't end with a newline, the final row didn't get\n // counted by the `\\n` tally — add one. Skipping when the file is\n // entirely empty (count=0 and lastByte=0).\n if (lastByte !== 0 && lastByte !== 0x0a) count += 1\n return hasHeader ? Math.max(0, count - 1) : count\n}\n\nexport interface StreamFeedOptions {\n /** Path to the file on disk. The PoC uploads land on local disk; S3-keyed reads come later. */\n filePath: string\n /**\n * Single-character field delimiter. Default `\\t` (the carmaker feed\n * format). Pass `,` for CSV, `;` for some European dialects.\n */\n delimiter?: string\n /**\n * `true` (default): the first row is the header and column names come\n * from it. `false`: rows are emitted as positional `{ \"0\": ..., \"1\": ... }`\n * and the transform reads by index — useful for headerless feeds that\n * commit to a documented column order.\n */\n hasHeader?: boolean\n /**\n * Optional explicit column-name list. When provided, takes precedence\n * over `hasHeader` (header row, if present, is skipped but its values\n * are ignored). Useful when the upstream header is unstable but the\n * positional shape isn't.\n */\n columns?: ReadonlyArray<string>\n /**\n * Forward to `csv-parse` `relax_column_count`. Default `false` —\n * a row whose column count doesn't match the header surfaces as a\n * parser error so the transform isn't silently fed truncated data.\n */\n relaxColumnCount?: boolean\n /**\n * Forward to `csv-parse` `quote`. The character (or `false`) that\n * encloses fields containing the delimiter. Default `false` — most\n * supplier feeds in this package's target use case are tab-delimited\n * exports that contain literal `\"` characters in description fields\n * (e.g. `LIVRE \"INVERSION D'IMAGE\"` from the Mercedes carmaker feed)\n * with NO quote-as-field-wrapper convention. csv-parse's library\n * default `'\"'` then misreads the literal `\"` as an opening quote\n * and rejects the row with `Invalid Opening Quote`.\n *\n * Pass `'\"'` (or any character) to opt back into RFC-4180-style\n * CSV parsing for genuine quoted-CSV inputs. Pass `'\\''` for\n * single-quoted dialects.\n */\n quote?: string | false\n}\n\nexport interface StreamFeedRow {\n /** 1-based row number. Header (when present) is row 0; first data row is row 1. */\n rowNumber: number\n /**\n * Cell values keyed by column name (or string-position when\n * `hasHeader: false` AND no `columns`).\n *\n * **Cell-value invariants:**\n * - Empty cells (`A\\t\\tC`) → `''` (empty string).\n * - Missing TRAILING cells in `relaxColumnCount: true` mode → the\n * key is **absent** from the object, not present-with-`''`. csv-parse\n * does not emit keys for short rows. Transforms reading those\n * columns get `undefined` from `row['col']` and must handle it\n * (`row['col'] ?? ''` is the canonical idiom).\n * - With the default `relaxColumnCount: false`, short rows reject at\n * the parser, so this case never reaches the transform.\n */\n row: Record<string, string>\n}\n\n/**\n * Async-iterable over the parsed rows of a delimited file. Use with\n * `for await (const { rowNumber, row } of streamFeed({ filePath, ... }))`.\n *\n * The iterator owns its file descriptor — the `for await` loop closes\n * the underlying stream when it returns or breaks. Aborting mid-stream\n * (`break`, `throw`, signal) is safe; csv-parse propagates the close.\n */\nexport async function* streamFeed(options: StreamFeedOptions): AsyncIterable<StreamFeedRow> {\n const {\n filePath,\n delimiter = '\\t',\n hasHeader = true,\n columns,\n relaxColumnCount = false,\n quote = false,\n } = options\n\n // When the caller provides explicit `columns`, prefer them. When the file\n // has a header but no explicit `columns`, derive the column names from the\n // first row via a function so we can TRIM them — real supplier feeds ship\n // leading/trailing-space headers (R03 Samples A/C: `\" JAEHIND KM-TA\"`), and\n // an untrimmed key wouldn't match a mapping's `source`. The xlsx reader trims\n // headers the same way. When neither is true, rows get string-position keys.\n //\n // csv-parse's `columns` accepts `ColumnOption[] | boolean | ((record) =>\n // ColumnOption[])`; `string[]` satisfies `ColumnOption[]`.\n const columnConfig: string[] | boolean | ((header: string[]) => string[]) = columns\n ? Array.from(columns)\n : hasHeader\n ? (header: string[]) => {\n const trimmed = header.map((h) => h.trim())\n assertUniqueHeaders(trimmed)\n return trimmed\n }\n : false\n\n const stream = createReadStream(filePath)\n const parser = stream.pipe(\n parse({\n delimiter,\n columns: columnConfig,\n bom: true,\n skip_empty_lines: true,\n // csv-parse defaults to strict column count; opt-in relaxation only.\n relax_column_count: relaxColumnCount,\n // Default `quote: false` — see StreamFeedOptions.quote JSDoc.\n // Carmaker / parts-feed exports contain literal `\"` characters\n // in description fields and would otherwise reject as\n // `Invalid Opening Quote`. Genuine RFC-4180 CSV consumers opt\n // back in by passing `quote: '\"'`.\n quote,\n }),\n )\n\n let rowNumber = 0\n try {\n for await (const rawRow of parser as AsyncIterable<\n ReadonlyArray<string> | Record<string, string | undefined>\n >) {\n rowNumber += 1\n // csv-parse emits records with string keys when `columns` is\n // truthy, otherwise an Array. Normalise both shapes to\n // `Record<string, string>` so transforms can rely on `value === ''`\n // for missing cells (csv-parse leaves trailing missing cells as\n // `undefined` when `relax_column_count: true`; this collapses\n // them to `''` to keep the contract uniform).\n const row: Record<string, string> = {}\n if (Array.isArray(rawRow)) {\n const arr = rawRow as ReadonlyArray<string | undefined>\n for (let i = 0; i < arr.length; i += 1) {\n row[String(i)] = arr[i] ?? ''\n }\n } else {\n for (const [k, v] of Object.entries(rawRow)) {\n row[k] = v ?? ''\n }\n }\n yield { rowNumber, row }\n }\n } finally {\n // Safety: ensure the underlying file descriptor closes even if the\n // consumer breaks mid-iteration. Node closes streams on\n // garbage-collection but this makes it deterministic under tests.\n stream.destroy()\n }\n}\n","/**\n * Feed reader dispatcher (commerce-demo phase 02, D005). Selects the reader by\n * `format` and yields the uniform `AsyncIterable<{ rowNumber, row }>` the runner\n * consumes — csv/tsv via the existing `streamFeed` (csv-parse), xlsx via the\n * exceljs-backed `streamXlsx`.\n *\n * **Back-compat**: with no `format` (the carmaker worker passes only `filePath`),\n * this defaults to tab-delimited — the original `streamFeed` behaviour — so the\n * existing import path is unchanged.\n *\n * **Bundle safety**: the xlsx reader (and its heavy, Node-only exceljs dep) is\n * `await import()`-ed ONLY for `format: 'xlsx'`, so the csv/tsv path — and anything\n * that statically imports the runner — never pulls exceljs into its module graph.\n */\n\nimport { z } from 'zod'\nimport { type StreamFeedOptions, type StreamFeedRow, streamFeed } from './streaming.js'\n\n/**\n * The reader-config subset safe to persist in `import_run.params.feed` and rehydrate\n * in the worker (commerce-demo PR3). It is exactly the {@link ReadFeedOptions} fields\n * that describe HOW to parse a feed — `filePath` is supplied by the worker after it\n * materialises the upload, never carried in params. Validated at BOTH ends: the\n * commerce run route builds it from a saved `import_mapping`, the worker re-parses it\n * before handing it to {@link readFeed} (defense-in-depth against a tampered row).\n */\nexport const feedReaderConfigSchema = z\n .object({\n format: z.enum(['csv', 'tsv', 'xlsx']).optional(),\n delimiter: z.string().min(1).max(4).optional(),\n hasHeader: z.boolean().optional(),\n headerRowIndex: z.number().int().min(0).optional(),\n sheet: z.string().min(1).max(128).optional(),\n })\n .strict()\nexport type FeedReaderConfig = z.infer<typeof feedReaderConfigSchema>\n\n/**\n * Rehydrate the reader config a run persisted in `import_run.params.feed`.\n *\n * ONE implementation, because two would drift and drift here is silent: the\n * worker uses it to decide how to READ a feed, and the #842 audit uses it to\n * re-read the same file the same way. An audit that rehydrates differently from\n * the run it is auditing invents corruption, or misses it.\n *\n * ABSENT means \"the carmaker default\", i.e. tab-delimited, which is what an\n * empty config parses to — so a non-object `params`, or `params` with no\n * `feed`, is a real answer rather than a gap. A PRESENT `feed` is validated\n * whatever its shape: a scalar or an array there is a malformed persisted blob,\n * and reading it as \"no config\" would silently import an xlsx run as tsv.\n */\nexport function readPersistedFeedConfig(\n params: unknown,\n): ReturnType<typeof feedReaderConfigSchema.safeParse> {\n const record =\n params && typeof params === 'object' && !Array.isArray(params)\n ? (params as Record<string, unknown>)\n : {}\n // `null` is how \"absent\" round-trips through JSONB, so it defaults with\n // `undefined`. Everything else present goes to the schema and is rejected on\n // its merits rather than being flattened into the default.\n const feed = record.feed === undefined || record.feed === null ? {} : record.feed\n return feedReaderConfigSchema.safeParse(feed)\n}\n\nexport interface ReadFeedOptions {\n /** Path to the file on local disk. */\n filePath: string\n /** Feed format. Omitted → tab-delimited (tsv), matching the legacy carmaker reader. */\n format?: 'csv' | 'tsv' | 'xlsx'\n /** Explicit delimiter override (csv/tsv). Defaults from `format` (`csv` → `,`, else `\\t`). */\n delimiter?: string\n /** First row is the header. Default `true`. */\n hasHeader?: boolean\n /** 0-based header row index (xlsx). */\n headerRowIndex?: number\n /** xlsx worksheet as a 1-based index string. Omit → first sheet. */\n sheet?: string\n /** Explicit column-name list (csv/tsv) — see `streamFeed`. */\n columns?: ReadonlyArray<string>\n /** Forward to csv-parse `relax_column_count` (csv/tsv). */\n relaxColumnCount?: boolean\n /** Forward to csv-parse `quote` (csv/tsv). */\n quote?: string | false\n}\n\nfunction toStreamFeedOptions(o: ReadFeedOptions): StreamFeedOptions {\n // No format → tab (the carmaker feed default). `csv` → comma; everything else → tab.\n const delimiter = o.delimiter ?? (o.format === 'csv' ? ',' : '\\t')\n return {\n filePath: o.filePath,\n delimiter,\n ...(o.hasHeader !== undefined && { hasHeader: o.hasHeader }),\n ...(o.columns !== undefined && { columns: o.columns }),\n ...(o.relaxColumnCount !== undefined && { relaxColumnCount: o.relaxColumnCount }),\n ...(o.quote !== undefined && { quote: o.quote }),\n }\n}\n\n/** Stream a feed file's data rows, dispatching on `format`. */\nexport async function* readFeed(options: ReadFeedOptions): AsyncIterable<StreamFeedRow> {\n if (options.format === 'xlsx') {\n const { streamXlsx } = await import('./xlsx-reader.js')\n yield* streamXlsx({\n filePath: options.filePath,\n ...(options.hasHeader !== undefined && { hasHeader: options.hasHeader }),\n ...(options.headerRowIndex !== undefined && { headerRowIndex: options.headerRowIndex }),\n ...(options.sheet !== undefined && { sheet: options.sheet }),\n })\n return\n }\n yield* streamFeed(toStreamFeedOptions(options))\n}\n","/**\n * Aggregates per-row errors into top-N pattern buckets so a feed of 1M\n * malformed rows surfaces as a handful of actionable signatures rather\n * than a million identical strings.\n *\n * Lifted from giga-test (`backend/src/workers/csv-importer.ts`) and\n * generalized:\n * - Configurable caps so the importer can tune memory bounds per run.\n * - Pure data — no logging side effects, no I/O.\n * - JSON-serialisable output via {@link ErrorTracker.snapshot} for the\n * `import_run.errorSummary` column.\n *\n * Pattern signature shape: `${errorType}:${field || 'GENERAL'}:${message}`.\n * Same `errorType + field + message` collapses to one bucket; differing\n * messages stay separate. This is intentional: a parser error on column\n * `NetPrice/Discount` (\"invalid number 'NA,5'\") and the same on column\n * `GrossPrice` are operationally distinct even if the parser is the same.\n *\n * Memory bounds: the patterns map is capped at `maxPatterns`. Once full,\n * additional NEW signatures are dropped — known patterns keep accumulating\n * counts. This is the \"top-N most common\" model: rare-but-novel errors\n * past the cap are invisible, but the cap protects against a runaway\n * adversarial feed exploding the map. Sample arrays are independently\n * capped at `maxSamplesPerPattern`.\n */\n\n/**\n * Recursively-defined JSON-serialisable value. Mirrors the shape of\n * `JsonValue` in `@murumets-ee/entity` without taking a dependency on\n * that package — error-tracker is otherwise standalone, and the\n * `ImportRun.errorSummary` JSONB column accepts anything in this shape.\n */\nexport type ImportJsonValue =\n | string\n | number\n | boolean\n | null\n | ImportJsonValue[]\n | { [key: string]: ImportJsonValue }\n\n/** One sample row attached to a pattern. `rowData` is the originally-parsed row. */\nexport interface ErrorSample {\n rowNumber: number\n rowData: ImportJsonValue\n}\n\n/** Public shape of an aggregated pattern as returned by {@link ErrorTracker.getTopPatterns}. */\nexport interface ErrorPattern {\n errorType: string\n field: string | null\n message: string\n count: number\n firstOccurrence: number\n lastOccurrence: number\n samples: ReadonlyArray<ErrorSample>\n /** `count / totalErrors`, scaled 0..100. `0` when there are zero errors total. */\n percentage: number\n}\n\nexport interface ErrorTrackerConfig {\n /** Hard cap on distinct signatures. Defaults to 50. New signatures past the cap are dropped. */\n maxPatterns?: number\n /** Hard cap on samples retained per pattern. Defaults to 5. Excess samples are dropped. */\n maxSamplesPerPattern?: number\n}\n\n/** Default caps — match giga-test for compatibility. */\nexport const DEFAULT_MAX_PATTERNS = 50\nexport const DEFAULT_MAX_SAMPLES_PER_PATTERN = 5\n\ninterface InternalPattern {\n errorType: string\n field: string | null\n message: string\n count: number\n firstOccurrence: number\n lastOccurrence: number\n samples: ErrorSample[]\n}\n\nexport class ErrorTracker {\n private readonly patterns = new Map<string, InternalPattern>()\n private readonly maxPatterns: number\n private readonly maxSamplesPerPattern: number\n private droppedSignatures = 0\n\n constructor(config: ErrorTrackerConfig = {}) {\n this.maxPatterns = config.maxPatterns ?? DEFAULT_MAX_PATTERNS\n this.maxSamplesPerPattern = config.maxSamplesPerPattern ?? DEFAULT_MAX_SAMPLES_PER_PATTERN\n }\n\n /**\n * Record one error. Same `(errorType, field, message)` triple bumps the\n * existing bucket; a new triple opens a new one (subject to {@link maxPatterns}).\n *\n * `field` is optional — pass `undefined` for errors not tied to a single\n * column (e.g. parse errors at row level). Internally normalised to the\n * literal string `'GENERAL'` so it shares a bucket with other genericised\n * errors of the same type+message.\n */\n addError(\n rowNumber: number,\n errorType: string,\n message: string,\n field: string | undefined,\n rowData: ImportJsonValue,\n ): void {\n const fieldKey = field ?? 'GENERAL'\n const signature = `${errorType}:${fieldKey}:${message}`\n\n let pattern = this.patterns.get(signature)\n if (!pattern) {\n if (this.patterns.size >= this.maxPatterns) {\n this.droppedSignatures += 1\n return\n }\n pattern = {\n errorType,\n field: field ?? null,\n message,\n count: 0,\n firstOccurrence: rowNumber,\n lastOccurrence: rowNumber,\n samples: [],\n }\n this.patterns.set(signature, pattern)\n }\n\n pattern.count += 1\n pattern.lastOccurrence = rowNumber\n if (pattern.samples.length < this.maxSamplesPerPattern) {\n pattern.samples.push({ rowNumber, rowData })\n }\n }\n\n /** Total count across every pattern. Counts errors, not patterns. */\n getTotalErrorCount(): number {\n let sum = 0\n for (const p of this.patterns.values()) sum += p.count\n return sum\n }\n\n /** Number of distinct signatures retained in the map (≤ `maxPatterns`). */\n getDistinctPatternCount(): number {\n return this.patterns.size\n }\n\n /**\n * Number of NEW signatures dropped because the map was already at\n * capacity. Surfacing this in the import_run summary tells the operator\n * \"the top-N was saturated — there's a long tail you're not seeing\".\n */\n getDroppedSignatureCount(): number {\n return this.droppedSignatures\n }\n\n /**\n * Top patterns sorted by descending count, capped at `maxPatterns`.\n * Stable secondary order is insertion order (Map iteration order is\n * insertion order; Array.sort is stable in V8).\n */\n getTopPatterns(): ErrorPattern[] {\n const all = Array.from(this.patterns.values()).sort((a, b) => b.count - a.count)\n const totalErrors = all.reduce((sum, p) => sum + p.count, 0)\n return all.map((p) => ({\n errorType: p.errorType,\n field: p.field,\n message: p.message,\n count: p.count,\n firstOccurrence: p.firstOccurrence,\n lastOccurrence: p.lastOccurrence,\n samples: p.samples.slice(),\n percentage: totalErrors > 0 ? (p.count / totalErrors) * 100 : 0,\n }))\n }\n\n /**\n * Compact JSON-serialisable snapshot for `import_run.errorSummary`.\n * Aside from the patterns array, includes the totals so a reader of\n * just this column doesn't have to re-derive them.\n */\n snapshot(): ErrorTrackerSnapshot {\n return {\n totalErrors: this.getTotalErrorCount(),\n distinctPatterns: this.getDistinctPatternCount(),\n droppedSignatures: this.droppedSignatures,\n patterns: this.getTopPatterns(),\n }\n }\n}\n\nexport interface ErrorTrackerSnapshot {\n totalErrors: number\n distinctPatterns: number\n droppedSignatures: number\n patterns: ErrorPattern[]\n}\n","/**\n * One-shot importer: stream rows → transform → batched bulk-write to ES,\n * accumulating per-row errors into `ErrorTracker` and reporting progress\n * to the queue every batch.\n *\n * Per PLAN-ECOMMERCE.md PR 7 (PoC scope):\n * - **Batch size 1000.** Matches giga-test precedent. Configurable for\n * integration tests that don't want a 1k row floor.\n * - **No resumability and no automatic retries.** The `imports:run` queue\n * job is registered with `defaultRetries: 0` (see `worker.ts`) so a\n * failed handler does NOT re-enqueue itself — re-running a multi-batch\n * import against the same `import_run.id` while the previous attempt\n * may still be writing is a footgun (duplicate batches, double-counted\n * progress). Operator retries by creating a NEW `import_run` row.\n * - **No per-supplier transform plugin.** The runner takes a single\n * `RowTransform<TDoc>` from the registry and applies it to every row;\n * PR 8 may diverge but only by registering a different transform name.\n * - **Direct `bulkUpsert` into the live aliased index** (D6 alias is\n * set up by PR 4's `ensureAliasedIndex`; the importer doesn't reindex).\n *\n * Per D21 (sanctioned bulk path): this runner intentionally bypasses\n * AdminClient and entity hooks. Per-batch audit / observability lives\n * on the surrounding `import_run` row + queue progress, NOT per-row.\n */\n\nimport {\n type BulkIndexResult,\n bulkPartialUpdate,\n bulkUpsert,\n type EsClientLike,\n} from '@murumets-ee/search-elasticsearch'\nimport { ErrorTracker } from './error-tracker.js'\nimport { readFeed, type ReadFeedOptions } from './read-feed.js'\nimport type {\n DirectionalPair,\n DocPatch,\n RowTransform,\n RowWarning,\n TransformContext,\n} from './transform.js'\n\n/** Soft default; chosen to match giga-test. ES bulk requests over ~5MB get split server-side anyway. */\nexport const DEFAULT_BATCH_SIZE = 1000\n\nexport interface RunImportOptions<TDoc> {\n /** UUID of the `import_run` row driving this run. Forwarded to every transform invocation. */\n importRunId: string\n /** Operator-supplied label for the run. Forwarded to the transform context. */\n runLabel: string\n /** Opaque per-run params copied from `import_run.params`. */\n params: Record<string, unknown>\n /** Transform applied to every parsed row. */\n transform: RowTransform<TDoc>\n /** Feed reader options — file path + format (csv/tsv/xlsx) + delimiter/header config. */\n feed: ReadFeedOptions\n /** ES client (low-level shape from `@murumets-ee/search-elasticsearch`). */\n esClient: EsClientLike\n /** Index alias to write to. Per D6, callers always pass an alias, never a physical index. */\n esIndex: string\n /** Rows per `bulkUpsert` call. Default {@link DEFAULT_BATCH_SIZE}. */\n batchSize?: number\n /**\n * Callback invoked after every batch. The handler in `worker.ts`\n * forwards this to `ctx.updateProgress` for the queue UI; tests\n * inspect it directly. Synchronous + cheap so a slow callback can't\n * back-pressure the importer.\n */\n onProgress?: (progress: ImportRunProgress) => void\n /** Optional: stop processing after this many rows. Tests use it; production passes `undefined`. */\n rowLimit?: number\n /** Abort signal threaded into the underlying ES client request — cooperative cancel. */\n signal?: AbortSignal\n /** Optional ErrorTracker config (caps). Default: top-50 patterns × 5 samples. */\n errorTracker?: ErrorTracker\n /**\n * Optional separate tracker for NON-FATAL row warnings (commerce-demo PR4 —\n * `no_purchase_price`). Distinct from {@link errorTracker} so warnings never\n * inflate `totals.failed` / the error summary: a warned row is a SUCCESS whose\n * doc is indexed. Default: a fresh tracker with the same caps.\n */\n warningTracker?: ErrorTracker\n /**\n * Optional structural logger for per-batch telemetry. Receives\n * `{ batch, ms, succeeded, failed, rowsRead, rowsPerSecond }` after\n * every flush, plus a one-shot `started` and `finished` event. The\n * worker forwards `app.logger.child({ pkg: 'imports' })`; tests\n * leave it undefined.\n *\n * Why: without per-batch visibility, a stalled run looks identical\n * to \"first batch in progress\" forever — the only feedback is the\n * queue's `progress` jsonb (which writes after each batch) and the\n * eventual `succeeded`/`failed` job event. Adding this lets the\n * operator tail the worker log and immediately see whether ES is\n * rate-limiting, the transform is rejecting every row, or the\n * stream is actually progressing.\n */\n logger?: {\n info: (data: Record<string, unknown>, msg: string) => void\n warn: (data: Record<string, unknown>, msg: string) => void\n }\n}\n\n/**\n * Progress payload written to `toolkit_jobs.progress` after every batch.\n * Caps + flush rules live on the queue's `updateProgress` debounce —\n * callers don't need to throttle.\n */\nexport interface ImportRunProgress {\n rowsRead: number\n rowsSucceeded: number\n rowsFailed: number\n rowsSkipped: number\n /** Rows indexed WITH a non-fatal warning (commerce-demo PR4 — `no_purchase_price`). */\n rowsWarned: number\n batchesCompleted: number\n /** Wall-clock seconds since the runner started. */\n elapsedSeconds: number\n /** Rows / second, computed at every batch. */\n rowsPerSecond: number\n /** Distinct error patterns currently held by the tracker. Saturates at the cap. */\n distinctErrorPatterns: number\n /**\n * Total data-row count from a pre-pass scan, when the worker computed one.\n * Lets the UI render `processed / total` percent. Absent when the worker\n * skipped the count (file too large for the count budget, count failed,\n * etc.) — UI must treat it as optional.\n */\n totalRows?: number\n}\n\n/**\n * Final result returned by {@link runImport}. The handler writes these\n * onto the `import_run` row alongside the ErrorTracker snapshot.\n */\nexport interface RunImportResult {\n /** Total rows read from the file (excludes skipped empty lines). */\n rowsRead: number\n /** Rows the transform turned into a successful doc AND the ES cluster acknowledged. */\n rowsSucceeded: number\n /**\n * Rows that the transform rejected (`{ kind: 'error' }`) OR that ES\n * rejected on bulk-write (per-doc failure). Both are aggregated by\n * `errorTracker` for the import_run summary.\n */\n rowsFailed: number\n /** Rows that the transform skipped (`{ kind: 'skip' }`) — header noise, blank lines, intentional drop. */\n rowsSkipped: number\n /**\n * Rows that succeeded (doc indexed) but carried ≥1 non-fatal warning —\n * counted SEPARATELY from `rowsSucceeded`/`rowsFailed` (a warned row is also\n * counted in `rowsSucceeded`). commerce-demo PR4: `no_purchase_price`.\n */\n rowsWarned: number\n /** Number of `bulkUpsert` calls made. */\n batchesCompleted: number\n /** Final value of {@link ErrorTracker.snapshot}. */\n errors: ReturnType<ErrorTracker['snapshot']>\n /** Aggregated NON-FATAL warnings (commerce-demo PR4). Empty when no row warned. */\n warnings: ReturnType<ErrorTracker['snapshot']>\n /**\n * Directional supersession pairs harvested as a side-output (commerce-demo PR6,\n * SD007). Buffered in memory from ES-ACCEPTED rows only (same accounting as\n * warnings — a row whose doc was rejected by ES contributes no pair). Empty unless\n * a schema emits them (the `parts` schema, when a row's `superseding_code` is set).\n * The worker hands these to an injected `pairSink` AFTER the run for the commerce\n * replacement-merge engine; the runner itself never writes the consumer's tables.\n */\n pairs: readonly DirectionalPair[]\n /**\n * Doc-patches applied by the phase-2 pass (commerce-demo PR7): a `<code>*S`\n * core-fee row is not a saleable doc — it emits a {@link DocPatch} that merges its\n * deposit onto the PARENT part's `core_charge_minor`. The runner buffers these\n * during the stream (sparse) and applies them via `bulkPartialUpdate` AFTER the ES\n * pass. `patchesApplied` = targets the cluster merged; `patchesOrphaned` = patches\n * whose parent genuinely wasn't in the index (a `document_missing`/404 → an\n * `orphan_core_charge` warning). An INFRA failure (whole-batch transport error, or a\n * non-404 per-doc failure) is NOT counted as orphaned — it lands in a distinct\n * `patch_attach_failed` warning bucket so it can't masquerade as a data orphan. Zero\n * unless a schema emits patches.\n */\n patchesApplied: number\n patchesOrphaned: number\n}\n\n/**\n * Apply the runner against a feed file. Stops on rowLimit OR end-of-file\n * OR if `signal` aborts. Throws if the streaming reader / ES client\n * throws — caller (the queue handler) catches that and writes\n * `import_run.status = 'failed'` with the error message in\n * `errorSummary.fatal`.\n */\nexport async function runImport<TDoc>(options: RunImportOptions<TDoc>): Promise<RunImportResult> {\n const {\n importRunId,\n runLabel,\n params,\n transform,\n feed,\n esClient,\n esIndex,\n batchSize = DEFAULT_BATCH_SIZE,\n onProgress,\n rowLimit,\n signal,\n errorTracker = new ErrorTracker(),\n warningTracker = new ErrorTracker(),\n logger,\n } = options\n\n if (batchSize < 1) {\n throw new Error(`batchSize must be >= 1 (got ${batchSize})`)\n }\n\n const startedAt = Date.now()\n logger?.info({ importRunId, runLabel, batchSize, esIndex }, 'imports.runner: started')\n let rowsRead = 0\n let rowsSucceeded = 0\n let rowsFailed = 0\n let rowsSkipped = 0\n let rowsWarned = 0\n let batchesCompleted = 0\n\n // Side-output buffer (commerce-demo PR6, SD007): directional supersession pairs\n // accumulated from ES-ACCEPTED rows across the whole run. An array append per\n // sparse superseded row — it never blocks the `bulkUpsert` loop. Handed to the\n // injected `pairSink` by the worker AFTER the run (read-once / merge-after).\n const collectedPairs: DirectionalPair[] = []\n\n // Side-output buffer (commerce-demo PR7): doc-patches from `*S` core-fee rows —\n // each attaches a core charge onto a DIFFERENT (parent) doc. Collected off the\n // `skip` result (a `*S` row is never a saleable doc), sparse, applied in a phase-2\n // `bulkPartialUpdate` after the ES pass (below) — order-independent because ES\n // `update` is realtime by `_id`.\n const collectedPatches: DocPatch<TDoc>[] = []\n\n // Warnings + pairs ride on the pending item (with the raw row for the warning\n // sample) so they're accounted at FLUSH time — only for rows ES actually accepted.\n // A warned row is by contract a SUCCESSFUL row, so counting it at push time (before\n // the bulk response) would wrongly keep a later-ES-rejected row in rowsWarned /\n // warnings; pairs follow the same accepted-rows-only rule.\n let pending: Array<{\n id: string\n doc: TDoc\n rowNumber: number\n rowData: Record<string, string>\n warnings?: readonly RowWarning[]\n pairs?: readonly DirectionalPair[]\n }> = []\n\n const flush = async (): Promise<void> => {\n if (pending.length === 0) return\n const batch = pending\n pending = []\n const flushStartedAt = Date.now()\n let result: BulkIndexResult\n try {\n result = await bulkUpsert<TDoc>(esClient, {\n index: esIndex,\n docs: batch.map(({ id, doc }) => ({ id, doc })),\n ...(signal !== undefined && { signal }),\n })\n } catch (err) {\n // Cluster- or transport-level failure — the whole batch is\n // unaccounted for. Distinguish abort (operator-driven cancel) from\n // a real cluster failure so the errorSummary doesn't mislabel a\n // cancelled run as broken cluster connectivity.\n const isAbort =\n signal?.aborted ??\n (err instanceof Error && (err.name === 'AbortError' || /abort/i.test(err.message)))\n const errorType = isAbort ? 'aborted' : 'bulk_request_failed'\n const reason = err instanceof Error ? err.message : String(err)\n for (const { rowNumber } of batch) {\n errorTracker.addError(rowNumber, errorType, reason, undefined, null)\n }\n rowsFailed += batch.length\n throw err\n }\n\n rowsSucceeded += result.succeeded\n rowsFailed += result.failures.length\n batchesCompleted += 1\n\n const flushMs = Date.now() - flushStartedAt\n const elapsedSec = (Date.now() - startedAt) / 1000\n logger?.info(\n {\n importRunId,\n batch: batchesCompleted,\n flushMs,\n submitted: batch.length,\n succeeded: result.succeeded,\n failed: result.failures.length,\n rowsRead,\n rowsPerSecond: elapsedSec > 0 ? Math.round(rowsRead / elapsedSec) : 0,\n },\n 'imports.runner: batch flushed',\n )\n\n if (result.failures.length > 0) {\n // Map each ES failure back to its source row via `id`. The bulk\n // response order matches the request order, but ES doesn't promise\n // that; matching by `id` is the safe path. PoC volume is small\n // enough that the O(failures × batch) cost is irrelevant.\n const byId = new Map(batch.map((b) => [b.id, b.rowNumber]))\n for (const fail of result.failures) {\n const rowNumber = byId.get(fail.id) ?? -1\n errorTracker.addError(rowNumber, fail.type, fail.reason, undefined, { id: fail.id })\n }\n }\n\n // Account non-fatal warnings ONLY for rows ES accepted (commerce-demo PR4) — a\n // warned row is by contract a SUCCESSFUL row, so a row that warned AND then failed\n // the bulk write must NOT land in rowsWarned/warnings (it's already in rowsFailed).\n const failedIds = new Set(result.failures.map((f) => f.id))\n for (const item of batch) {\n if (!item.warnings || item.warnings.length === 0) continue\n if (failedIds.has(item.id)) continue\n rowsWarned += 1\n for (const w of item.warnings) {\n warningTracker.addError(item.rowNumber, w.warningType, w.message, w.field, item.rowData)\n }\n }\n\n // Buffer directional pairs for rows ES accepted (commerce-demo PR6, SD007) — same\n // accepted-rows-only rule as warnings, so a pair from a doc ES rejected is dropped.\n for (const item of batch) {\n if (!item.pairs || item.pairs.length === 0) continue\n if (failedIds.has(item.id)) continue\n collectedPairs.push(...item.pairs)\n }\n\n if (onProgress) {\n const elapsedSeconds = (Date.now() - startedAt) / 1000\n onProgress({\n rowsRead,\n rowsSucceeded,\n rowsFailed,\n rowsSkipped,\n rowsWarned,\n batchesCompleted,\n elapsedSeconds,\n rowsPerSecond: elapsedSeconds > 0 ? rowsRead / elapsedSeconds : 0,\n distinctErrorPatterns: errorTracker.getDistinctPatternCount(),\n })\n }\n }\n\n // Streaming heartbeat — sample every Nth row so the operator sees the\n // streamer is alive even when a transform-rejected file would prevent\n // any flush from firing. Without this, a feed that's 100% rejected\n // looks identical to \"stuck\" until end-of-file. Sample frequency is\n // batchSize so the cadence matches the natural batch rhythm.\n const streamSampleEvery = batchSize\n\n // First-error capture per error type — surface what's actually rejecting\n // the rows when 100% of a feed is rejected. Without this, the only signal\n // is `errorTracker.snapshot()` which only writes to import_run.errorSummary\n // at the END of the run. Mid-run we want to know NOW.\n const firstErrorByType = new Map<string, { rowNumber: number; message: string }>()\n\n for await (const { rowNumber, row } of readFeed(feed)) {\n if (signal?.aborted) break\n if (rowLimit !== undefined && rowsRead >= rowLimit) break\n rowsRead += 1\n\n if (rowsRead === 1) {\n logger?.info(\n { importRunId, rowNumber, sampleKeys: Object.keys(row) },\n 'imports.runner: STREAM_FIRST_ROW',\n )\n }\n if (rowsRead % streamSampleEvery === 0) {\n const elapsedSec = (Date.now() - startedAt) / 1000\n // Telemetry only — no row content, no error sample text.\n // PR #262 review (M-5): the prior `firstErrors:\n // Object.fromEntries(firstErrorByType)` payload included the\n // raw error message captured from the transform, which for the\n // carmaker feed embeds supplier codes + price fragments. The\n // detailed first-error breakdown is already persisted on\n // `import_run.errorSummary` via `errorTracker.snapshot()` —\n // operators inspect it there, not in the worker log.\n logger?.info(\n {\n importRunId,\n rowsRead,\n rowsSucceeded,\n rowsFailed,\n rowsSkipped,\n pending: pending.length,\n elapsedSec: Math.round(elapsedSec * 10) / 10,\n rowsPerSecond: elapsedSec > 0 ? Math.round(rowsRead / elapsedSec) : 0,\n distinctFirstErrorTypes: firstErrorByType.size,\n },\n 'imports.runner: STREAM_TICK',\n )\n }\n\n const ctx: TransformContext = { importRunId, params, runLabel, rowNumber }\n let result: Awaited<ReturnType<typeof transform>>\n try {\n result = await transform(row, ctx)\n } catch (err) {\n // A throw from the transform is a programmer error — surface it as\n // a row-level error so the run can continue. (If the bug is\n // catastrophic, the operator sees the same message repeated and\n // can stop the run.)\n const reason = err instanceof Error ? err.message : String(err)\n errorTracker.addError(rowNumber, 'transform_threw', reason, undefined, row)\n if (!firstErrorByType.has('transform_threw')) {\n firstErrorByType.set('transform_threw', { rowNumber, message: reason })\n // PR #262 review (M-5): drop the `row` payload from the\n // log line — supplier feeds carry pricing + internal codes.\n // The full row is on `import_run.errorSummary.samples` for\n // post-mortem review by operators with view permission.\n logger?.warn(\n { importRunId, rowNumber, errorType: 'transform_threw', message: reason },\n 'imports.runner: FIRST_ERROR transform_threw',\n )\n }\n rowsFailed += 1\n continue\n }\n\n if (result.kind === 'skip') {\n rowsSkipped += 1\n // A `*S` core-fee row skips the saleable index but may carry a doc-patch\n // (commerce-demo PR7) — buffer it for the phase-2 attach. Unlike pairs, a\n // patch has no ES write of its own to gate on, so it's collected here\n // unconditionally; its success is decided by the phase-2 update.\n if (result.patches && result.patches.length > 0) {\n collectedPatches.push(...result.patches)\n }\n continue\n }\n if (result.kind === 'error') {\n errorTracker.addError(\n rowNumber,\n result.error.errorType,\n result.error.message,\n result.error.field,\n row,\n )\n if (!firstErrorByType.has(result.error.errorType)) {\n firstErrorByType.set(result.error.errorType, {\n rowNumber,\n message: result.error.message,\n })\n logger?.warn(\n {\n importRunId,\n rowNumber,\n errorType: result.error.errorType,\n field: result.error.field,\n message: result.error.message,\n },\n `imports.runner: FIRST_ERROR ${result.error.errorType}`,\n )\n }\n rowsFailed += 1\n continue\n }\n\n // Non-fatal warnings ride on a SUCCESS — the doc is still indexed\n // (commerce-demo PR4: `no_purchase_price`). Carry them (+ the raw row for the\n // sample) on the pending item; the flush aggregates them into the separate\n // `warningTracker` AFTER the bulk response confirms the row was accepted, so a\n // warned-then-ES-rejected row never inflates rowsWarned / the warning summary.\n pending.push({\n id: result.id,\n doc: result.doc,\n rowNumber,\n rowData: row,\n ...(result.warnings && result.warnings.length > 0 && { warnings: result.warnings }),\n ...(result.pairs && result.pairs.length > 0 && { pairs: result.pairs }),\n })\n if (pending.length >= batchSize) {\n await flush()\n }\n }\n\n await flush()\n\n // Phase 2 (commerce-demo PR7): attach the buffered `*S` core-charge patches onto\n // their PARENT docs. Runs AFTER the whole stream so every parent that exists in\n // this run is already indexed; ES `update` is realtime by `_id`, so the merge\n // lands regardless of whether the parent streamed before or after its `*S` row\n // (order-independent). Patches are sparse (only reman parts carry `*S`), but batch\n // anyway for a giant catalogue. A patch whose parent isn't in the index comes back\n // as a per-doc failure (`document_missing_exception`) → an `orphan_core_charge`\n // warning, never a phantom doc, never a silent drop (D004). A cluster failure of\n // the whole batch is logged as a warning too — the saleable docs already indexed;\n // only the deferred core-charge attach didn't happen — so we never fail the run\n // over it.\n let patchesApplied = 0\n let patchesOrphaned = 0\n for (let i = 0; i < collectedPatches.length; i += batchSize) {\n // Operator-driven cancel BETWEEN batches: THROW rather than break, so a run\n // cancelled after phase 1 is not marked `succeeded` with core charges left\n // unattached. Mirrors phase-1's flush, which also re-throws on abort. The queue\n // handler catches this and marks the run failed.\n if (signal?.aborted) {\n throw new Error('imports: run aborted during core-charge attach (phase 2)')\n }\n const slice = collectedPatches.slice(i, i + batchSize)\n let updateResult: BulkIndexResult\n try {\n updateResult = await bulkPartialUpdate<TDoc>(esClient, {\n index: esIndex,\n updates: slice.map(({ id, doc }) => ({ id, doc })),\n ...(signal !== undefined && { signal }),\n })\n } catch (err) {\n // An abort surfacing as an AbortError from the ES client is a cancel, NOT an\n // attach failure — re-throw so the run fails (same as phase 1), never a silent\n // \"succeeded with patches unapplied\".\n const isAbort =\n signal?.aborted ??\n (err instanceof Error && (err.name === 'AbortError' || /abort/i.test(err.message)))\n if (isAbort) throw err\n // Whole-batch transport/cluster failure (ES down, timeout). The parents may\n // well exist — the attach simply didn't happen — so this is an INFRA failure,\n // NOT a data orphan: it gets the distinct `patch_attach_failed` bucket and is\n // NOT counted in patchesOrphaned. Best-effort: the saleable docs already\n // indexed, and a re-import re-attaches, so we warn + continue rather than fail.\n const reason = err instanceof Error ? err.message : String(err)\n for (const patch of slice) {\n warningTracker.addError(-1, 'patch_attach_failed', reason, patch.orphanWarning?.field, {\n target: patch.id,\n })\n }\n continue\n }\n patchesApplied += updateResult.succeeded\n if (updateResult.failures.length > 0) {\n const byId = new Map(slice.map((p) => [p.id, p]))\n for (const fail of updateResult.failures) {\n const w = byId.get(fail.id)?.orphanWarning\n // A missing target (`document_missing_exception` / 404) is a genuine data\n // orphan — the referenced parent isn't in this import (D004: warn, never a\n // phantom doc). A stable message (from the patch's orphanWarning) aggregates\n // orphans; the missing parent id rides in the sample. Any OTHER per-doc\n // failure (mapper error, etc.) is an infra/attach failure kept in a distinct\n // bucket so it can't masquerade as a data orphan.\n const isOrphan = fail.status === 404 || fail.type === 'document_missing_exception'\n if (isOrphan) {\n patchesOrphaned += 1\n warningTracker.addError(-1, w?.warningType ?? 'orphan_patch', w?.message ?? fail.reason, w?.field, {\n target: fail.id,\n })\n } else {\n warningTracker.addError(-1, 'patch_attach_failed', fail.reason, w?.field, {\n target: fail.id,\n })\n }\n }\n }\n }\n\n const totalSec = (Date.now() - startedAt) / 1000\n logger?.info(\n {\n importRunId,\n rowsRead,\n rowsSucceeded,\n rowsFailed,\n rowsSkipped,\n batchesCompleted,\n patchesApplied,\n patchesOrphaned,\n totalSec: Math.round(totalSec * 10) / 10,\n rowsPerSecond: totalSec > 0 ? Math.round(rowsRead / totalSec) : 0,\n },\n 'imports.runner: finished',\n )\n\n return {\n rowsRead,\n rowsSucceeded,\n rowsFailed,\n rowsSkipped,\n rowsWarned,\n batchesCompleted,\n errors: errorTracker.snapshot(),\n warnings: warningTracker.snapshot(),\n pairs: collectedPairs,\n patchesApplied,\n patchesOrphaned,\n }\n}\n"],"mappings":"2LA+BA,SAAgB,EAAoB,EAAiC,CACnE,IAAM,EAAO,IAAI,IACjB,IAAK,IAAM,KAAK,EACV,OAAM,GACV,IAAI,EAAK,IAAI,CAAC,EACZ,MAAU,MAAM,qBAAqB,EAAE,+CAA+C,EAExF,EAAK,IAAI,CAAC,CAF8E,CAI5F,CAuBA,eAAsB,EACpB,EACA,EAAmC,CAAC,EACnB,CACjB,GAAM,CAAE,YAAY,IAAS,EACvB,EAAS,EAAiB,CAAQ,EACpC,EAAQ,EACR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AuB,EAAQ,EAAM,eAAe,MAAO,CACrF,OAAQ,EAAM,EAChB,CAAC,EAEH,QACF,CAEA,GADA,GAAkB,EAAa,UAC3B,EAAa,SAAS,OAAS,EAAG,CACpC,IAAM,EAAO,IAAI,IAAI,EAAM,IAAK,GAAM,CAAC,EAAE,GAAI,CAAC,CAAC,CAAC,EAChD,IAAK,IAAM,KAAQ,EAAa,SAAU,CACxC,IAAM,EAAI,EAAK,IAAI,EAAK,EAAE,CAAC,EAAE,cAOZ,EAAK,SAAW,KAAO,EAAK,OAAS,8BAEpD,GAAmB,EACnB,EAAe,SAAS,GAAI,GAAG,aAAe,eAAgB,GAAG,SAAW,EAAK,OAAQ,GAAG,MAAO,CACjG,OAAQ,EAAK,EACf,CAAC,GAED,EAAe,SAAS,GAAI,sBAAuB,EAAK,OAAQ,GAAG,MAAO,CACxE,OAAQ,EAAK,EACf,CAAC,CAEL,CACF,CACF,CAEA,IAAM,GAAY,KAAK,IAAI,EAAI,GAAa,IAiB5C,OAhBA,GAAQ,KACN,CACE,cACA,WACA,gBACA,aACA,cACA,mBACA,iBACA,kBACA,SAAU,KAAK,MAAM,EAAW,EAAE,EAAI,GACtC,cAAe,EAAW,EAAI,KAAK,MAAM,EAAW,CAAQ,EAAI,CAClE,EACA,0BACF,EAEO,CACL,WACA,gBACA,aACA,cACA,aACA,mBACA,OAAQ,EAAa,SAAS,EAC9B,SAAU,EAAe,SAAS,EAClC,MAAO,EACP,iBACA,iBACF,CACF"}
@@ -1,4 +1,4 @@
1
- import { r as FilePathResolver } from "./worker-CA4jf4BA.mjs";
1
+ import { r as FilePathResolver } from "./worker-ZWkDs7gz.mjs";
2
2
 
3
3
  //#region src/storage-resolver.d.ts
4
4
  /**
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./rolldown-runtime-DK3Fl9T5.mjs";import{c as t,u as n}from"./parts-schema-RH48v5VW.mjs";import{n as r,r as i}from"./schema-registry-TK4sBFmD.mjs";import{behavior as a,defineEntity as o,field as s,searchable as c}from"@murumets-ee/entity";import{z as l}from"zod";import{sql as u}from"drizzle-orm";var d=e({IMPORT_RUN_STATUSES:()=>f,ImportRun:()=>p});const f=[`pending`,`running`,`succeeded`,`failed`,`cancelled`],p=o({name:`import_run`,fields:{label:s.text({required:!0,maxLength:255}),status:s.select({options:f,default:`pending`,indexed:!0}),filePath:s.text({required:!0,maxLength:2048}),transformName:s.text({required:!0,maxLength:128,indexed:!0}),params:s.json(),totals:s.json(),errorSummary:s.json(),warningSummary:s.json(),startedAt:s.date(),finishedAt:s.date(),queueJobId:s.text({maxLength:64,indexed:!0})},behaviors:[a.auditable(),c({fields:[`label`,`transformName`,`queueJobId`,`status`,`filePath`],projection:e=>({id:e.id,label:e.label,description:`${e.transformName} · ${e.status}`})})],scope:`global`,admin:{group:`imports`,label:`Import runs`,labelSingular:`Import run`,icon:`upload`,hideFromMenu:!0}}),m={decimal:`.`,thousands:``},h=l.array(t).max(512),g=l.strictObject({columns:l.array(l.string().min(1).max(256)).min(1).max(256),rows:l.array(l.record(l.string().max(500))).max(5)});function _(e){if(e.headerSnapshot!==void 0&&e.headerSnapshot!==null){let t=g.safeParse(e.headerSnapshot);if(!t.success)throw Error(`Invalid headerSnapshot: ${t.error.issues[0]?.message??`bad shape`}`);let n=JSON.stringify(e.headerSnapshot).length;if(n>1e5)throw Error(`headerSnapshot too large (${n} > 100000 serialized chars) — trim sample rows/cells`)}let t=typeof e.targetSchema==`string`?e.targetSchema:``,a=r(t);if(!a)throw Error(`Unknown target schema "${t}" (registered: ${i().join(`, `)})`);let o=n.safeParse(e.numberFormat);if(!o.success)throw Error(`Invalid numberFormat: ${o.error.issues[0]?.message??`bad shape`}`);let s=h.safeParse(e.columnMap);if(!s.success)throw Error(`Invalid columnMap: ${s.error.issues[0]?.message??`bad shape`}`);let c=JSON.stringify(e.columnMap).length;if(c>1e5)throw Error(`columnMap too large (${c} > 100000 serialized chars)`);let l=new Set(a.fields.map(e=>e.key)),u=new Set,d=new Set;for(let e of s.data){if(!l.has(e.target))throw Error(`Mapping target "${e.target}" is not a field of schema "${a.name}" (allowed: ${[...l].join(`, `)})`);u.has(e.target)&&d.add(e.target),u.add(e.target)}if(d.size>0)throw Error(`Mapping for schema "${a.name}" maps a target more than once: ${[...d].join(`, `)}`);let f=new Set(s.data.map(e=>e.target)),p=a.fields.filter(e=>e.required&&!f.has(e.key)).map(e=>e.key);if(p.length>0)throw Error(`Mapping for schema "${a.name}" is missing required target(s): ${p.join(`, `)}`)}const v={name:`imports:import-mapping-validation`,hooks:{beforeCreate:async e=>(_({targetSchema:e.targetSchema,numberFormat:e.numberFormat??m,columnMap:e.columnMap??[],headerSnapshot:e.headerSnapshot}),e),beforeUpdate:async(e,t,n)=>{let r=await n?.loadCurrent?.()??{};return _({targetSchema:`targetSchema`in t?t.targetSchema:r.targetSchema,numberFormat:`numberFormat`in t?t.numberFormat:r.numberFormat??m,columnMap:`columnMap`in t?t.columnMap:r.columnMap??[],headerSnapshot:`headerSnapshot`in t?t.headerSnapshot:void 0}),t}}},y=[`parts`,`discount_table`],b=[`csv`,`tsv`,`xlsx`],x=o({name:`import_mapping`,scope:`global`,fields:{supplierId:s.reference({entity:`supplier`,required:!0,indexed:!0}),brandId:s.reference({entity:`brand`,indexed:!0}),targetSchema:s.select({options:y,required:!0,indexed:!0}),name:s.text({required:!0,maxLength:255}),format:s.select({options:b,required:!0}),delimiter:s.text({maxLength:4}),hasHeader:s.boolean({default:!0}),headerRowIndex:s.number({integer:!0,min:0,default:0}),sheet:s.text({maxLength:128}),numberFormat:s.json({default:{decimal:`.`,thousands:``}}),columnMap:s.json({default:[]}),headerSnapshot:s.json(),active:s.boolean({default:!0,indexed:!0})},behaviors:[a.auditable(),c({fields:[`name`,`targetSchema`,`format`],projection:e=>({id:e.id,label:e.name,description:`${e.targetSchema} · ${e.format}`})}),{name:`imports:import-mapping-unique`,constraints:(e,t)=>{if(t!==`main`)return[];let n=e.supplierId,r=e.brandId,i=e.targetSchema;return!n||!r||!i?[]:[{kind:`uniqueIndex`,name:`uq_import_mapping_supplier_brand_schema`,on:[n,r,i],where:u`${r} IS NOT NULL`},{kind:`uniqueIndex`,name:`uq_import_mapping_supplier_schema_default`,on:[n,i],where:u`${r} IS NULL`}]}},v],admin:{group:`imports`,label:`Import mappings`,labelSingular:`Import mapping`,icon:`table`,hideFromMenu:!0}});var S=class{entries=new Map;register(e,t){if(this.entries.has(e))throw Error(`Transform "${e}" is already registered — two plugins cannot register the same transform name.`);this.entries.set(e,t)}set(e,t){this.entries.set(e,t)}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}list(){return Array.from(this.entries.keys()).sort()}clear(){this.entries.clear()}};const C=Symbol.for(`@murumets-ee/imports:transforms`);function w(){let e=globalThis,t=e[C];return t||(t=new S,e[C]=t),t}function T(e,t){w().set(e,t)}export{y as a,v as c,d,b as i,f as l,w as n,x as o,T as r,_ as s,S as t,p as u};
2
+ //# sourceMappingURL=transform-D7uHod4E.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transform-D7uHod4E.mjs","names":[],"sources":["../src/entities/import-run.ts","../src/entities/import-mapping-validation.ts","../src/entities/import-mapping.ts","../src/transform.ts"],"sourcesContent":["/**\n * ImportRun — one feed-import attempt. Tracks file, transform, status,\n * row totals, and the top error patterns surfaced by `ErrorTracker`.\n *\n * Per PLAN-ECOMMERCE.md PR 7 (PoC scope): generic plumbing entity. The\n * commerce-specific transform parameters (brandId, supplierId, supplier\n * code prefix) live in the opaque `params` JSONB so the imports package\n * stays free of commerce-domain dependencies. PR 8 wires a concrete\n * carmaker-feed transform that reads those params; PR 8a renders a\n * bespoke `/admin/commerce/imports` page over this entity's history.\n *\n * `hideFromMenu: true` because PR 7 ships only the entity + plumbing —\n * the operator-facing surface is PR 8a. The auto-EntityListPage at\n * `/admin/import_run` still resolves for direct lookups, but no sidebar\n * entry points to it.\n */\n\nimport { behavior, defineEntity, field, searchable } from '@murumets-ee/entity'\nimport type { AdminClient } from '@murumets-ee/entity/admin'\n\n/**\n * Lifecycle stages.\n *\n * - `pending` — row exists, queue job has been enqueued, worker hasn't picked it up yet.\n * - `running` — worker is streaming + bulk-writing.\n * - `succeeded` — worker finished cleanly (note: per-row failures still possible — see `totals.failed`).\n * - `failed` — worker threw and the queue marked the job dead. `errorSummary.fatal` carries the cause.\n * - `cancelled` — manual operator action via PR 8a (out of scope for PR 7).\n */\nexport const IMPORT_RUN_STATUSES = [\n 'pending',\n 'running',\n 'succeeded',\n 'failed',\n 'cancelled',\n] as const\nexport type ImportRunStatus = (typeof IMPORT_RUN_STATUSES)[number]\n\nexport const ImportRun = defineEntity({\n name: 'import_run',\n fields: {\n /** Operator-visible label, e.g. `\"MERCEDES — ME_20251027075918.txt\"`. Free-form. */\n label: field.text({ required: true, maxLength: 255 }),\n /** See {@link IMPORT_RUN_STATUSES}. */\n status: field.select({\n options: IMPORT_RUN_STATUSES,\n default: 'pending',\n indexed: true,\n }),\n /**\n * Path or storage key of the uploaded feed file. Generic string —\n * could be `/var/lumi/uploads/<id>.txt` for the local-disk PoC or an\n * S3 object key once storage adapter integration lands. The worker\n * reads this with the configured `readFeed` resolver.\n */\n filePath: field.text({ required: true, maxLength: 2048 }),\n /**\n * Name of the registered transform applied to each row. Resolved at\n * worker-dispatch time against the transform registry contributed by\n * the consumer. PoC: `'commerce:carmaker-feed'`.\n */\n transformName: field.text({ required: true, maxLength: 128, indexed: true }),\n /**\n * Opaque per-transform parameters. The carmaker transform expects\n * `{ brandId, supplierId, codePrefix? }`. Validation happens inside\n * the transform — the imports package never inspects this shape so\n * a new transform with different params doesn't require a schema\n * migration.\n */\n params: field.json(),\n /**\n * Row counters: `{ submitted, succeeded, failed, skipped, batches }`.\n * Updated by the worker as each batch completes. Final values are\n * what the operator reads; intermediate progress comes from\n * `toolkit_jobs.progress` via the queue UI.\n */\n totals: field.json(),\n /**\n * Output of `ErrorTracker.getTopPatterns(totalRows)` — the top-50\n * error signatures with up to 5 sample rows each. Empty `[]` until\n * the worker writes it on completion.\n */\n errorSummary: field.json(),\n /**\n * NON-FATAL warning patterns (commerce-demo PR4) — same\n * `ErrorTrackerSnapshot` shape as {@link errorSummary} but for advisories\n * on rows that STILL succeeded (their doc was indexed), e.g.\n * `no_purchase_price` (a part imported list-only, cost pending). Kept\n * separate from `errorSummary` so a warning never reads as a failed row.\n * Null/absent until a SUCCESSFUL run that produced warnings writes it — a\n * fatal failure (`markFailed`) abandons the run mid-stream and only sets\n * `errorSummary.fatal`, so the two summaries are not co-present.\n *\n * NOTE: because the warning aggregator reuses `ErrorTracker`, the persisted\n * JSON reuses its field names — the `totalErrors` key inside this blob is\n * really the WARNING count (and `patterns[].errorType` the warning type).\n */\n warningSummary: field.json(),\n /** Set when the worker picks up the job. */\n startedAt: field.date(),\n /** Set when the worker finishes (success OR fatal failure). */\n finishedAt: field.date(),\n /**\n * `toolkit_jobs.id` of the queue job processing this run — link\n * back so PR 8a can show live progress without a second lookup.\n */\n queueJobId: field.text({ maxLength: 64, indexed: true }),\n },\n behaviors: [\n behavior.auditable(),\n // Operator-facing search: by label (e.g. \"MERCEDES — ME_*.txt\"),\n // transform name, or queue job id. No FTS — labels are short\n // alphanumeric tags, not prose.\n searchable({\n fields: ['label', 'transformName', 'queueJobId', 'status', 'filePath'],\n projection: (row) => ({\n id: row.id as string,\n label: row.label as string,\n description: `${row.transformName} · ${row.status}`,\n }),\n }),\n ],\n scope: 'global',\n admin: {\n group: 'imports',\n label: 'Import runs',\n labelSingular: 'Import run',\n icon: 'upload',\n hideFromMenu: true,\n },\n})\n\nexport type ImportRunClient = AdminClient<typeof ImportRun.allFields>\n","/**\n * Save-time validation for `import_mapping` rows (commerce-demo phase 02 §3/§5).\n *\n * This is the R02 injection boundary realised as an entity behavior: a mapping's\n * `columnMap` may only point at fields the chosen `TargetSchema` whitelists, and a\n * mapping is incomplete unless every REQUIRED target of that schema is mapped. Both\n * checks run on EVERY write path (the PR3 wizard's generic-CRUD `POST`, a future\n * seed, a direct `AdminClient` call) — \"validate at the boundary\", not \"validate in\n * the one UI we happen to ship\".\n *\n * The transform compiler (`buildMappingTransform`) re-checks the whitelist at run\n * time, so this is defense-in-depth — but failing at SAVE gives the operator the\n * error in the wizard (where they can fix it) instead of as a per-row run failure.\n *\n * Lives next to the entity (same package) and imports the mapping engine + schema\n * registry one-directionally (engine/registry never import the entity), so no cycle.\n */\n\nimport type { Behavior } from '@murumets-ee/entity'\nimport { z } from 'zod'\nimport { mappingColumnSchema, numberFormatSchema } from '../mapping/engine.js'\nimport { getTargetSchema, listTargetSchemas } from '../mapping/schema-registry.js'\n\n/** Default applied by the `numberFormat` field — used when a create omits it (defaults run after hooks). */\nconst DEFAULT_NUMBER_FORMAT = { decimal: '.', thousands: '' } as const\n\n// Bounded, like every JSONB the entity accepts: a legitimate column map has at\n// most one entry per source column (same order of magnitude as the snapshot's\n// 256-column cap), so an arbitrarily long array is a bloat vector, not data.\nconst columnMapSchema = z.array(mappingColumnSchema).max(512)\n\n/**\n * File-less edit snapshot (#667) — header columns + a few sample rows, same\n * `{ columns, rows: [{column → cell}] }` shape as the preview endpoint's\n * response. Bounded on every axis (these are DISPLAY samples, not data):\n * a snapshot that exceeds the caps should have been trimmed/omitted by the\n * wizard, so an oversized one here is a bypass attempt or a bug — reject, and\n * additionally hard-cap the serialized size so 256-wide × max-cell rows can't\n * park ~600 KB of JSONB per mapping row.\n *\n * Strictness matters: the behavior hook persists the RAW input, so a\n * non-strict parse would let unknown top-level keys ride into JSONB unmeasured\n * (zod strips them from `snap.data`, but that stripped copy isn't what's\n * stored).\n */\nconst headerSnapshotSchema = z.strictObject({\n columns: z.array(z.string().min(1).max(256)).min(1).max(256),\n rows: z.array(z.record(z.string().max(500))).max(5),\n})\n\n/**\n * Serialized-size ceiling for a stored snapshot (defense-in-depth over the\n * per-axis caps). Measured in UTF-16 code units (`JSON.stringify(...).length`)\n * — multi-byte content can serialize up to ~3× larger on disk; the bound holds\n * either way. Mirrored client-side by `toHeaderSnapshot` in commerce-ui\n * (pinned by its round-trip test).\n */\nexport const HEADER_SNAPSHOT_MAX_CHARS = 100_000\n\n/**\n * Serialized-size ceiling for the RAW `columnMap` input. Same rationale + same\n * raw-not-parsed measurement as the snapshot ceiling: `mappingColumnSchema` is\n * shared with the RUN-TIME params parser (engine.ts), so it can't be made\n * `.strict()` without risking previously-persisted `import_run.params` — this\n * save-path-only ceiling bounds what unknown entry keys / unbounded per-entry\n * `transforms` arrays can park in JSONB without touching run-time parsing. A\n * legitimate 256-column map with transform chains serializes well under this.\n */\nexport const COLUMN_MAP_MAX_CHARS = 100_000\n\n/**\n * Throw a descriptive error unless the mapping is structurally valid AND honours its\n * schema's field whitelist + required targets. The thrown message is operator-facing\n * (surfaced verbatim by the admin CRUD route as a 4xx body).\n */\nexport function assertValidMapping(input: {\n targetSchema: unknown\n numberFormat: unknown\n columnMap: unknown\n headerSnapshot?: unknown\n}): void {\n // Snapshot is optional metadata — validate only when present (absent/null =\n // \"no file-less edit support for this row\", a valid state for pre-#667 rows).\n if (input.headerSnapshot !== undefined && input.headerSnapshot !== null) {\n const snap = headerSnapshotSchema.safeParse(input.headerSnapshot)\n if (!snap.success) {\n throw new Error(`Invalid headerSnapshot: ${snap.error.issues[0]?.message ?? 'bad shape'}`)\n }\n // Measure the RAW input, not `snap.data` — the raw value is what the write\n // path persists, and it's identical to the parse only because the schema\n // is `.strict()`. Measuring the raw keeps that true even if strictness is\n // ever relaxed.\n const serialized = JSON.stringify(input.headerSnapshot).length\n if (serialized > HEADER_SNAPSHOT_MAX_CHARS) {\n throw new Error(\n `headerSnapshot too large (${serialized} > ${HEADER_SNAPSHOT_MAX_CHARS} serialized chars) — trim sample rows/cells`,\n )\n }\n }\n const targetSchema = typeof input.targetSchema === 'string' ? input.targetSchema : ''\n const schema = getTargetSchema(targetSchema)\n if (!schema) {\n throw new Error(\n `Unknown target schema \"${targetSchema}\" (registered: ${listTargetSchemas().join(', ')})`,\n )\n }\n\n const nf = numberFormatSchema.safeParse(input.numberFormat)\n if (!nf.success) {\n throw new Error(`Invalid numberFormat: ${nf.error.issues[0]?.message ?? 'bad shape'}`)\n }\n\n const cm = columnMapSchema.safeParse(input.columnMap)\n if (!cm.success) {\n throw new Error(`Invalid columnMap: ${cm.error.issues[0]?.message ?? 'bad shape'}`)\n }\n const columnMapSerialized = JSON.stringify(input.columnMap).length\n if (columnMapSerialized > COLUMN_MAP_MAX_CHARS) {\n throw new Error(\n `columnMap too large (${columnMapSerialized} > ${COLUMN_MAP_MAX_CHARS} serialized chars)`,\n )\n }\n\n const allowed = new Set(schema.fields.map((f) => f.key))\n const seenTargets = new Set<string>()\n const dupeTargets = new Set<string>()\n for (const col of cm.data) {\n if (!allowed.has(col.target)) {\n throw new Error(\n `Mapping target \"${col.target}\" is not a field of schema \"${schema.name}\" ` +\n `(allowed: ${[...allowed].join(', ')})`,\n )\n }\n // Two source columns mapping to the SAME target collapse last-write-wins at run\n // time (`mapped[col.target] = …`), silently importing wrong data. The wizard\n // blocks this client-side; enforce it here too so a direct API call can't bypass\n // it (validate at the boundary).\n if (seenTargets.has(col.target)) dupeTargets.add(col.target)\n seenTargets.add(col.target)\n }\n if (dupeTargets.size > 0) {\n throw new Error(\n `Mapping for schema \"${schema.name}\" maps a target more than once: ${[...dupeTargets].join(', ')}`,\n )\n }\n\n const mappedTargets = new Set(cm.data.map((c) => c.target))\n const missing = schema.fields\n .filter((f) => f.required && !mappedTargets.has(f.key))\n .map((f) => f.key)\n if (missing.length > 0) {\n throw new Error(\n `Mapping for schema \"${schema.name}\" is missing required target(s): ${missing.join(', ')}`,\n )\n }\n}\n\n/**\n * Behavior wrapping {@link assertValidMapping}. Typed `Behavior<Record<never,\n * never>, …>` (NOT plain `Behavior`, whose wide `fields?` would collapse the\n * entity's inferred field types — the documented no-field-behavior gotcha).\n * Contributes a hook, no fields.\n */\nexport const importMappingValidation: Behavior<\n Record<never, never>,\n 'imports:import-mapping-validation'\n> = {\n name: 'imports:import-mapping-validation',\n hooks: {\n beforeCreate: async (data) => {\n // Field defaults run AFTER hooks, so an omitted numberFormat/columnMap is the\n // field default here — mirror those defaults so a minimal create validates\n // against the same effective config the row will hold.\n assertValidMapping({\n targetSchema: data.targetSchema,\n numberFormat: data.numberFormat ?? DEFAULT_NUMBER_FORMAT,\n columnMap: data.columnMap ?? [],\n headerSnapshot: data.headerSnapshot,\n })\n return data\n },\n beforeUpdate: async (_id, data, ctx) => {\n // A PATCH is partial — validate the EFFECTIVE config (patch overlaid on the\n // current row), so changing only `name` doesn't escape validation and changing\n // only `columnMap` is still checked against the persisted `targetSchema`.\n const current = (await ctx?.loadCurrent?.()) ?? {}\n assertValidMapping({\n targetSchema: 'targetSchema' in data ? data.targetSchema : current.targetSchema,\n numberFormat:\n 'numberFormat' in data\n ? data.numberFormat\n : (current.numberFormat ?? DEFAULT_NUMBER_FORMAT),\n columnMap: 'columnMap' in data ? data.columnMap : (current.columnMap ?? []),\n // Only the incoming value needs checking — the persisted snapshot was\n // validated when it was written.\n headerSnapshot: 'headerSnapshot' in data ? data.headerSnapshot : undefined,\n })\n return data\n },\n },\n}\n","/**\n * ImportMapping — a reusable, per-(supplier, brand) column-mapping profile that\n * drives the configurable feed-import engine (commerce-demo D005, phase 02).\n *\n * Replaces the hardcoded 14/15-column carmaker transform with operator-editable\n * mappings: which source column → which whitelisted target field, per-column\n * cleaning transforms, the file format (csv/tsv/xlsx), and the number format\n * (decimal + thousands separators — real supplier feeds vary, see R03).\n *\n * **Why this lives in `@murumets-ee/imports`, not `@murumets-ee/commerce`**\n * (D005 cycle constraint): the engine + the concrete target schemas need the\n * commerce `PartsDocument` shape, and `imports` already depends on\n * `@murumets-ee/search-elasticsearch` for it. Putting the mapping in commerce\n * would force `commerce → imports` and a forbidden import cycle. The entity\n * references the commerce `supplier` / `brand` entities **by name string**\n * (`field.reference({ entity: 'supplier' })`) — no Entity-object import, so the\n * leaf-package boundary holds.\n *\n * **Resolution** (most-specific, D002 ladder): for an upload tagged\n * `(supplier, brand)`, pick the `(supplier, brand)` mapping if present, else the\n * `(supplier, NULL)` supplier-default. See `resolveMapping()` in the engine.\n *\n * `hideFromMenu: true` — the mapping CRUD wizard lands in commerce-demo PR3. The\n * auto-EntityListPage at `/admin/import_mapping` still resolves for direct lookups\n * and for the admin-only AdminClient writes this engine relies on.\n */\n\nimport type { Behavior, SchemaFragment, SchemaTarget } from '@murumets-ee/entity'\nimport { behavior, defineEntity, field, searchable } from '@murumets-ee/entity'\nimport type { AdminClient } from '@murumets-ee/entity/admin'\nimport { sql } from 'drizzle-orm'\nimport type { PgColumn } from 'drizzle-orm/pg-core'\nimport { importMappingValidation } from './import-mapping-validation.js'\n\n/**\n * Registered target schemas a mapping may write into. This is the FIRST of two\n * whitelists (the second is each schema's target-field set) — a mapping whose\n * `targetSchema` is outside this list is rejected (deny-by-default, R02).\n */\nexport const IMPORT_MAPPING_TARGET_SCHEMAS = ['parts', 'discount_table'] as const\nexport type ImportMappingTargetSchema = (typeof IMPORT_MAPPING_TARGET_SCHEMAS)[number]\n\n/** File formats the reader dispatches on. `csv`/`tsv` → csv-parse; `xlsx` → exceljs. */\nexport const IMPORT_MAPPING_FORMATS = ['csv', 'tsv', 'xlsx'] as const\nexport type ImportMappingFormat = (typeof IMPORT_MAPPING_FORMATS)[number]\n\n/**\n * Declarative DDL: one mapping per `(supplier, brand, target_schema)`, enforced by\n * TWO PARTIAL unique indexes rather than one plain composite unique.\n *\n * Why partial: a plain `UNIQUE (supplierId, brandId, targetSchema)` treats NULL\n * `brandId` as distinct (Postgres NULL-distinct semantics), so it would allow MANY\n * supplier-default rows (`brandId IS NULL`) for the same `(supplier, schema)` —\n * ambiguous, since the engine resolves `brandId === null` as THE supplier default\n * (`resolveMapping`). Splitting it:\n * - brand-specific rows (`brandId IS NOT NULL`): unique on `(supplier, brand, schema)`;\n * - supplier-default rows (`brandId IS NULL`): unique on `(supplier, schema)`.\n *\n * The `where` predicates use raw `sql` with the live Drizzle column reference (so the\n * emitted identifier is correct regardless of casing) — `IS NULL` / `IS NOT NULL`,\n * NOT `eq(col, …)` which would serialize as an invalid bound `$1` in DDL.\n *\n * Typed `Behavior<Record<never, never>, …>` (NOT plain `Behavior`, whose wide\n * `fields?` would collapse the entity's inferred field types to `any` — the\n * documented no-field-behavior gotcha). Contributes constraints, no fields.\n */\nconst importMappingUnique: Behavior<Record<never, never>, 'imports:import-mapping-unique'> = {\n name: 'imports:import-mapping-unique',\n constraints: (table: Record<string, PgColumn>, target: SchemaTarget): SchemaFragment[] => {\n if (target !== 'main') return []\n const supplierId = table.supplierId\n const brandId = table.brandId\n const targetSchema = table.targetSchema\n // Defensive: only emit when all three columns exist.\n if (!supplierId || !brandId || !targetSchema) return []\n return [\n {\n kind: 'uniqueIndex',\n name: 'uq_import_mapping_supplier_brand_schema',\n on: [supplierId, brandId, targetSchema],\n where: sql`${brandId} IS NOT NULL`,\n },\n {\n kind: 'uniqueIndex',\n name: 'uq_import_mapping_supplier_schema_default',\n on: [supplierId, targetSchema],\n where: sql`${brandId} IS NULL`,\n },\n ]\n },\n}\n\nexport const ImportMapping = defineEntity({\n name: 'import_mapping',\n scope: 'global',\n fields: {\n /** FK to commerce `supplier` (by name string — no cross-package import). Required. */\n supplierId: field.reference({ entity: 'supplier', required: true, indexed: true }),\n /** FK to commerce `brand`. NULL = supplier default (applies to all that supplier's brands). */\n brandId: field.reference({ entity: 'brand', indexed: true }),\n /** Which registered target schema this mapping feeds — `parts` or `discount_table`. */\n targetSchema: field.select({\n options: IMPORT_MAPPING_TARGET_SCHEMAS,\n required: true,\n indexed: true,\n }),\n /** Operator-facing profile name (a supplier can have e.g. \"monthly full\" vs \"weekly delta\"). */\n name: field.text({ required: true, maxLength: 255 }),\n /** File format — drives reader dispatch + the default delimiter. */\n format: field.select({ options: IMPORT_MAPPING_FORMATS, required: true }),\n /**\n * Explicit single-char field delimiter override. When omitted, the reader\n * defaults from `format` (`csv` → `,`, `tsv` → `\\t`). Ignored for `xlsx`.\n */\n delimiter: field.text({ maxLength: 4 }),\n /** First row is the header. `false` → positional `{ \"0\": …, \"1\": … }` source keys. */\n hasHeader: field.boolean({ default: true }),\n /** 0-based header row index (header hygiene — R03 feeds have leading/trailing-space headers). */\n headerRowIndex: field.number({ integer: true, min: 0, default: 0 }),\n /** xlsx sheet name (or 1-based index as a string). Ignored for csv/tsv. */\n sheet: field.text({ maxLength: 128 }),\n /**\n * Number format for the `number` per-column transform:\n * `{ decimal: '.'|',', thousands: ''|'.'|','|' ' }`. Opaque json; validated\n * by the engine's Zod schema at consume time (matches `import_run.params`).\n */\n numberFormat: field.json({ default: { decimal: '.', thousands: '' } }),\n /**\n * Ordered column map: `[{ source, target, transforms? }]`. `source` is a\n * header name (or positional index string); `target` MUST be a field in the\n * chosen schema's whitelist (validated by the engine's Zod schema, R02\n * injection boundary); `transforms` is a bounded, enum-keyed list. Opaque\n * json on the entity; typed + validated by the engine.\n */\n columnMap: field.json({ default: [] }),\n /**\n * File-less edit snapshot (#667): `{ columns: string[], rows: [{column →\n * cell}] }` — the sample feed's header + a few sample rows, captured from\n * the wizard's preview at save time. Lets the editor re-open a saved\n * mapping WITHOUT re-uploading the (potentially huge) feed just to tweak a\n * transform. NULL on rows saved before this field existed (and when the\n * preview exceeded the size caps) — the editor falls back to the\n * upload-first flow. Staleness is benign: a source column that later\n * vanishes from the real feed is caught at run time by the 6b drift check\n * (409) / row errors, not by this snapshot. Size-capped by\n * `import-mapping-validation`.\n */\n headerSnapshot: field.json(),\n /** Inactive mappings are skipped by resolution. */\n active: field.boolean({ default: true, indexed: true }),\n },\n behaviors: [\n behavior.auditable(),\n // Operator-facing search (PR3 wizard): by profile name, schema, or format.\n // No `fts` → IlikeProvider, so this adds NO DDL (the 0036 migration is\n // unchanged). Names are short tags, not prose.\n searchable({\n fields: ['name', 'targetSchema', 'format'],\n projection: (row) => ({\n id: row.id as string,\n label: row.name as string,\n description: `${row.targetSchema} · ${row.format}`,\n }),\n }),\n importMappingUnique,\n // Save-time whitelist + required-target validation (R02 injection boundary).\n importMappingValidation,\n ],\n admin: {\n group: 'imports',\n label: 'Import mappings',\n labelSingular: 'Import mapping',\n icon: 'table',\n hideFromMenu: true,\n },\n})\n\nexport type ImportMappingClient = AdminClient<typeof ImportMapping.allFields>\n","/**\n * Per-feed transform plugin interface (PLAN-ECOMMERCE.md PR 7 / D14).\n *\n * The streaming reader reads raw rows out of the file (column key →\n * string). The transform turns one row into a typed `OutputDoc` ready\n * for the bulk-write surface (PoC: `PartsDocument` for the parts ES\n * index). The transform is what makes a generic feed-importer\n * commerce-aware — without it, the importer has no opinion on what a\n * row \"means\".\n *\n * Why an interface, not a function:\n * - The transform may need to reject a row (`RowSkip`) without that\n * counting as an error in `ErrorTracker` — e.g. blank lines, header\n * rows mistakenly retained, or \"this is a replacement-code marker\n * row, handled out-of-band\" decisions.\n * - The transform may need to fail a row (`RowError`) with a typed\n * error class so `ErrorTracker` collapses them by `errorType`.\n * - The transform may need access to the run-level params (brand /\n * supplier IDs, code prefix, batch ID) without those being\n * re-derived per row.\n *\n * PR 7 ships only the interface + a registry. PR 8 ships the first\n * concrete carmaker-feed transform.\n */\n\n/** Identifies which transform a registered handler implements. Stable across deploys. */\nexport type TransformName = string\n\n/** Per-run context provided to every row call. Kept narrow on purpose. */\nexport interface TransformContext {\n /** UUID of the `import_run` row. Forward to the output doc as `import_batch_id` for source attribution (D20). */\n importRunId: string\n /** Opaque per-run params copied from `import_run.params`. The transform validates the shape it expects. */\n params: Record<string, unknown>\n /** Operator-supplied label, useful for logging / debugging. */\n runLabel: string\n /** 1-based row number across the whole feed (header counts as row 0). Forward to `RowError.rowNumber`. */\n rowNumber: number\n}\n\n/**\n * A directional supersession pair harvested from a row as a SIDE-OUTPUT\n * (commerce-demo PR6, SD007): `from` (the row's own code) is superseded by `to`\n * (the row's `superseding_code`), so `to` is the newer/current code. Both are\n * already NORMALIZED (same normalization as the doc's `code_normalized`) so a\n * downstream equivalence-group merge collides codes correctly.\n *\n * This is PURE DATA. The runner buffers pairs in memory during the single ES pass\n * (an array append — it never blocks the `bulkUpsert` loop) and hands the buffer to\n * an INJECTED post-run sink (the commerce replacement-merge engine). The\n * `@murumets-ee/imports` leaf never writes the consumer's Postgres tables itself —\n * the boundary holds because the sink is injected, not imported.\n */\nexport interface DirectionalPair {\n /** The superseded (older) normalized code — the row's own `code_normalized`. */\n from: string\n /** The superseding (newer / current) normalized code — normalized `superseding_code`. */\n to: string\n}\n\n/**\n * A partial-document PATCH emitted as a side-output (commerce-demo PR7): the row\n * itself produces no saleable doc, but it carries a partial update that must land\n * on a DIFFERENT doc — identified by `id` (the same `<code_normalized>__<supplier>`\n * key the parts sink uses). The runner buffers these during the single stream and,\n * AFTER the ES pass, applies them via a phase-2 `bulkPartialUpdate` (an ES `update`\n * merge, realtime by `_id` → order-independent). A patch whose target doesn't exist\n * surfaces as an `orphan_*` warning, never a phantom doc.\n *\n * Canonical use: a `<code>*S` core-fee row (D004) attaches its deposit to the parent\n * part's `core_charge_minor`. Kept GENERIC (`Partial<TDoc>`) so the runner never\n * imports a schema-specific doc type — the same leaf-clean shape as {@link DirectionalPair}.\n */\nexport interface DocPatch<TDoc> {\n /** The `_id` of the doc to merge into (a different row's doc than the one that emitted this). */\n id: string\n /** The partial fields to merge onto that doc. */\n doc: Partial<TDoc>\n /**\n * The warning to record if the target `id` isn't in the index (the phase-2\n * update 404s). The runner detects the orphan (it can't be known at buildRow\n * time — the parent may stream later) but the SCHEMA owns the bucket name +\n * message, so this rides on the patch. Absent → a generic `orphan_patch`\n * fallback. For `*S` core-fee rows the parts schema sets `orphan_core_charge`\n * (D004: warn, never silently drop).\n */\n orphanWarning?: RowWarning\n}\n\n/**\n * One of: a successful `OutputDoc` keyed by a stable `id`, an\n * intentional `skip` (counted in `totals.skipped`), or a row-level\n * error (counted in `totals.failed` AND aggregated by `ErrorTracker`).\n *\n * The `id` field on `success` is used as the bulk-upsert primary key\n * (`_id` in ES). Per D4 the parts index uses\n * `<code_normalized>__<supplier_id>` so a re-run of the same feed\n * idempotently overwrites instead of duplicating.\n *\n * **`warnings` on `success`** (commerce-demo PR4): a row can be a valid,\n * indexable doc AND still carry a non-fatal advisory — e.g. a part imported\n * with `list_price` but no resolvable purchase cost (`no_purchase_price`,\n * phase 03 §5). The runner indexes the doc (it's a success, NOT a failure)\n * and separately aggregates the warnings into a `warningSummary`, so the\n * operator sees \"120 rows cost-pending\" without those rows being dropped or\n * mis-counted as failures. Empty/absent `warnings` is the common case.\n *\n * **`pairs` on `success`** (commerce-demo PR6, SD007): a row can ALSO carry\n * directional supersession {@link DirectionalPair}s as a side-output — the `parts`\n * schema emits one when a row's `superseding_code` is present (a SPARSE column on a\n * full manufacturer catalogue, so most rows emit none). The runner buffers these\n * from ES-accepted rows and returns them for the injected `pairSink`. Empty/absent\n * `pairs` is the common case.\n *\n * **`patches` on `skip`** (commerce-demo PR7): a `<code>*S` core-fee row is NOT a\n * saleable doc (so it `skip`s the main index), but it carries a {@link DocPatch}\n * side-output that attaches its deposit to the PARENT part's `core_charge_minor`.\n * The runner buffers these (sparse — only reman parts carry `*S`) and applies them\n * in a phase-2 `bulkPartialUpdate` AFTER the stream; an unresolved parent becomes an\n * `orphan_core_charge` warning (D004). Empty/absent `patches` is the common case.\n */\nexport type RowResult<TDoc> =\n | {\n kind: 'success'\n id: string\n doc: TDoc\n warnings?: readonly RowWarning[]\n pairs?: readonly DirectionalPair[]\n }\n | { kind: 'skip'; reason: string; patches?: readonly DocPatch<TDoc>[] }\n | { kind: 'error'; error: RowError }\n\n/** Row-level error. The aggregator uses `(errorType, field, message)` as the dedup signature. */\nexport interface RowError {\n errorType: string\n message: string\n field?: string | undefined\n}\n\n/**\n * A non-fatal advisory attached to a SUCCESSFUL row (the doc is still\n * indexed). Same `(warningType, field, message)` dedup signature shape as\n * {@link RowError} so the runner can aggregate warnings through an\n * `ErrorTracker` instance into `import_run.warningSummary`.\n */\nexport interface RowWarning {\n warningType: string\n message: string\n field?: string | undefined\n}\n\n/**\n * The contract every per-feed transform implements. Pure function of\n * `(row, ctx) → RowResult` — no I/O. Async only because the future\n * carmaker variant might consult an in-memory taxonomy lookup.\n */\nexport interface RowTransform<TDoc> {\n (rawRow: Record<string, string>, ctx: TransformContext): Promise<RowResult<TDoc>>\n}\n\n/**\n * Holds the registered transforms for the current process. Each plugin\n * that ships a transform calls {@link TransformRegistry.register} from\n * its `init` hook.\n *\n * Per CLAUDE.md \"Whitelist, don't blacklist\": the worker dispatches\n * by `import_run.transformName` against this registry. An unregistered\n * name fails the run rather than running with a default transform.\n *\n * **Production callers MUST go through {@link getTransformRegistry}**, not\n * `new TransformRegistry()`. The constructor is exposed only so tests\n * (and rare custom-worker embeds) can build an isolated instance and\n * inject it into {@link createRunImportHandler} directly. Two `new`\n * instances do NOT share state — registering a transform on one will\n * NOT make it visible to a worker resolving against the other. The\n * package's queue handler (registered by `imports()` plugin) always\n * resolves against the singleton.\n */\nexport class TransformRegistry {\n private readonly entries = new Map<TransformName, RowTransform<unknown>>()\n\n /**\n * Register a transform under a stable name. Throws on duplicate\n * names so two plugins can't silently overwrite each other (same\n * fail-loud collision protection that `combineAdminRoutes` enforces\n * for duplicate `(prefix, method, path)` route registrations).\n */\n register<TDoc>(name: TransformName, transform: RowTransform<TDoc>): void {\n if (this.entries.has(name)) {\n throw new Error(\n `Transform \"${name}\" is already registered — two plugins cannot register the same transform name.`,\n )\n }\n this.entries.set(name, transform as RowTransform<unknown>)\n }\n\n /**\n * Last-wins registration — overwrites an existing entry instead of\n * throwing. The {@link registerImportTransform} consumer-app path uses\n * this (same semantics as `@murumets-ee/queue/client`'s `registerJob`):\n * under dev HMR a re-evaluated consumer module re-registers against the\n * surviving globalThis registry, and an overwrite picks up the edited\n * function where a skip-or-throw would keep dispatching the stale one\n * (the #186 staleness class). Plugin built-ins keep using\n * {@link register} behind `has()` guards so genuine cross-plugin name\n * collisions still fail loud.\n */\n set<TDoc>(name: TransformName, transform: RowTransform<TDoc>): void {\n this.entries.set(name, transform as RowTransform<unknown>)\n }\n\n /** Look up a transform by name. Returns `undefined` if no plugin has registered one. */\n get(name: TransformName): RowTransform<unknown> | undefined {\n return this.entries.get(name)\n }\n\n /** True iff a transform is registered for the given name. */\n has(name: TransformName): boolean {\n return this.entries.has(name)\n }\n\n /** All registered names. Useful for the admin Catalog tab and for tests. */\n list(): TransformName[] {\n return Array.from(this.entries.keys()).sort()\n }\n\n /** Drop all registrations. Tests only. */\n clear(): void {\n this.entries.clear()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Process-global singleton (mirrors `@murumets-ee/queue`'s handler registry).\n// ---------------------------------------------------------------------------\n//\n// Why a singleton: registrations (the plugin's built-ins at init, plus\n// any consumer-app custom transforms) and the worker's `get` happen in\n// different modules that Next.js HMR / Turbopack can re-evaluate\n// independently. Holding the registry on `globalThis` via `Symbol.for`\n// means the same `Map` instance is shared across module evaluations —\n// `register` and `get` see each other regardless of evaluation order.\n// Same fix shape as the queue's handler-registry HMR bug (#186).\n\nconst REGISTRY_KEY = Symbol.for('@murumets-ee/imports:transforms')\n\ninterface GlobalThisWithTransforms {\n [REGISTRY_KEY]?: TransformRegistry\n}\n\n/** Returns the singleton registry, creating it on first access. */\nexport function getTransformRegistry(): TransformRegistry {\n const g = globalThis as GlobalThisWithTransforms\n let reg = g[REGISTRY_KEY]\n if (!reg) {\n reg = new TransformRegistry()\n g[REGISTRY_KEY] = reg\n }\n return reg\n}\n\n/**\n * Convenience wrapper around the singleton registry for CONSUMER apps that\n * ship their own custom transforms — same semantics as\n * `@murumets-ee/queue/client`'s `registerJob`: **last-wins overwrite, never\n * throws on a duplicate name.** Two reasons, both load-bearing:\n *\n * 1. **Upgrade safety.** The `imports()` plugin registers the built-in\n * transforms (`commerce:mapping`, `commerce:carmaker-feed`) during\n * `createApp`, and older hand-wired apps — following this module's\n * previous docs — call this helper UNGUARDED from their bootstrap right\n * after. A duplicate-name throw here would crash boot on the very\n * `pnpm up` upgrade that ships plugin-owned registration; re-registering\n * the identical stock function is a harmless overwrite instead.\n * 2. **HMR freshness.** The registry lives on globalThis and survives dev\n * module re-evaluation; an edited consumer transform re-registers on the\n * next eval and the overwrite picks up the edit — a skip would keep\n * dispatching the stale function forever (the #186 staleness class).\n *\n * Side effect worth knowing: an app can deliberately override a built-in\n * name (its bootstrap runs after plugin init, so last-wins = app wins).\n * Genuine collision protection (two plugins claiming one name) stays on the\n * raw `TransformRegistry.register`.\n */\nexport function registerImportTransform<TDoc>(\n name: TransformName,\n transform: RowTransform<TDoc>,\n): void {\n getTransformRegistry().set(name, transform)\n}\n"],"mappings":"gXA6BA,MAAa,EAAsB,CACjC,UACA,UACA,YACA,SACA,WACF,EAGa,EAAY,EAAa,CACpC,KAAM,aACN,OAAQ,CAEN,MAAO,EAAM,KAAK,CAAE,SAAU,GAAM,UAAW,GAAI,CAAC,EAEpD,OAAQ,EAAM,OAAO,CACnB,QAAS,EACT,QAAS,UACT,QAAS,EACX,CAAC,EAOD,SAAU,EAAM,KAAK,CAAE,SAAU,GAAM,UAAW,IAAK,CAAC,EAMxD,cAAe,EAAM,KAAK,CAAE,SAAU,GAAM,UAAW,IAAK,QAAS,EAAK,CAAC,EAQ3E,OAAQ,EAAM,KAAK,EAOnB,OAAQ,EAAM,KAAK,EAMnB,aAAc,EAAM,KAAK,EAezB,eAAgB,EAAM,KAAK,EAE3B,UAAW,EAAM,KAAK,EAEtB,WAAY,EAAM,KAAK,EAKvB,WAAY,EAAM,KAAK,CAAE,UAAW,GAAI,QAAS,EAAK,CAAC,CACzD,EACA,UAAW,CACT,EAAS,UAAU,EAInB,EAAW,CACT,OAAQ,CAAC,QAAS,gBAAiB,aAAc,SAAU,UAAU,EACrE,WAAa,IAAS,CACpB,GAAI,EAAI,GACR,MAAO,EAAI,MACX,YAAa,GAAG,EAAI,cAAc,KAAK,EAAI,QAC7C,EACF,CAAC,CACH,EACA,MAAO,SACP,MAAO,CACL,MAAO,UACP,MAAO,cACP,cAAe,aACf,KAAM,SACN,aAAc,EAChB,CACF,CAAC,EC1GK,EAAwB,CAAE,QAAS,IAAK,UAA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ACM,CACN,EAAqB,CAAC,CAAC,IAAI,EAAM,CAAS,CAC5C"}
@@ -1,7 +1,7 @@
1
1
  import { c as TransformRegistry, i as RowTransform, t as DirectionalPair } from "./transform-CulePAbJ.mjs";
2
+ import { Logger } from "@murumets-ee/core";
2
3
  import { z } from "zod";
3
4
  import { EsClientLike } from "@murumets-ee/search-elasticsearch";
4
- import { Logger } from "@murumets-ee/core";
5
5
  import { JobDefinition, QueueTerminalNotifier } from "@murumets-ee/queue/client";
6
6
  import { AdminClient } from "@murumets-ee/entity/admin";
7
7
 
@@ -100,113 +100,6 @@ declare const ImportRun: import("@murumets-ee/entity").Entity<{
100
100
  }, "import_run", [import("@murumets-ee/entity").Behavior<import("@murumets-ee/entity").AuditableFields, string>, import("@murumets-ee/entity").SearchableBehavior]>;
101
101
  type ImportRunClient = AdminClient<typeof ImportRun.allFields>;
102
102
  //#endregion
103
- //#region src/error-tracker.d.ts
104
- /**
105
- * Aggregates per-row errors into top-N pattern buckets so a feed of 1M
106
- * malformed rows surfaces as a handful of actionable signatures rather
107
- * than a million identical strings.
108
- *
109
- * Lifted from giga-test (`backend/src/workers/csv-importer.ts`) and
110
- * generalized:
111
- * - Configurable caps so the importer can tune memory bounds per run.
112
- * - Pure data — no logging side effects, no I/O.
113
- * - JSON-serialisable output via {@link ErrorTracker.snapshot} for the
114
- * `import_run.errorSummary` column.
115
- *
116
- * Pattern signature shape: `${errorType}:${field || 'GENERAL'}:${message}`.
117
- * Same `errorType + field + message` collapses to one bucket; differing
118
- * messages stay separate. This is intentional: a parser error on column
119
- * `NetPrice/Discount` ("invalid number 'NA,5'") and the same on column
120
- * `GrossPrice` are operationally distinct even if the parser is the same.
121
- *
122
- * Memory bounds: the patterns map is capped at `maxPatterns`. Once full,
123
- * additional NEW signatures are dropped — known patterns keep accumulating
124
- * counts. This is the "top-N most common" model: rare-but-novel errors
125
- * past the cap are invisible, but the cap protects against a runaway
126
- * adversarial feed exploding the map. Sample arrays are independently
127
- * capped at `maxSamplesPerPattern`.
128
- */
129
- /**
130
- * Recursively-defined JSON-serialisable value. Mirrors the shape of
131
- * `JsonValue` in `@murumets-ee/entity` without taking a dependency on
132
- * that package — error-tracker is otherwise standalone, and the
133
- * `ImportRun.errorSummary` JSONB column accepts anything in this shape.
134
- */
135
- type ImportJsonValue = string | number | boolean | null | ImportJsonValue[] | {
136
- [key: string]: ImportJsonValue;
137
- };
138
- /** One sample row attached to a pattern. `rowData` is the originally-parsed row. */
139
- interface ErrorSample {
140
- rowNumber: number;
141
- rowData: ImportJsonValue;
142
- }
143
- /** Public shape of an aggregated pattern as returned by {@link ErrorTracker.getTopPatterns}. */
144
- interface ErrorPattern {
145
- errorType: string;
146
- field: string | null;
147
- message: string;
148
- count: number;
149
- firstOccurrence: number;
150
- lastOccurrence: number;
151
- samples: ReadonlyArray<ErrorSample>;
152
- /** `count / totalErrors`, scaled 0..100. `0` when there are zero errors total. */
153
- percentage: number;
154
- }
155
- interface ErrorTrackerConfig {
156
- /** Hard cap on distinct signatures. Defaults to 50. New signatures past the cap are dropped. */
157
- maxPatterns?: number;
158
- /** Hard cap on samples retained per pattern. Defaults to 5. Excess samples are dropped. */
159
- maxSamplesPerPattern?: number;
160
- }
161
- /** Default caps — match giga-test for compatibility. */
162
- declare const DEFAULT_MAX_PATTERNS = 50;
163
- declare const DEFAULT_MAX_SAMPLES_PER_PATTERN = 5;
164
- declare class ErrorTracker {
165
- private readonly patterns;
166
- private readonly maxPatterns;
167
- private readonly maxSamplesPerPattern;
168
- private droppedSignatures;
169
- constructor(config?: ErrorTrackerConfig);
170
- /**
171
- * Record one error. Same `(errorType, field, message)` triple bumps the
172
- * existing bucket; a new triple opens a new one (subject to {@link maxPatterns}).
173
- *
174
- * `field` is optional — pass `undefined` for errors not tied to a single
175
- * column (e.g. parse errors at row level). Internally normalised to the
176
- * literal string `'GENERAL'` so it shares a bucket with other genericised
177
- * errors of the same type+message.
178
- */
179
- addError(rowNumber: number, errorType: string, message: string, field: string | undefined, rowData: ImportJsonValue): void;
180
- /** Total count across every pattern. Counts errors, not patterns. */
181
- getTotalErrorCount(): number;
182
- /** Number of distinct signatures retained in the map (≤ `maxPatterns`). */
183
- getDistinctPatternCount(): number;
184
- /**
185
- * Number of NEW signatures dropped because the map was already at
186
- * capacity. Surfacing this in the import_run summary tells the operator
187
- * "the top-N was saturated — there's a long tail you're not seeing".
188
- */
189
- getDroppedSignatureCount(): number;
190
- /**
191
- * Top patterns sorted by descending count, capped at `maxPatterns`.
192
- * Stable secondary order is insertion order (Map iteration order is
193
- * insertion order; Array.sort is stable in V8).
194
- */
195
- getTopPatterns(): ErrorPattern[];
196
- /**
197
- * Compact JSON-serialisable snapshot for `import_run.errorSummary`.
198
- * Aside from the patterns array, includes the totals so a reader of
199
- * just this column doesn't have to re-derive them.
200
- */
201
- snapshot(): ErrorTrackerSnapshot;
202
- }
203
- interface ErrorTrackerSnapshot {
204
- totalErrors: number;
205
- distinctPatterns: number;
206
- droppedSignatures: number;
207
- patterns: ErrorPattern[];
208
- }
209
- //#endregion
210
103
  //#region src/streaming.d.ts
211
104
  /**
212
105
  * Pre-pass: count data rows in a delimited file (excluding the header
@@ -334,6 +227,21 @@ declare const feedReaderConfigSchema: z.ZodObject<{
334
227
  sheet?: string | undefined;
335
228
  }>;
336
229
  type FeedReaderConfig = z.infer<typeof feedReaderConfigSchema>;
230
+ /**
231
+ * Rehydrate the reader config a run persisted in `import_run.params.feed`.
232
+ *
233
+ * ONE implementation, because two would drift and drift here is silent: the
234
+ * worker uses it to decide how to READ a feed, and the #842 audit uses it to
235
+ * re-read the same file the same way. An audit that rehydrates differently from
236
+ * the run it is auditing invents corruption, or misses it.
237
+ *
238
+ * ABSENT means "the carmaker default", i.e. tab-delimited, which is what an
239
+ * empty config parses to — so a non-object `params`, or `params` with no
240
+ * `feed`, is a real answer rather than a gap. A PRESENT `feed` is validated
241
+ * whatever its shape: a scalar or an array there is a malformed persisted blob,
242
+ * and reading it as "no config" would silently import an xlsx run as tsv.
243
+ */
244
+ declare function readPersistedFeedConfig(params: unknown): ReturnType<typeof feedReaderConfigSchema.safeParse>;
337
245
  interface ReadFeedOptions {
338
246
  /** Path to the file on local disk. */
339
247
  filePath: string;
@@ -357,6 +265,113 @@ interface ReadFeedOptions {
357
265
  /** Stream a feed file's data rows, dispatching on `format`. */
358
266
  declare function readFeed(options: ReadFeedOptions): AsyncIterable<StreamFeedRow>;
359
267
  //#endregion
268
+ //#region src/error-tracker.d.ts
269
+ /**
270
+ * Aggregates per-row errors into top-N pattern buckets so a feed of 1M
271
+ * malformed rows surfaces as a handful of actionable signatures rather
272
+ * than a million identical strings.
273
+ *
274
+ * Lifted from giga-test (`backend/src/workers/csv-importer.ts`) and
275
+ * generalized:
276
+ * - Configurable caps so the importer can tune memory bounds per run.
277
+ * - Pure data — no logging side effects, no I/O.
278
+ * - JSON-serialisable output via {@link ErrorTracker.snapshot} for the
279
+ * `import_run.errorSummary` column.
280
+ *
281
+ * Pattern signature shape: `${errorType}:${field || 'GENERAL'}:${message}`.
282
+ * Same `errorType + field + message` collapses to one bucket; differing
283
+ * messages stay separate. This is intentional: a parser error on column
284
+ * `NetPrice/Discount` ("invalid number 'NA,5'") and the same on column
285
+ * `GrossPrice` are operationally distinct even if the parser is the same.
286
+ *
287
+ * Memory bounds: the patterns map is capped at `maxPatterns`. Once full,
288
+ * additional NEW signatures are dropped — known patterns keep accumulating
289
+ * counts. This is the "top-N most common" model: rare-but-novel errors
290
+ * past the cap are invisible, but the cap protects against a runaway
291
+ * adversarial feed exploding the map. Sample arrays are independently
292
+ * capped at `maxSamplesPerPattern`.
293
+ */
294
+ /**
295
+ * Recursively-defined JSON-serialisable value. Mirrors the shape of
296
+ * `JsonValue` in `@murumets-ee/entity` without taking a dependency on
297
+ * that package — error-tracker is otherwise standalone, and the
298
+ * `ImportRun.errorSummary` JSONB column accepts anything in this shape.
299
+ */
300
+ type ImportJsonValue = string | number | boolean | null | ImportJsonValue[] | {
301
+ [key: string]: ImportJsonValue;
302
+ };
303
+ /** One sample row attached to a pattern. `rowData` is the originally-parsed row. */
304
+ interface ErrorSample {
305
+ rowNumber: number;
306
+ rowData: ImportJsonValue;
307
+ }
308
+ /** Public shape of an aggregated pattern as returned by {@link ErrorTracker.getTopPatterns}. */
309
+ interface ErrorPattern {
310
+ errorType: string;
311
+ field: string | null;
312
+ message: string;
313
+ count: number;
314
+ firstOccurrence: number;
315
+ lastOccurrence: number;
316
+ samples: ReadonlyArray<ErrorSample>;
317
+ /** `count / totalErrors`, scaled 0..100. `0` when there are zero errors total. */
318
+ percentage: number;
319
+ }
320
+ interface ErrorTrackerConfig {
321
+ /** Hard cap on distinct signatures. Defaults to 50. New signatures past the cap are dropped. */
322
+ maxPatterns?: number;
323
+ /** Hard cap on samples retained per pattern. Defaults to 5. Excess samples are dropped. */
324
+ maxSamplesPerPattern?: number;
325
+ }
326
+ /** Default caps — match giga-test for compatibility. */
327
+ declare const DEFAULT_MAX_PATTERNS = 50;
328
+ declare const DEFAULT_MAX_SAMPLES_PER_PATTERN = 5;
329
+ declare class ErrorTracker {
330
+ private readonly patterns;
331
+ private readonly maxPatterns;
332
+ private readonly maxSamplesPerPattern;
333
+ private droppedSignatures;
334
+ constructor(config?: ErrorTrackerConfig);
335
+ /**
336
+ * Record one error. Same `(errorType, field, message)` triple bumps the
337
+ * existing bucket; a new triple opens a new one (subject to {@link maxPatterns}).
338
+ *
339
+ * `field` is optional — pass `undefined` for errors not tied to a single
340
+ * column (e.g. parse errors at row level). Internally normalised to the
341
+ * literal string `'GENERAL'` so it shares a bucket with other genericised
342
+ * errors of the same type+message.
343
+ */
344
+ addError(rowNumber: number, errorType: string, message: string, field: string | undefined, rowData: ImportJsonValue): void;
345
+ /** Total count across every pattern. Counts errors, not patterns. */
346
+ getTotalErrorCount(): number;
347
+ /** Number of distinct signatures retained in the map (≤ `maxPatterns`). */
348
+ getDistinctPatternCount(): number;
349
+ /**
350
+ * Number of NEW signatures dropped because the map was already at
351
+ * capacity. Surfacing this in the import_run summary tells the operator
352
+ * "the top-N was saturated — there's a long tail you're not seeing".
353
+ */
354
+ getDroppedSignatureCount(): number;
355
+ /**
356
+ * Top patterns sorted by descending count, capped at `maxPatterns`.
357
+ * Stable secondary order is insertion order (Map iteration order is
358
+ * insertion order; Array.sort is stable in V8).
359
+ */
360
+ getTopPatterns(): ErrorPattern[];
361
+ /**
362
+ * Compact JSON-serialisable snapshot for `import_run.errorSummary`.
363
+ * Aside from the patterns array, includes the totals so a reader of
364
+ * just this column doesn't have to re-derive them.
365
+ */
366
+ snapshot(): ErrorTrackerSnapshot;
367
+ }
368
+ interface ErrorTrackerSnapshot {
369
+ totalErrors: number;
370
+ distinctPatterns: number;
371
+ droppedSignatures: number;
372
+ patterns: ErrorPattern[];
373
+ }
374
+ //#endregion
360
375
  //#region src/runner.d.ts
361
376
  /** Soft default; chosen to match giga-test. ES bulk requests over ~5MB get split server-side anyway. */
362
377
  declare const DEFAULT_BATCH_SIZE = 1000;
@@ -720,5 +735,5 @@ interface ImportsRunDeadListenerConfig {
720
735
  */
721
736
  declare function createImportsRunDeadListener(config: ImportsRunDeadListenerConfig): QueueTerminalNotifier;
722
737
  //#endregion
723
- export { ErrorSample as A, StreamFeedOptions as C, DEFAULT_MAX_PATTERNS as D, streamFeed as E, ImportRunClient as F, ImportRunStatus as I, ErrorTrackerConfig as M, IMPORT_RUN_STATUSES as N, DEFAULT_MAX_SAMPLES_PER_PATTERN as O, ImportRun as P, readFeed as S, countDataRows as T, RunImportResult as _, ImportsRunJobContext as a, ReadFeedOptions as b, PairSinkContext as c, createRunImportHandler as d, importsRunJob as f, RunImportOptions as g, ImportRunProgress as h, ImportsRunDeadListenerConfig as i, ErrorTracker as j, ErrorPattern as k, RunImportHandlerConfig as l, DEFAULT_BATCH_SIZE as m, EsClientResolver as n, ImportsRunJobPayload as o, importsRunJobPayloadSchema as p, FilePathResolver as r, PairSink as s, EnsureIndexResolver as t, createImportsRunDeadListener as u, runImport as v, StreamFeedRow as w, feedReaderConfigSchema as x, FeedReaderConfig as y };
724
- //# sourceMappingURL=worker-CA4jf4BA.d.mts.map
738
+ export { StreamFeedOptions as A, ErrorTracker as C, feedReaderConfigSchema as D, ReadFeedOptions as E, ImportRun as F, ImportRunClient as I, ImportRunStatus as L, countDataRows as M, streamFeed as N, readFeed as O, IMPORT_RUN_STATUSES as P, ErrorSample as S, FeedReaderConfig as T, RunImportResult as _, ImportsRunJobContext as a, DEFAULT_MAX_SAMPLES_PER_PATTERN as b, PairSinkContext as c, createRunImportHandler as d, importsRunJob as f, RunImportOptions as g, ImportRunProgress as h, ImportsRunDeadListenerConfig as i, StreamFeedRow as j, readPersistedFeedConfig as k, RunImportHandlerConfig as l, DEFAULT_BATCH_SIZE as m, EsClientResolver as n, ImportsRunJobPayload as o, importsRunJobPayloadSchema as p, FilePathResolver as r, PairSink as s, EnsureIndexResolver as t, createImportsRunDeadListener as u, runImport as v, ErrorTrackerConfig as w, ErrorPattern as x, DEFAULT_MAX_PATTERNS as y };
739
+ //# sourceMappingURL=worker-ZWkDs7gz.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-ZWkDs7gz.d.mts","names":[],"sources":["../src/entities/import-run.ts","../src/streaming.ts","../src/read-feed.ts","../src/error-tracker.ts","../src/runner.ts","../src/worker.ts"],"mappings":";;;;;;;;AAoCyD;AAEzD;;;;;;;;AAFyD,cAP5C,mBAAA;AAAA,KAOD,eAAA,WAA0B,mBAAmB;AAAA,cAE5C,SAAA,gCAAS,MAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA8FV;;;;;;;;AAAwD;;;;ACrEpE;;8GAGU;yGADG;;EACV;;AAAO;AAkBV;;;;;;KDgDY,eAAA,GAAkB,WAAW,QAAQ,SAAA,CAAU,SAAA;;;;;;;;;;;;;;;;;;;;;;;;iBCrErC,aAAA,CACpB,QAAA,UACA,OAAA;EAAW,SAAA;AAAA,IACV,OAAO;AAAA,UAkBO,i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EAEX,MAAA,GAAS,MAAA;AAAA;;;;;;;;;;;iBAaK,sBAAA,CACd,MAAA,EAAQ,sBAAA,IACN,GAAA,EAAK,oBAAA,KAAyB,OAAA;AAAA,UAgTjB,4BAAA;EACf,UAAA,EAAY,eAAA;;EAEZ,MAAA,GAAS,MAAM;AAAA;;;;;;;;;;AHxejB;;;;;;;;AAAoE;AAgBpE;;;;;;;;;AAEqD;AAYrD;;;;;;;;;iBGkfgB,4BAAA,CACd,MAAA,EAAQ,4BAAA,GACP,qBAAqB"}
package/dist/worker.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as ImportsRunJobContext, c as PairSinkContext, d as createRunImportHandler, f as importsRunJob, i as ImportsRunDeadListenerConfig, l as RunImportHandlerConfig, n as EsClientResolver, o as ImportsRunJobPayload, p as importsRunJobPayloadSchema, r as FilePathResolver, s as PairSink, t as EnsureIndexResolver, u as createImportsRunDeadListener } from "./worker-CA4jf4BA.mjs";
1
+ import { a as ImportsRunJobContext, c as PairSinkContext, d as createRunImportHandler, f as importsRunJob, i as ImportsRunDeadListenerConfig, l as RunImportHandlerConfig, n as EsClientResolver, o as ImportsRunJobPayload, p as importsRunJobPayloadSchema, r as FilePathResolver, s as PairSink, t as EnsureIndexResolver, u as createImportsRunDeadListener } from "./worker-ZWkDs7gz.mjs";
2
2
  export { EnsureIndexResolver, EsClientResolver, FilePathResolver, ImportsRunDeadListenerConfig, ImportsRunJobContext, ImportsRunJobPayload, PairSink, PairSinkContext, RunImportHandlerConfig, createImportsRunDeadListener, createRunImportHandler, importsRunJob, importsRunJobPayloadSchema };
package/dist/worker.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e,o as t,r as n}from"./runner-BOwPUm7W.mjs";import{a as r,i,r as a}from"./publish-DCXIPwTE.mjs";import{eq as o}from"drizzle-orm";import{z as s}from"zod";import{runAsCli as c}from"@murumets-ee/core";import{defineJob as l}from"@murumets-ee/queue/client";const u=s.object({importRunId:s.string().uuid()}),d=l({name:`imports:run`,description:`Stream a feed file, transform rows, bulk-write to Elasticsearch.`,schema:u,defaultRetries:0});function f(a){let{importRuns:o,transforms:s,esClient:l,esIndex:u,resolveFilePath:d,ensureIndex:f,pairSink:m,logger:h}=a;return async a=>c(async()=>{let{importRunId:c}=a.payload,g=h?.child({jobId:a.id,importRunId:c,type:`imports:run`}),_=await o.findById(c);if(!_){g?.warn(`import_run row not found — skipping`);return}_.status===`running`&&g?.warn({previousQueueJobId:_.queueJobId,previousStartedAt:_.startedAt},`imports: re-claiming a row left in running by a prior worker — likely a crash recovered by queue lock-recovery`);let v=s.get(_.transformName);if(!v)throw await p(o,c,`Unknown transform "${_.transformName}"`),Error(`No transform registered for name "${_.transformName}"`);let y=_.params&&typeof _.params==`object`&&!Array.isArray(_.params)?_.params:{},b=y.feed&&typeof y.feed==`object`&&!Array.isArray(y.feed)?y.feed:{},x=n.safeParse(b);if(!x.success){let e=x.error.issues[0]?.message??`invalid feed reader config`;throw await p(o,c,`Invalid params.feed: ${e}`),Error(`Invalid params.feed for import_run ${c}: ${e}`)}let S=x.data;await o.update(c,{status:`running`,queueJobId:a.id,startedAt:new Date}),i(c);let C;try{C=await l()}catch(e){throw await p(o,c,`Could not resolve ES client: ${e instanceof Error?e.message:String(e)}`),e}if(f)try{await f()}catch(e){throw await p(o,c,`Could not ensure ES index/alias: ${e instanceof Error?e.message:String(e)}`),e}let w,T;if(d)try{let e=await d(_.filePath);w=e.localPath,T=e.cleanup}catch(e){throw await p(o,c,`Could not resolve filePath: ${e instanceof Error?e.message:String(e)}`),e}else w=_.filePath;let E;if(S.format!==`xlsx`)try{E=await t(w,S.hasHeader===void 0?{}:{hasHeader:S.hasHeader}),g?.info({importRunId:c,totalRows:E},`imports: pre-pass row count`)}catch(e){g?.warn({err:e},`imports: pre-pass row count failed — continuing without total`)}let D;try{let t={filePath:w,...S.format!==void 0&&{format:S.format},...S.delimiter!==void 0&&{delimiter:S.delimiter},...S.hasHeader!==void 0&&{hasHeader:S.hasHeader},...S.headerRowIndex!==void 0&&{headerRowIndex:S.headerRowIndex},...S.sheet!==void 0&&{sheet:S.sheet}};D=await e({importRunId:c,runLabel:_.label,params:y,transform:v,feed:t,esClient:C,esIndex:u,onProgress:e=>a.updateProgress(E===void 0?e:{...e,totalRows:E}),...g!==void 0&&{logger:g}})}catch(e){throw await p(o,c,e instanceof Error?e.message:String(e)),T&&await T().catch(e=>{g?.warn({err:e},`filePath cleanup after failed run threw — ignoring`)}),e}if(T&&await T().catch(e=>{g?.warn({err:e},`filePath cleanup after successful run threw — ignoring`)}),await o.update(c,{status:`succeeded`,finishedAt:new Date,totals:{rowsRead:D.rowsRead,rowsSucceeded:D.rowsSucceeded,rowsFailed:D.rowsFailed,rowsSkipped:D.rowsSkipped,rowsWarned:D.rowsWarned,batchesCompleted:D.batchesCompleted,patchesApplied:D.patchesApplied,patchesOrphaned:D.patchesOrphaned},errorSummary:JSON.parse(JSON.stringify(D.errors)),warningSummary:JSON.parse(JSON.stringify(D.warnings))}),r(c,{rowsRead:D.rowsRead,rowsSucceeded:D.rowsSucceeded,rowsFailed:D.rowsFailed}),m&&D.pairs.length>0)try{await m(D.pairs,{importRunId:c,params:y,...g!==void 0&&{logger:g}}),g?.info({importRunId:c,pairs:D.pairs.length},`imports: pairSink invoked`)}catch(e){g?.warn({importRunId:c,pairs:D.pairs.length,err:e},`imports: pairSink threw — replacement ingestion skipped, catalogue import unaffected`)}g?.info({rowsRead:D.rowsRead,rowsSucceeded:D.rowsSucceeded,rowsFailed:D.rowsFailed,rowsSkipped:D.rowsSkipped,batches:D.batchesCompleted},`import_run completed`)})}async function p(e,t,n){try{await e.update(t,{status:`failed`,finishedAt:new Date,errorSummary:{fatal:n}}),a(t,n)}catch{}}function m(e){let{importRuns:t,logger:n}=e;return{onJobDead:async e=>{e.jobType===`imports:run`&&await c(async()=>{let r=n?.child({event:`imports.run.dead`,jobId:e.jobId,type:`imports:run`}),i=t.getTable(),a=(await t.findMany({where:o(i.queueJobId,e.jobId),limit:1}))[0];if(!a){r?.warn(`queue.job.dead with no matching import_run — skipping`);return}if(a.status!==`running`&&a.status!==`pending`){r?.info({importRunId:a.id,status:a.status},`queue.job.dead arrived for a row already in a terminal state — leaving as-is`);return}a.status===`pending`&&r?.warn({importRunId:a.id,attempts:e.attempts},`queue.job.dead arrived for an import_run still in pending — worker crashed BEFORE claim/lookup`),await p(t,a.id,e.error),r?.info({importRunId:a.id,attempts:e.attempts,priorStatus:a.status},`queue.job.dead → import_run marked failed`)})}}}export{m as createImportsRunDeadListener,f as createRunImportHandler,d as importsRunJob,u as importsRunJobPayloadSchema};
1
+ import{c as e,n as t,u as n}from"./runner-C-s6SD7t.mjs";import{a as r,i,r as a}from"./publish-DCXIPwTE.mjs";import{runAsCli as o}from"@murumets-ee/core";import{z as s}from"zod";import{eq as c}from"drizzle-orm";import{defineJob as l}from"@murumets-ee/queue/client";const u=s.object({importRunId:s.string().uuid()}),d=l({name:`imports:run`,description:`Stream a feed file, transform rows, bulk-write to Elasticsearch.`,schema:u,defaultRetries:0});function f(a){let{importRuns:s,transforms:c,esClient:l,esIndex:u,resolveFilePath:d,ensureIndex:f,pairSink:m,logger:h}=a;return async a=>o(async()=>{let{importRunId:o}=a.payload,g=h?.child({jobId:a.id,importRunId:o,type:`imports:run`}),_=await s.findById(o);if(!_){g?.warn(`import_run row not found — skipping`);return}_.status===`running`&&g?.warn({previousQueueJobId:_.queueJobId,previousStartedAt:_.startedAt},`imports: re-claiming a row left in running by a prior worker — likely a crash recovered by queue lock-recovery`);let v=c.get(_.transformName);if(!v)throw await p(s,o,`Unknown transform "${_.transformName}"`),Error(`No transform registered for name "${_.transformName}"`);let y=_.params&&typeof _.params==`object`&&!Array.isArray(_.params)?_.params:{},b=e(y);if(!b.success){let e=b.error.issues[0]?.message??`invalid feed reader config`;throw await p(s,o,`Invalid params.feed: ${e}`),Error(`Invalid params.feed for import_run ${o}: ${e}`)}let x=b.data;await s.update(o,{status:`running`,queueJobId:a.id,startedAt:new Date}),i(o);let S;try{S=await l()}catch(e){throw await p(s,o,`Could not resolve ES client: ${e instanceof Error?e.message:String(e)}`),e}if(f)try{await f()}catch(e){throw await p(s,o,`Could not ensure ES index/alias: ${e instanceof Error?e.message:String(e)}`),e}let C,w;if(d)try{let e=await d(_.filePath);C=e.localPath,w=e.cleanup}catch(e){throw await p(s,o,`Could not resolve filePath: ${e instanceof Error?e.message:String(e)}`),e}else C=_.filePath;let T;if(x.format!==`xlsx`)try{T=await n(C,x.hasHeader===void 0?{}:{hasHeader:x.hasHeader}),g?.info({importRunId:o,totalRows:T},`imports: pre-pass row count`)}catch(e){g?.warn({err:e},`imports: pre-pass row count failed — continuing without total`)}let E;try{let e={filePath:C,...x.format!==void 0&&{format:x.format},...x.delimiter!==void 0&&{delimiter:x.delimiter},...x.hasHeader!==void 0&&{hasHeader:x.hasHeader},...x.headerRowIndex!==void 0&&{headerRowIndex:x.headerRowIndex},...x.sheet!==void 0&&{sheet:x.sheet}};E=await t({importRunId:o,runLabel:_.label,params:y,transform:v,feed:e,esClient:S,esIndex:u,onProgress:e=>a.updateProgress(T===void 0?e:{...e,totalRows:T}),...g!==void 0&&{logger:g}})}catch(e){throw await p(s,o,e instanceof Error?e.message:String(e)),w&&await w().catch(e=>{g?.warn({err:e},`filePath cleanup after failed run threw — ignoring`)}),e}if(w&&await w().catch(e=>{g?.warn({err:e},`filePath cleanup after successful run threw — ignoring`)}),await s.update(o,{status:`succeeded`,finishedAt:new Date,totals:{rowsRead:E.rowsRead,rowsSucceeded:E.rowsSucceeded,rowsFailed:E.rowsFailed,rowsSkipped:E.rowsSkipped,rowsWarned:E.rowsWarned,batchesCompleted:E.batchesCompleted,patchesApplied:E.patchesApplied,patchesOrphaned:E.patchesOrphaned},errorSummary:JSON.parse(JSON.stringify(E.errors)),warningSummary:JSON.parse(JSON.stringify(E.warnings))}),r(o,{rowsRead:E.rowsRead,rowsSucceeded:E.rowsSucceeded,rowsFailed:E.rowsFailed}),m&&E.pairs.length>0)try{await m(E.pairs,{importRunId:o,params:y,...g!==void 0&&{logger:g}}),g?.info({importRunId:o,pairs:E.pairs.length},`imports: pairSink invoked`)}catch(e){g?.warn({importRunId:o,pairs:E.pairs.length,err:e},`imports: pairSink threw — replacement ingestion skipped, catalogue import unaffected`)}g?.info({rowsRead:E.rowsRead,rowsSucceeded:E.rowsSucceeded,rowsFailed:E.rowsFailed,rowsSkipped:E.rowsSkipped,batches:E.batchesCompleted},`import_run completed`)})}async function p(e,t,n){try{await e.update(t,{status:`failed`,finishedAt:new Date,errorSummary:{fatal:n}}),a(t,n)}catch{}}function m(e){let{importRuns:t,logger:n}=e;return{onJobDead:async e=>{e.jobType===`imports:run`&&await o(async()=>{let r=n?.child({event:`imports.run.dead`,jobId:e.jobId,type:`imports:run`}),i=t.getTable(),a=(await t.findMany({where:c(i.queueJobId,e.jobId),limit:1}))[0];if(!a){r?.warn(`queue.job.dead with no matching import_run — skipping`);return}if(a.status!==`running`&&a.status!==`pending`){r?.info({importRunId:a.id,status:a.status},`queue.job.dead arrived for a row already in a terminal state — leaving as-is`);return}a.status===`pending`&&r?.warn({importRunId:a.id,attempts:e.attempts},`queue.job.dead arrived for an import_run still in pending — worker crashed BEFORE claim/lookup`),await p(t,a.id,e.error),r?.info({importRunId:a.id,attempts:e.attempts,priorStatus:a.status},`queue.job.dead → import_run marked failed`)})}}}export{m as createImportsRunDeadListener,f as createRunImportHandler,d as importsRunJob,u as importsRunJobPayloadSchema};
2
2
  //# sourceMappingURL=worker.mjs.map