@murumets-ee/imports 0.0.0-preview-20261014110621

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.
Files changed (72) hide show
  1. package/LICENSE +94 -0
  2. package/dist/analyze/index.d.mts +265 -0
  3. package/dist/analyze/index.d.mts.map +1 -0
  4. package/dist/analyze/index.mjs +2 -0
  5. package/dist/analyze/index.mjs.map +1 -0
  6. package/dist/carmaker-feed-B-QYr3PI.mjs +2 -0
  7. package/dist/carmaker-feed-B-QYr3PI.mjs.map +1 -0
  8. package/dist/carmaker-feed-CWrZLYUt.d.mts +59 -0
  9. package/dist/carmaker-feed-CWrZLYUt.d.mts.map +1 -0
  10. package/dist/cleanup-DDljBe0Z.mjs +2 -0
  11. package/dist/cleanup-DDljBe0Z.mjs.map +1 -0
  12. package/dist/engine-B0ExE4jL.mjs +2 -0
  13. package/dist/engine-B0ExE4jL.mjs.map +1 -0
  14. package/dist/engine-tkbUXKxB.d.mts +609 -0
  15. package/dist/engine-tkbUXKxB.d.mts.map +1 -0
  16. package/dist/index-Bm69N5DW.d.mts +97 -0
  17. package/dist/index-Bm69N5DW.d.mts.map +1 -0
  18. package/dist/index.d.mts +390 -0
  19. package/dist/index.d.mts.map +1 -0
  20. package/dist/index.mjs +2 -0
  21. package/dist/index.mjs.map +1 -0
  22. package/dist/mapping/index.d.mts +42 -0
  23. package/dist/mapping/index.d.mts.map +1 -0
  24. package/dist/mapping/index.mjs +1 -0
  25. package/dist/mapping-transform-CO4MNhMe.mjs +2 -0
  26. package/dist/mapping-transform-CO4MNhMe.mjs.map +1 -0
  27. package/dist/matching/index.d.mts +2 -0
  28. package/dist/matching/index.mjs +1 -0
  29. package/dist/matching-Sr0z4HvN.mjs +2 -0
  30. package/dist/matching-Sr0z4HvN.mjs.map +1 -0
  31. package/dist/parts-schema-M1AtjNJt.d.mts +61 -0
  32. package/dist/parts-schema-M1AtjNJt.d.mts.map +1 -0
  33. package/dist/parts-schema-QqLci_Pl.mjs +2 -0
  34. package/dist/parts-schema-QqLci_Pl.mjs.map +1 -0
  35. package/dist/plugin.d.mts +148 -0
  36. package/dist/plugin.d.mts.map +1 -0
  37. package/dist/plugin.mjs +2 -0
  38. package/dist/plugin.mjs.map +1 -0
  39. package/dist/publish-DCXIPwTE.mjs +2 -0
  40. package/dist/publish-DCXIPwTE.mjs.map +1 -0
  41. package/dist/read-feed-DsLgRDNR.mjs +2 -0
  42. package/dist/read-feed-DsLgRDNR.mjs.map +1 -0
  43. package/dist/realtime/index.d.mts +123 -0
  44. package/dist/realtime/index.d.mts.map +1 -0
  45. package/dist/realtime/index.mjs +1 -0
  46. package/dist/rolldown-runtime-DK3Fl9T5.mjs +1 -0
  47. package/dist/runner-BnFvID1z.mjs +2 -0
  48. package/dist/runner-BnFvID1z.mjs.map +1 -0
  49. package/dist/schema-registry-DB5aIZMN.mjs +2 -0
  50. package/dist/schema-registry-DB5aIZMN.mjs.map +1 -0
  51. package/dist/storage-resolver.d.mts +32 -0
  52. package/dist/storage-resolver.d.mts.map +1 -0
  53. package/dist/storage-resolver.mjs +2 -0
  54. package/dist/storage-resolver.mjs.map +1 -0
  55. package/dist/storage.d.mts +31 -0
  56. package/dist/storage.d.mts.map +1 -0
  57. package/dist/storage.mjs +2 -0
  58. package/dist/storage.mjs.map +1 -0
  59. package/dist/transform-Cu5YEoOl.mjs +2 -0
  60. package/dist/transform-Cu5YEoOl.mjs.map +1 -0
  61. package/dist/transform-WeiiLdYP.d.mts +246 -0
  62. package/dist/transform-WeiiLdYP.d.mts.map +1 -0
  63. package/dist/transforms.d.mts +2 -0
  64. package/dist/transforms.mjs +1 -0
  65. package/dist/worker-CRH_PjKO.d.mts +940 -0
  66. package/dist/worker-CRH_PjKO.d.mts.map +1 -0
  67. package/dist/worker.d.mts +2 -0
  68. package/dist/worker.mjs +2 -0
  69. package/dist/worker.mjs.map +1 -0
  70. package/dist/xlsx-reader-D9Ntxm29.mjs +2 -0
  71. package/dist/xlsx-reader-D9Ntxm29.mjs.map +1 -0
  72. package/package.json +81 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-CRH_PjKO.d.mts","names":[],"sources":["../src/entities/import-run.ts","../src/streaming.ts","../src/read-feed.ts","../src/error-tracker.ts","../src/price-stats.ts","../src/runner.ts","../src/worker.ts"],"mappings":";;;;;;;;AAoCyD;AAEzD;;;;;;;;AAFyD,cAP5C,mBAAA;AAAA,KAOD,eAAA,WAA0B,mBAAmB;AAAA,cAE5C,SAAA,gCAAS,MAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuHtB;;;;;;;;AAAoE;;;;AC3FpE;;;;;;;;;AAGU;AAkBV;;;;;;;;;;;;0GA6CiB;;;EAEf;;;;;;;;;KDuBU,eAAA,GAAkB,WAAW,QAAQ,SAAA,CAAU,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;iBC3FrC,aAAA,CACpB,QAAA,UACA,OAAA;EAAW,SAAA;AAAA,IACV,OAAO;AAAA,UAkBO,iBAAA;;EAEf,QAAA;;;;;EAKA,SAAA;;;;;;;EAOA,SAAA;;;;;;;EAOA,OAAA,GAAU,aAAa;;;;;;EAMvB,gBAAA;;;;;;;;AD2CF;;;;;;;EC5BE,KAAA;AAAA;AAAA,UAGe,aAAA;;EAEf,SAAA;EApEoB;;;;;;;;;AAGZ;AAkBV;;;;EA8DE,GAAA,EAAK,MAAM;AAAA;;;;;;;AApBN;AAGP;iBA4BuB,UAAA,CAAW,OAAA,EAAS,iBAAA,GAAoB,aAAA,CAAc,aAAA;;;;AD5HpB;AAEzD;;;;;;cEZa,sBAAA,EAAsB,CAAA,CAAA,SAAA;;;;;;EFYb;;;;;;;;;;;;;;;;;;;;;;;;;;KEQV,gBAAA,GAAmB,CAAA,CAAE,KAAK,QAAQ,sBAAA;;;;;;;;;;;;;;;iBAgB9B,uBAAA,CACd,MAAA,YACC,UAAU,QAAQ,sBAAA,CAAuB,SA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AAmB,GAAA,EAAK,eAAA,KAAoB,OAAA;AAAA,UAEnE,sBAAA;;EAEf,UAAA,EAAY,eAAA;EJtJD;EIwJX,UAAA,EAAY,iBAAA;;EAEZ,QAAA,EAAU,gBAAA;;EAEV,OAAA;;;;;;EAMA,WAAA,GAAc,mBAAA;;;;;;EAMd,eAAA,GAAkB,gBAAA;EJxKe;;;;;;EI+KjC,QAAA,GAAW,QAAA;;EAEX,MAAA,GAAS,MAAA;AAAA;;;;;;;;;;;iBAaK,sBAAA,CACd,MAAA,EAAQ,sBAAA,IACN,GAAA,EAAK,oBAAA,KAAyB,OAAA;AAAA,UAsZjB,4BAAA;EACf,UAAA,EAAY,eAAA;;EAEZ,MAAA,GAAS,MAAM;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AJrkBjB;;;;;;;;iBI6mBgB,4BAAA,CACd,MAAA,EAAQ,4BAAA,GACP,qBAAqB"}
@@ -0,0 +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-CRH_PjKO.mjs";
2
+ export { EnsureIndexResolver, EsClientResolver, FilePathResolver, ImportsRunDeadListenerConfig, ImportsRunJobContext, ImportsRunJobPayload, PairSink, PairSinkContext, RunImportHandlerConfig, createImportsRunDeadListener, createRunImportHandler, importsRunJob, importsRunJobPayloadSchema };
@@ -0,0 +1,2 @@
1
+ import{a as e,r as t}from"./read-feed-DsLgRDNR.mjs";import{c as n,d as r,f as i,n as a,s as o}from"./runner-BnFvID1z.mjs";import{a as s,i as c,r as l}from"./publish-DCXIPwTE.mjs";import{runAsCli as u}from"@murumets-ee/core";import{z as d}from"zod";import{and as f,desc as p,eq as m}from"drizzle-orm";import{defineJob as h}from"@murumets-ee/queue/client";const g=d.object({importRunId:d.string().uuid()}),_=h({name:`imports:run`,description:`Stream a feed file, transform rows, bulk-write to Elasticsearch.`,schema:g,defaultRetries:0});function v(l){let{importRuns:d,transforms:h,esClient:g,esIndex:_,resolveFilePath:v,ensureIndex:b,pairSink:x,logger:S}=l;return async l=>u(async()=>{let{importRunId:u}=l.payload,C=S?.child({jobId:l.id,importRunId:u,type:`imports:run`}),w=await d.findById(u);if(!w){C?.warn(`import_run row not found — skipping`);return}w.status===`running`&&C?.warn({previousQueueJobId:w.queueJobId,previousStartedAt:w.startedAt},`imports: re-claiming a row left in running by a prior worker — likely a crash recovered by queue lock-recovery`);let T=h.get(w.transformName);if(!T)throw await y(d,u,`Unknown transform "${w.transformName}"`),Error(`No transform registered for name "${w.transformName}"`);let E=w.params&&typeof w.params==`object`&&!Array.isArray(w.params)?w.params:{},D=t(E);if(!D.success){let e=D.error.issues[0]?.message??`invalid feed reader config`;throw await y(d,u,`Invalid params.feed: ${e}`),Error(`Invalid params.feed for import_run ${u}: ${e}`)}let O=D.data;await d.update(u,{status:`running`,queueJobId:l.id,startedAt:new Date}),c(u);let k;try{k=await g()}catch(e){throw await y(d,u,`Could not resolve ES client: ${e instanceof Error?e.message:String(e)}`),e}if(b)try{await b()}catch(e){throw await y(d,u,`Could not ensure ES index/alias: ${e instanceof Error?e.message:String(e)}`),e}let A,j;if(v)try{let e=await v(w.filePath);A=e.localPath,j=e.cleanup}catch(e){throw await y(d,u,`Could not resolve filePath: ${e instanceof Error?e.message:String(e)}`),e}else A=w.filePath;let M;if(O.format!==`xlsx`)try{M=await e(A,O.hasHeader===void 0?{}:{hasHeader:O.hasHeader}),C?.info({importRunId:u,totalRows:M},`imports: pre-pass row count`)}catch(e){C?.warn({err:e},`imports: pre-pass row count failed — continuing without total`)}let N;try{let e={filePath:A,...O.format!==void 0&&{format:O.format},...O.delimiter!==void 0&&{delimiter:O.delimiter},...O.hasHeader!==void 0&&{hasHeader:O.hasHeader},...O.headerRowIndex!==void 0&&{headerRowIndex:O.headerRowIndex},...O.sheet!==void 0&&{sheet:O.sheet},...O.quote!==void 0&&{quote:O.quote}};N=await a({importRunId:u,runLabel:w.label,params:E,transform:T,feed:e,esClient:k,esIndex:_,onProgress:e=>l.updateProgress(M===void 0?e:{...e,totalRows:M}),...C!==void 0&&{logger:C}})}catch(e){throw await y(d,u,e instanceof Error?e.message:String(e)),j&&await j().catch(e=>{C?.warn({err:e},`filePath cleanup after failed run threw — ignoring`)}),e}j&&await j().catch(e=>{C?.warn({err:e},`filePath cleanup after successful run threw — ignoring`)});let P=N.warnings,F=typeof E.brandId==`string`?E.brandId:void 0,I=typeof E.supplierId==`string`?E.supplierId:void 0;if(F&&I&&N.priceStats.median!==null)try{let e=d.getTable(),t=await d.findMany({where:f(m(e.transformName,w.transformName),m(e.status,`succeeded`)),orderBy:p(e.createdAt),limit:50}),a=t.find(e=>{if(e.id===u)return!1;let t=e.params;if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t;return n.brandId===F&&n.supplierId===I});!a&&t.length>=50&&C?.warn({brandId:F,supplierId:I,transformName:w.transformName},`imports: price-drift check found no prior run for this (brand, supplier) within the 50 most recent succeeded runs for this transform — a real prior run may exist beyond the bound, not necessarily absent`);let s=a?n(a.priceStats):null,c=s?o(s,N.priceStats):null;if(c){let e=c.ratio>=1,t=new r;t.addError(-1,`price_anomaly`,`Median purchase price is ${(e?c.ratio:1/c.ratio).toFixed(1)}x ${e?`higher`:`lower`} than the previous successful run for this supplier/brand (previous run ${a?.id??`unknown`}: median ${c.prevMedian}; this run: median ${c.currMedian}, minor units). Check for a decimal or thousands-separator format change in the source feed.`,`priceStats.median`,{previousImportRunId:a?.id??null,previousMedian:c.prevMedian,currentMedian:c.currMedian,ratio:c.ratio}),P=i(N.warnings,t.snapshot()),C?.warn({previousImportRunId:a?.id,ratio:c.ratio},`imports: price_anomaly — median purchase price shifted by a magnitude vs the prior run`)}}catch(e){C?.warn({err:e},`imports: price-drift comparison failed — continuing without it`)}if(await d.update(u,{status:`succeeded`,finishedAt:new Date,totals:{rowsRead:N.rowsRead,rowsSucceeded:N.rowsSucceeded,rowsFailed:N.rowsFailed,rowsSkipped:N.rowsSkipped,rowsWarned:N.rowsWarned,batchesCompleted:N.batchesCompleted,patchesApplied:N.patchesApplied,patchesOrphaned:N.patchesOrphaned},errorSummary:JSON.parse(JSON.stringify(N.errors)),warningSummary:JSON.parse(JSON.stringify(P)),priceStats:JSON.parse(JSON.stringify(N.priceStats))}),s(u,{rowsRead:N.rowsRead,rowsSucceeded:N.rowsSucceeded,rowsFailed:N.rowsFailed}),x&&N.pairs.length>0)try{await x(N.pairs,{importRunId:u,params:E,...C!==void 0&&{logger:C}}),C?.info({importRunId:u,pairs:N.pairs.length},`imports: pairSink invoked`)}catch(e){C?.warn({importRunId:u,pairs:N.pairs.length,err:e},`imports: pairSink threw — replacement ingestion incomplete, catalogue import unaffected`)}C?.info({rowsRead:N.rowsRead,rowsSucceeded:N.rowsSucceeded,rowsFailed:N.rowsFailed,rowsSkipped:N.rowsSkipped,batches:N.batchesCompleted},`import_run completed`)})}async function y(e,t,n){try{await e.update(t,{status:`failed`,finishedAt:new Date,errorSummary:{fatal:n}}),l(t,n)}catch{}}function b(e){let{importRuns:t,logger:n}=e;return{onJobDead:async e=>{e.jobType===`imports:run`&&await u(async()=>{let r=n?.child({event:`imports.run.dead`,jobId:e.jobId,type:`imports:run`}),i=t.getTable(),a=(await t.findMany({where:m(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 y(t,a.id,e.error),r?.info({importRunId:a.id,attempts:e.attempts,priorStatus:a.status},`queue.job.dead → import_run marked failed`)})}}}export{b as createImportsRunDeadListener,v as createRunImportHandler,_ as importsRunJob,g as importsRunJobPayloadSchema};
2
+ //# sourceMappingURL=worker.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.mjs","names":[],"sources":["../src/worker.ts"],"sourcesContent":["/**\n * Queue handler for `imports:run`. The route handler that creates the\n * `import_run` row enqueues this job carrying `{ importRunId }`; the\n * worker module here resolves the run, the transform, and the ES\n * client, then runs `runImport` and writes results back.\n *\n * Per PLAN-ECOMMERCE.md PR 7 (PoC scope): one job type, no resumability.\n * A failed handler attempt re-runs from row 1 on retry — fine for the\n * tens-of-MB feed sizes the PoC exercises.\n *\n * Per CLAUDE.md \"leaf packages\" boundary rule: this handler reads the\n * import_run row via an injected `AdminClient`, NOT a direct `db.select`.\n * Construction happens at plugin init in `plugin.ts`.\n */\n\nimport { type Logger, runAsCli } from '@murumets-ee/core'\nimport {\n defineJob,\n type JobDefinition,\n type QueueJobDeadEvent,\n type QueueTerminalNotifier,\n} from '@murumets-ee/queue/client'\nimport type { EsClientLike } from '@murumets-ee/search-elasticsearch'\nimport { and, desc, eq } from 'drizzle-orm'\nimport type { PgColumn } from 'drizzle-orm/pg-core'\nimport { z } from 'zod'\nimport type { ImportRunClient, ImportRunStatus } from './entities/import-run.js'\nimport { ErrorTracker, mergeErrorTrackerSnapshots } from './error-tracker.js'\nimport { detectPriceAnomaly, parsePriceStats } from './price-stats.js'\nimport { type ReadFeedOptions, readPersistedFeedConfig } from './read-feed.js'\nimport {\n publishImportRunFailed,\n publishImportRunStarted,\n publishImportRunSucceeded,\n} from './realtime/publish.js'\nimport { type ImportRunProgress, runImport } from './runner.js'\nimport { countDataRows } from './streaming.js'\nimport type { DirectionalPair, TransformRegistry } from './transform.js'\n\n/**\n * Structural subset of `JobContext` the handler reads. Declared\n * locally so we don't depend on a `JobHandler` import — the queue\n * package doesn't re-export it from any subpath today (matches the\n * `SendEmailJobContext` pattern in `@murumets-ee/notifications`).\n *\n * Function-param contravariance lets a handler returned with this\n * narrower shape be assigned to the wider `JobHandler<TPayload>` that\n * `registerJob` expects.\n */\nexport interface ImportsRunJobContext {\n id: string\n payload: ImportsRunJobPayload\n updateProgress(data: ImportRunProgress): void\n}\n\n/**\n * Payload schema. `importRunId` is the `import_run.id` UUID — the worker\n * looks up everything else (filePath, transformName, params, …) from\n * that row. Keeping the payload tiny means the queue's progress JSON\n * column never bloats with feed metadata duplicated across `toolkit_jobs`.\n */\nexport const importsRunJobPayloadSchema = z.object({\n importRunId: z.string().uuid(),\n})\nexport type ImportsRunJobPayload = z.infer<typeof importsRunJobPayloadSchema>\n\n/**\n * Job definition. Consumers register their handler against this with\n * `registerJob(importsRunJob, createRunImportHandler({...}))`.\n *\n * `defaultRetries: 0` — re-running a multi-batch import against the\n * same `import_run.id` while the previous handler may still be writing\n * is a footgun (duplicate batches, double-counted progress). The\n * operator handles retries explicitly via PR 8a's \"retry\" button by\n * creating a new `import_run` row. When the resumable design lands\n * (post-PoC), retries become safe to enable.\n */\nexport const importsRunJob: JobDefinition<ImportsRunJobPayload> = defineJob({\n name: 'imports:run',\n description: 'Stream a feed file, transform rows, bulk-write to Elasticsearch.',\n schema: importsRunJobPayloadSchema,\n defaultRetries: 0,\n})\n\n/**\n * Resolves the ES client at handler-invocation time. A function (rather\n * than the bare `EsClientLike`) so the consumer can lazy-construct the\n * client — typical Next.js setups create the ES connection in a\n * route-handler initialiser, not at plugin-init time.\n */\nexport type EsClientResolver = () => EsClientLike | Promise<EsClientLike>\n\n/**\n * Ensure the destination index/alias exists before the first bulk-write.\n * Invoked once per job, BEFORE {@link runImport}. Idempotent: the canonical\n * implementation (`ensureAliasedIndex` in `@murumets-ee/search-elasticsearch`)\n * no-ops when the alias already resolves.\n *\n * **Why it lives here.** This is the home of the foot-gun it guards: a worker\n * that bulk-writes to alias `<x>` before the alias exists makes ES\n * auto-create a physical `<x>` index with default `text` mappings, breaking\n * aggregations forever. The bootstrap used to run at app boot, which turned\n * \"ES is down\" into a full-admin 500 (issue #610). Moving it onto the import\n * path keeps the guarantee while scoping ES availability to imports/search —\n * the rest of the admin boots and runs with ES down.\n */\nexport type EnsureIndexResolver = () => Promise<unknown>\n\n/**\n * Resolves the value of `import_run.filePath` (whatever the upload\n * route persisted there — typically a storage adapter key) to a\n * readable LOCAL filesystem path that {@link runImport} can hand to\n * `node:fs.createReadStream`.\n *\n * **Why this exists:** the streaming reader (`streamFeed`) reads from\n * local disk via `createReadStream`. The upload route may persist a\n * remote-storage object key (R2, S3, …) on `import_run.filePath`\n * because that's what `@murumets-ee/storage` returns. Without a\n * resolver, `createReadStream('uploads/2026/05/<uuid>/feed.txt')`\n * crashes with `ENOENT`. The resolver is the documented integration\n * point — typical wiring downloads the storage object to a tmpfile\n * and returns its path.\n *\n * **`cleanup`** runs after the run finishes (success OR failure). The\n * worker awaits it best-effort — a failed cleanup logs but does not\n * crash the run.\n *\n * **No-resolver fallback:** when `resolveFilePath` is unset, the\n * worker treats `import_run.filePath` as already a local FS path\n * (back-compat with the original PoC design where uploads landed on\n * local disk). This stays valid for fixture-driven tests + on-disk\n * deployments.\n */\nexport type FilePathResolver = (\n storageKey: string,\n) => Promise<{ localPath: string; cleanup?: () => Promise<void> }>\n\n/**\n * Context handed to a {@link PairSink} alongside the harvested pairs. Carries the\n * run identity so the sink can build `source` attribution\n * (`feed:<supplierId>:<importBatchId>`, D20) and scope its writes.\n */\nexport interface PairSinkContext {\n importRunId: string\n /** The `import_run.params` object — the sink reads `supplierId` / `importBatchId`. */\n params: Record<string, unknown>\n /**\n * The run's structured logger (child), forwarded so the sink's INTERNAL telemetry —\n * a params-parse miss that skips ingestion, an over-merge flag — is visible. Without it\n * a misconfigured run looks successful from the worker's vantage (a params-miss returns\n * normally, so the worker logs \"applied\"). Optional; the sink no-ops its logs if absent.\n */\n logger?: Logger\n}\n\n/**\n * Optional post-run consumer for the directional supersession pairs the runner\n * harvested as a side-output (commerce-demo PR6, SD007). Invoked ONCE after a\n * successful run with the full in-memory pair buffer (read-once / merge-after) so\n * the consumer (the commerce replacement-merge engine) can build equivalence groups\n * and bulk-write them to Postgres.\n *\n * **Why injected, not imported.** The merge writes the CONSUMER's Postgres tables,\n * but the runner + this worker live in the `@murumets-ee/imports` leaf, which must\n * not depend on commerce. The app composes the sink (commerce exports it, the app\n * passes it to `imports({ pairSink })`) — the same injection shape as `esClient` /\n * `resolveFilePath` / `ensureIndex`. The boundary holds.\n *\n * **Best-effort.** A sink throw is logged and SWALLOWED — the catalogue import\n * (the ES write) has already succeeded and must not be undone by a secondary\n * replacement-ingestion failure. The merge is idempotent, so a re-import recovers.\n */\nexport type PairSink = (pairs: readonly DirectionalPair[], ctx: PairSinkContext) => Promise<void>\n\nexport interface RunImportHandlerConfig {\n /** AdminClient over the `import_run` entity. */\n importRuns: ImportRunClient\n /** Transform registry to dispatch against. Defaults to the process-global singleton. */\n transforms: TransformRegistry\n /** Resolver for the ES client. */\n esClient: EsClientResolver\n /** ES alias / index to bulk-write into. Per D6 callers always pass an alias. */\n esIndex: string\n /**\n * Optional bootstrap for the destination index/alias, run once per job\n * before any bulk-write. See {@link EnsureIndexResolver}. Omit for\n * deployments that bootstrap the index out-of-band (e.g. a reindex job).\n */\n ensureIndex?: EnsureIndexResolver\n /**\n * Optional resolver for `import_run.filePath`. See {@link FilePathResolver}.\n * Required when uploads land in remote storage (R2/S3); optional for\n * on-disk PoC setups.\n */\n resolveFilePath?: FilePathResolver\n /**\n * Optional consumer for the directional supersession pairs harvested as a\n * side-output (commerce-demo PR6, SD007). See {@link PairSink}. Omit for\n * deployments that don't ingest replacement codes — the pairs are simply\n * discarded after the run.\n */\n pairSink?: PairSink\n /** Optional structured logger. Defaults to silent. */\n logger?: Logger\n}\n\n/**\n * Build the `JobHandler` for {@link importsRunJob}. The returned\n * handler is what gets passed to `registerJob`.\n *\n * The body is wrapped in `runAsCli` so AdminClient calls inside have a\n * synthetic `cli` admin context — `auditable()` records `updatedBy:\n * 'cli'` rather than NULL, and the firewall checker passes. This is\n * the documented worker entry-point pattern (see `runAsCli` JSDoc in\n * `@murumets-ee/core`).\n */\nexport function createRunImportHandler(\n config: RunImportHandlerConfig,\n): (job: ImportsRunJobContext) => Promise<void> {\n const {\n importRuns,\n transforms,\n esClient,\n esIndex,\n resolveFilePath,\n ensureIndex,\n pairSink,\n logger,\n } = config\n\n return async (job: ImportsRunJobContext): Promise<void> =>\n runAsCli(async () => {\n const { importRunId } = job.payload\n const log = logger?.child({ jobId: job.id, importRunId, type: 'imports:run' })\n\n const run = await importRuns.findById(importRunId)\n if (!run) {\n // Row was deleted between enqueue and dispatch — nothing to do.\n // Don't throw: a thrown handler retries with no payoff because\n // the row stays gone. Log + return so the queue marks the job\n // completed.\n log?.warn('import_run row not found — skipping')\n return\n }\n\n // Re-claim detection. The queue's `recoverStuckJobs` sweep flips a\n // crashed worker's `toolkit_jobs` row from `processing` back to\n // `pending` — but the queue layer has no knowledge of `import_run`,\n // so this row stays at `status='running'` from the prior attempt.\n // When the queue re-dispatches the job, we land here with a row\n // that the operator-facing Active panel has been showing as live\n // for however long lock-recovery took (default 30 min). The\n // existing `update` below overwrites `queueJobId` + `startedAt` so\n // there is no STATE corruption — but emit a structured warning so\n // ops can correlate this re-run with the worker crash that\n // produced it. The sibling `sweepStaleImportRuns` job below catches\n // the case where re-dispatch never happens (queue marks the job\n // dead, or the queue worker is offline long-term).\n if (run.status === 'running') {\n log?.warn(\n {\n previousQueueJobId: run.queueJobId,\n previousStartedAt: run.startedAt,\n },\n 'imports: re-claiming a row left in running by a prior worker — likely a crash recovered by queue lock-recovery',\n )\n }\n\n // `transformName`, `filePath`, `label` are declared `field.text({\n // required: true })` so the inferred DTO already types them as\n // `string` — no cast needed. `params` is `field.json()` which\n // infers as `JsonValue | undefined`; narrow to a record so the\n // transform receives an object.\n const transform = transforms.get(run.transformName)\n if (!transform) {\n await markFailed(importRuns, importRunId, `Unknown transform \"${run.transformName}\"`)\n throw new Error(`No transform registered for name \"${run.transformName}\"`)\n }\n const params: Record<string, unknown> =\n run.params && typeof run.params === 'object' && !Array.isArray(run.params)\n ? (run.params as Record<string, unknown>)\n : {}\n\n // Reader config (format/delimiter/header/sheet) travels in\n // `params.feed` for mapping-driven runs (commerce-demo PR3). Carmaker\n // runs omit it → empty config → tab-delimited default, so the existing\n // path is byte-for-byte unchanged. Re-validate here as defense-in-depth\n // even though the enqueuing route already validated the saved mapping.\n // Shared with the #842 audit, which has to rehydrate IDENTICALLY or it\n // re-reads a past run with options that run never used.\n const feedParsed = readPersistedFeedConfig(params)\n if (!feedParsed.success) {\n const reason = feedParsed.error.issues[0]?.message ?? 'invalid feed reader config'\n await markFailed(importRuns, importRunId, `Invalid params.feed: ${reason}`)\n throw new Error(`Invalid params.feed for import_run ${importRunId}: ${reason}`)\n }\n const feedConfig = feedParsed.data\n\n await importRuns.update(importRunId, {\n status: 'running' satisfies ImportRunStatus,\n queueJobId: job.id,\n startedAt: new Date(),\n })\n // Realtime: row transitioned pending → running. Subscribers\n // refetch to surface the change in the imports admin page.\n // Best-effort — a publish failure is logged inside `publishSafe`\n // and does NOT roll back the row update.\n publishImportRunStarted(importRunId)\n\n let resolvedClient: EsClientLike\n try {\n resolvedClient = await esClient()\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n await markFailed(importRuns, importRunId, `Could not resolve ES client: ${reason}`)\n throw err\n }\n\n // Ensure the destination alias exists BEFORE any bulk-write. Moved here\n // from app boot (issue #610): the foot-gun is the worker auto-creating a\n // mis-mapped physical index, so the guard belongs on the import path —\n // not gating the whole app on ES. Idempotent + scoped: an ES outage (or\n // the `ensureAliasedIndex` physical-collision guard firing) fails THIS\n // job loudly while the rest of the admin keeps working.\n if (ensureIndex) {\n try {\n await ensureIndex()\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n await markFailed(importRuns, importRunId, `Could not ensure ES index/alias: ${reason}`)\n throw err\n }\n }\n\n // Materialise the file locally if the consumer wired a resolver.\n // The `cleanup` callback (when present) runs in the `finally`\n // below regardless of run outcome so a tmpfile created here\n // doesn't outlive the handler.\n let localPath: string\n let fileCleanup: (() => Promise<void>) | undefined\n if (resolveFilePath) {\n try {\n const resolved = await resolveFilePath(run.filePath)\n localPath = resolved.localPath\n fileCleanup = resolved.cleanup\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n await markFailed(importRuns, importRunId, `Could not resolve filePath: ${reason}`)\n throw err\n }\n } else {\n // Back-compat: no resolver wired → treat `filePath` as already\n // a local FS path. Fine for fixture-driven tests + the original\n // on-disk PoC design.\n localPath = run.filePath\n }\n\n // Pre-pass line count: a 16 MB tab-delimited feed counts in\n // ~50ms; a 500 MB feed in <2s. Cheap relative to the full\n // import. Gives the operator a denominator (`processed / total`)\n // so the imports-page panel can render an actual percent\n // instead of just \"rows so far\".\n // Pre-pass row count is a `\\n`-tally over a delimited file — meaningless\n // on an xlsx binary, so skip it there (the UI falls back to bare counts).\n // `hasHeader` from the feed config keeps the header-exclusion correct for\n // headerless mappings.\n let totalRows: number | undefined\n if (feedConfig.format !== 'xlsx') {\n try {\n totalRows = await countDataRows(\n localPath,\n feedConfig.hasHeader !== undefined ? { hasHeader: feedConfig.hasHeader } : {},\n )\n log?.info({ importRunId, totalRows }, 'imports: pre-pass row count')\n } catch (err) {\n // Don't fail the run on a count miss — the actual import is\n // unaffected; the operator just loses the percent denominator.\n log?.warn({ err }, 'imports: pre-pass row count failed — continuing without total')\n }\n }\n\n let result: Awaited<ReturnType<typeof runImport>>\n try {\n // Build feed options with the conditional-spread idiom (NOT\n // `...feedConfig`) so absent optionals stay ABSENT — spreading a\n // `T | undefined` value would set the key to `undefined`, which\n // `exactOptionalPropertyTypes` rejects against `ReadFeedOptions`.\n const feedOpts: ReadFeedOptions = {\n filePath: localPath,\n ...(feedConfig.format !== undefined && { format: feedConfig.format }),\n ...(feedConfig.delimiter !== undefined && { delimiter: feedConfig.delimiter }),\n ...(feedConfig.hasHeader !== undefined && { hasHeader: feedConfig.hasHeader }),\n ...(feedConfig.headerRowIndex !== undefined && {\n headerRowIndex: feedConfig.headerRowIndex,\n }),\n ...(feedConfig.sheet !== undefined && { sheet: feedConfig.sheet }),\n ...(feedConfig.quote !== undefined && { quote: feedConfig.quote }),\n }\n result = await runImport({\n importRunId,\n runLabel: run.label,\n params,\n transform,\n feed: feedOpts,\n esClient: resolvedClient,\n esIndex,\n onProgress: (progress) =>\n job.updateProgress(totalRows !== undefined ? { ...progress, totalRows } : progress),\n ...(log !== undefined && { logger: log }),\n })\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n await markFailed(importRuns, importRunId, reason)\n if (fileCleanup) {\n await fileCleanup().catch((cleanupErr: unknown) => {\n log?.warn({ err: cleanupErr }, 'filePath cleanup after failed run threw — ignoring')\n })\n }\n throw err\n }\n\n // Cleanup runs before the success-update so a cleanup throw\n // surfaces as a logged warning rather than a crashed handler at\n // the worst possible moment (just after the row was about to be\n // marked succeeded).\n if (fileCleanup) {\n await fileCleanup().catch((cleanupErr: unknown) => {\n log?.warn({ err: cleanupErr }, 'filePath cleanup after successful run threw — ignoring')\n })\n }\n\n // Value-drift detection (F010 / #602). The 6b header-presence drift check\n // (commerce's register-handler.ts, upload-time) only catches a STRUCTURAL\n // change — a mapped column vanishing from the header row. It cannot catch a\n // supplier silently flipping their decimal/thousands separator: no header\n // changes, and `import_mapping.numberFormat` stays the same, so every price\n // parses as a numerically valid but silently WRONG value. Compare THIS run's\n // price distribution against the most recent prior SUCCEEDED run for the same\n // (transformName, brandId, supplierId) and, on a magnitude-scale shift, append\n // a NON-FATAL `price_anomaly` warning. Unlike 6b's 409, this never blocks the\n // run — a genuine repricing is a legitimate reason the median would move, so\n // this is advisory only.\n let warningsToWrite = result.warnings\n const brandIdForDrift = typeof params.brandId === 'string' ? params.brandId : undefined\n const supplierIdForDrift =\n typeof params.supplierId === 'string' ? params.supplierId : undefined\n if (brandIdForDrift && supplierIdForDrift && result.priceStats.median !== null) {\n try {\n // `getTable()` is `PgTableWithColumns<any>` (dynamic entity columns —\n // see the documented-`any` list in CLAUDE.md); cast to the columns we\n // filter/sort on, same pattern as `createImportsRunDeadListener` below.\n const table = importRuns.getTable() as unknown as {\n transformName: PgColumn\n status: PgColumn\n createdAt: PgColumn\n }\n // Bounded lookup (limit 50), filtered to this transform + succeeded runs\n // in SQL, then narrowed to the same (brandId, supplierId) in memory —\n // `params` is an opaque per-transform JSONB blob (CLAUDE.md \"no raw\n // SQL\": no `params->>'brandId'` jsonb operator here). 50 candidates is\n // far more than any operator re-runs between two imports for the same\n // supplier/brand pair before this one.\n const candidates = await importRuns.findMany({\n where: and(eq(table.transformName, run.transformName), eq(table.status, 'succeeded')),\n orderBy: desc(table.createdAt),\n limit: 50,\n })\n const prior = candidates.find((c) => {\n if (c.id === importRunId) return false\n const p = c.params\n if (!p || typeof p !== 'object' || Array.isArray(p)) return false\n const pr = p as Record<string, unknown>\n return pr.brandId === brandIdForDrift && pr.supplierId === supplierIdForDrift\n })\n // CLAUDE.md \"No Unbounded Fan-Out\": \"log() whatever you drop — silent\n // truncation reads as 'covered everything' when it didn't.\" `transformName`\n // is shared across every (brand, supplier) pair using that mapping (e.g.\n // all 17 GIGA brands share `commerce:mapping`), so a genuinely prior run\n // for THIS pair can fall outside the 50-candidate window as import cadence\n // and supplier count grow. Distinguish that from \"no prior run exists\" —\n // both look identical downstream (no anomaly check runs) but only one is\n // an operator-actionable coverage gap.\n if (!prior && candidates.length >= 50) {\n log?.warn(\n {\n brandId: brandIdForDrift,\n supplierId: supplierIdForDrift,\n transformName: run.transformName,\n },\n 'imports: price-drift check found no prior run for this (brand, supplier) within the 50 most recent succeeded runs for this transform — a real prior run may exist beyond the bound, not necessarily absent',\n )\n }\n const priorStats = prior ? parsePriceStats(prior.priceStats) : null\n const anomaly = priorStats ? detectPriceAnomaly(priorStats, result.priceStats) : null\n if (anomaly) {\n const higher = anomaly.ratio >= 1\n const anomalyTracker = new ErrorTracker()\n anomalyTracker.addError(\n -1,\n 'price_anomaly',\n `Median purchase price is ${(higher ? anomaly.ratio : 1 / anomaly.ratio).toFixed(1)}x ${higher ? 'higher' : 'lower'} than the previous successful run for this supplier/brand (previous run ${prior?.id ?? 'unknown'}: median ${anomaly.prevMedian}; this run: median ${anomaly.currMedian}, minor units). Check for a decimal or thousands-separator format change in the source feed.`,\n 'priceStats.median',\n {\n previousImportRunId: prior?.id ?? null,\n previousMedian: anomaly.prevMedian,\n currentMedian: anomaly.currMedian,\n ratio: anomaly.ratio,\n },\n )\n warningsToWrite = mergeErrorTrackerSnapshots(result.warnings, anomalyTracker.snapshot())\n log?.warn(\n { previousImportRunId: prior?.id, ratio: anomaly.ratio },\n 'imports: price_anomaly — median purchase price shifted by a magnitude vs the prior run',\n )\n }\n } catch (err) {\n // Best-effort — a comparison failure must never fail an otherwise-\n // successful catalogue import. Same \"log + continue\" discipline as the\n // pairSink / cleanup best-effort paths elsewhere in this handler.\n log?.warn({ err }, 'imports: price-drift comparison failed — continuing without it')\n }\n }\n\n await importRuns.update(importRunId, {\n status: 'succeeded' satisfies ImportRunStatus,\n finishedAt: new Date(),\n totals: {\n rowsRead: result.rowsRead,\n rowsSucceeded: result.rowsSucceeded,\n rowsFailed: result.rowsFailed,\n rowsSkipped: result.rowsSkipped,\n rowsWarned: result.rowsWarned,\n batchesCompleted: result.batchesCompleted,\n // Phase-2 core-charge attach (commerce-demo PR7) — durable on the run row so\n // an operator sees how many `*S` deposits attached vs orphaned, not just the\n // orphan warnings in `warningSummary`.\n patchesApplied: result.patchesApplied,\n patchesOrphaned: result.patchesOrphaned,\n },\n // The typed `ErrorTrackerSnapshot` is fully JSON-serialisable but\n // doesn't structurally satisfy entity's recursive `JsonValue`\n // (objects without an index signature aren't `Record<string,\n // JsonValue>`). Round-trip through `JSON.parse(JSON.stringify(...))`\n // to land as the recursive JSON shape — the runtime cost is one\n // serialise per import_run completion, the type-cast cost is zero.\n errorSummary: JSON.parse(JSON.stringify(result.errors)),\n // Non-fatal warnings (commerce-demo PR4) — kept separate from\n // `errorSummary` so a `no_purchase_price` advisory never reads as a\n // failed row. Same serialise-roundtrip rationale as `errorSummary`.\n // `warningsToWrite` is `result.warnings` UNLESS the price-drift check\n // above appended a `price_anomaly` entry (F010 / #602).\n warningSummary: JSON.parse(JSON.stringify(warningsToWrite)),\n // Price-distribution snapshot (F010 / #602) — read back by the NEXT\n // run for this (transformName, brandId, supplierId) to detect drift.\n priceStats: JSON.parse(JSON.stringify(result.priceStats)),\n })\n // Realtime: row transitioned to terminal-success. Subscribers\n // refetch to move the row from Active → Recent.\n publishImportRunSucceeded(importRunId, {\n rowsRead: result.rowsRead,\n rowsSucceeded: result.rowsSucceeded,\n rowsFailed: result.rowsFailed,\n })\n\n // Side-output: hand the harvested supersession pairs to the injected sink\n // (commerce-demo PR6, SD007) AFTER the catalogue run is marked succeeded — the\n // ES import is primary; replacement ingestion is secondary. Best-effort: a sink\n // throw is logged + swallowed so a Postgres hiccup can't undo a successful\n // catalogue import (the merge is idempotent → a re-import recovers).\n if (pairSink && result.pairs.length > 0) {\n try {\n await pairSink(result.pairs, {\n importRunId,\n params,\n ...(log !== undefined && { logger: log }),\n })\n // \"invoked\" not \"applied\": the sink may internally skip (e.g. missing run params);\n // it logs its own applied/skipped outcome via the forwarded logger.\n log?.info({ importRunId, pairs: result.pairs.length }, 'imports: pairSink invoked')\n } catch (err) {\n log?.warn(\n { importRunId, pairs: result.pairs.length, err },\n // NOT \"skipped\": a sink may apply part of the batch before failing (the commerce\n // replacement sink commits per batch), so some pairs can already have landed.\n // \"Incomplete\" is the only claim this boundary can honestly make about a sink\n // whose internals it does not know.\n 'imports: pairSink threw — replacement ingestion incomplete, catalogue import unaffected',\n )\n }\n }\n\n log?.info(\n {\n rowsRead: result.rowsRead,\n rowsSucceeded: result.rowsSucceeded,\n rowsFailed: result.rowsFailed,\n rowsSkipped: result.rowsSkipped,\n batches: result.batchesCompleted,\n },\n 'import_run completed',\n )\n })\n}\n\n/** Write a `failed` row with a fatal error reason. Best-effort — logs but does not throw on DB failure. */\nasync function markFailed(importRuns: ImportRunClient, id: string, reason: string): Promise<void> {\n try {\n await importRuns.update(id, {\n status: 'failed' satisfies ImportRunStatus,\n finishedAt: new Date(),\n errorSummary: { fatal: reason },\n })\n // Realtime: row transitioned to terminal-failure. Subscribers\n // refetch to surface the failure in the Recent panel. Publish\n // is best-effort and only fires when the persist succeeds —\n // skipping it on persist failure keeps subscribers consistent\n // with the DB (no event for a row that didn't transition).\n publishImportRunFailed(id, reason)\n } catch {\n // The handler already threw / will throw — the queue will surface\n // the original error. A second failure here just logs noise.\n }\n}\n\nexport interface ImportsRunDeadListenerConfig {\n importRuns: ImportRunClient\n /** Optional structured logger. */\n logger?: Logger\n}\n\n/**\n * Build a {@link QueueTerminalNotifier} that mirrors `imports:run`\n * dead-job events into `import_run.status='failed'`.\n *\n * **Why this exists.** The `imports:run` handler's normal failure path\n * already calls `markFailed` before re-throwing, so a synchronous\n * handler error reaches the operator-visible `failed` status without\n * help from anyone. The case THIS listener catches is the one\n * `markFailed` never gets to: the worker process is killed mid-handler\n * (OOM, container restart, kill -9), the queue's lock-recovery sweep\n * eventually reclaims the row, and the queue ultimately marks the job\n * `dead` (defaultRetries: 0 + repeated process death = dead-letter\n * with `import_run.status` still `running`). Without this listener\n * the row sits in the operator's Active panel forever.\n *\n * **Generic primitive.** This is a thin subscriber over the queue's\n * multi-subscriber `QueueTerminalNotifier` registry — the same shape\n * graphile-worker (`job:failed`) and BullMQ (`failed`) expose. Other\n * domain plugins that mirror queue state (ticketing-reply, future\n * exports/reports/...) can register their own listeners exactly the\n * same way without coordinating via a per-domain sweep job.\n *\n * **Filtering.** The listener is invoked for EVERY dead event in the\n * process. We early-return on any `jobType` other than `imports:run`\n * so the per-event cost on unrelated jobs is a single property read.\n *\n * **Idempotency.** A dead event delivered after the row has already\n * reached its own terminal state (succeeded / failed / cancelled) is\n * ignored — the only transition we make is `running → failed`. This\n * keeps a late replay or out-of-order delivery from clobbering a\n * row whose worker reached `markFailed` faster than the queue's\n * dead-letter dispatch.\n *\n * The handler is wrapped in `runAsCli` so AdminClient calls inside\n * have a synthetic CLI admin context — same pattern as\n * {@link createRunImportHandler}.\n */\nexport function createImportsRunDeadListener(\n config: ImportsRunDeadListenerConfig,\n): QueueTerminalNotifier {\n const { importRuns, logger } = config\n\n return {\n onJobDead: async (event: QueueJobDeadEvent): Promise<void> => {\n if (event.jobType !== 'imports:run') return\n\n await runAsCli(async () => {\n const log = logger?.child({\n event: 'imports.run.dead',\n jobId: event.jobId,\n type: 'imports:run',\n })\n\n // Look up the mirror row by `queueJobId`. Cap to 1 — the\n // upload route writes one `import_run` per enqueued job.\n //\n // `AdminClient.getTable()` returns `PgTableWithColumns<any>`\n // because entity tables have dynamic column shapes (see the\n // `getTable()` JSDoc in `packages/entity/src/admin/client.ts`\n // and the documented-`any`-cases list in CLAUDE.md). Cast\n // the table to a structural shape covering only the column\n // we touch, so both `eq()` and type-coverage see a typed\n // operand instead of an `any`-derived property access.\n const table = importRuns.getTable() as unknown as { queueJobId: PgColumn }\n const matches = await importRuns.findMany({\n where: eq(table.queueJobId, event.jobId),\n limit: 1,\n })\n const row = matches[0]\n if (!row) {\n // No mirror row for this dead job. Either it was deleted\n // by the operator, or the dead event is for a job\n // unrelated to imports despite the type filter\n // (shouldn't happen, but is cheap to log).\n log?.warn('queue.job.dead with no matching import_run — skipping')\n return\n }\n\n // Only transition rows that haven't already reached their\n // own terminal state. A late dead-event must not overwrite\n // a `succeeded` row that the worker reached via the normal\n // path before the queue's dead-letter dispatch fired.\n if (row.status !== 'running' && row.status !== 'pending') {\n log?.info(\n { importRunId: row.id, status: row.status },\n 'queue.job.dead arrived for a row already in a terminal state — leaving as-is',\n )\n return\n }\n\n // Dead-from-`pending` is the rarer + more interesting case:\n // the worker process died (or never claimed) BEFORE it could\n // flip the row to `running`. Log it at warn so ops can spot\n // a queue+worker-startup pathology that the standard `running\n // → failed` transition wouldn't surface. Dead-from-`running`\n // is the documented \"crash mid-import\" case — info is enough.\n if (row.status === 'pending') {\n log?.warn(\n { importRunId: row.id, attempts: event.attempts },\n 'queue.job.dead arrived for an import_run still in pending — worker crashed BEFORE claim/lookup',\n )\n }\n\n await markFailed(importRuns, row.id, event.error)\n log?.info(\n { importRunId: row.id, attempts: event.attempts, priorStatus: row.status },\n 'queue.job.dead → import_run marked failed',\n )\n })\n },\n }\n}\n"],"mappings":"kWA6DA,MAAa,EAA6B,EAAE,OAAO,CACjD,YAAa,EAAE,OAAO,CAAC,CAAC,KAAK,CAC/B,CAAC,EAcY,EAAqD,EAAU,CAC1E,KAAM,cACN,YAAa,mEACb,OAAQ,EACR,eAAgB,CAClB,CAAC,EAsID,SAAgB,EACd,EAC8C,CAC9C,GAAM,CACJ,aACA,aACA,WACA,UACA,kBACA,cACA,WACA,UACE,EAEJ,OAAO,KAAO,IACZ,EAAS,SAAY,CACnB,GAAM,CAAE,eAAgB,EAAI,QACtB,EAAM,GAAQ,MAAM,CAAE,MAAO,EAAI,GAAI,cAAa,KAAM,aAAc,CAAC,EAEvE,EAAM,MAAM,EAAW,SAAS,CAAW,EACjD,GAAI,CAAC,EAAK,CAKR,GAAK,KAAK,qCAAqC,EAC/C,MACF,CAeI,EAAI,SAAW,WACjB,GAAK,KACH,CACE,mBAAoB,EAAI,WACxB,kBAAmB,EAAI,SACzB,EACA,gHACF,EAQF,IAAM,EAAY,EAAW,IAAI,EAAI,aAAa,EAClD,GAAI,CAAC,EAEH,MADA,MAAM,EAAW,EAAY,EAAa,sBAAsB,EAAI,cAAc,EAAE,EAC1E,MAAM,qCAAqC,EAAI,cAAc,EAAE,EAE3E,IAAM,EACJ,EAAI,QAAU,OAAO,EAAI,QAAW,UAAY,CAAC,MAAM,QAAQ,EAAI,MAAM,EACpE,EAAI,OACL,CAAC,EASD,EAAa,EAAwB,CAAM,EACjD,GAAI,CAAC,EAAW,QAAS,CACvB,IAAM,EAAS,EAAW,MAAM,OAAO,EAAE,EAAE,SAAW,6BAEtD,MADA,MAAM,EAAW,EAAY,EAAa,wBAAwB,GAAQ,EAChE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C,EAAK,CAKR,GAAK,KAAK,uDAAuD,EACjE,MACF,CAMA,GAAI,EAAI,SAAW,WAAa,EAAI,SAAW,UAAW,CACxD,GAAK,KACH,CAAE,YAAa,EAAI,GAAI,OAAQ,EAAI,MAAO,EAC1C,8EACF,EACA,MACF,CAQI,EAAI,SAAW,WACjB,GAAK,KACH,CAAE,YAAa,EAAI,GAAI,SAAU,EAAM,QAAS,EAChD,gGACF,EAGF,MAAM,EAAW,EAAY,EAAI,GAAI,EAAM,KAAK,EAChD,GAAK,KACH,CAAE,YAAa,EAAI,GAAI,SAAU,EAAM,SAAU,YAAa,EAAI,MAAO,EACzE,2CACF,CACF,CAAC,CACH,CACF,CACF"}
@@ -0,0 +1,2 @@
1
+ import{i as e}from"./read-feed-DsLgRDNR.mjs";import{open as t}from"node:fs/promises";import{Duplex as n}from"node:stream";var r=class extends Error{headerRowNumber;constructor(e){super(`xlsx header row ${e} has no readable columns — the file may be corrupt, or its shared strings failed to load. Refusing rather than importing empty rows.`),this.name=`XlsxEmptyHeaderError`,this.headerRowNumber=e}},i=class extends Error{constructor(e){super(`xlsx path "${e}" is not a regular file`),this.name=`XlsxNotAFileError`}};function a(e){if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(e instanceof Date)return e.toISOString();if(`richText`in e&&Array.isArray(e.richText))return e.richText.map(e=>e.text).join(``);if(`text`in e&&typeof e.text==`string`)return e.text;if(`result`in e&&e.result!==void 0&&e.result!==null){let t=e.result;return t instanceof Date?t.toISOString():typeof t==`object`?``:String(t)}return``}function o(e){let t=[];if(Array.isArray(e))for(let n=1;n<e.length;n+=1)t[n-1]=a(e[n]);else for(let[n,r]of Object.entries(e)){let e=Number.parseInt(n,10);!Number.isNaN(e)&&e>=1&&(t[e-1]=a(r))}for(let e=0;e<t.length;e+=1)t[e]===void 0&&(t[e]=``);return t}function s(e){let t=e.pipe.bind(e);e.pipe=(e,r)=>{if(e instanceof n){let t=e,n=t.emit.bind(t);t.emit=(e,...r)=>e===`end`&&t.readableLength>0?!1:n(e,...r)}return t(e,r)}}async function*c(n){let{filePath:a,hasHeader:c=!0,headerRowIndex:l=0,sheet:u}=n,d=await import(`exceljs`),f;if(u!==void 0&&(f=Number.parseInt(u,10),Number.isNaN(f)||f<1))throw Error(`Invalid xlsx sheet "${u}" — expected a 1-based worksheet index`);let p=await t(a,`r`),m;try{if(!(await p.stat()).isFile())throw new i(a);m=p.createReadStream({autoClose:!1}),s(m);let t=new d.stream.xlsx.WorkbookReader(m,{worksheets:`emit`,sharedStrings:`cache`,styles:`ignore`,hyperlinks:`ignore`,entries:`ignore`});t.model={sheets:[]};let n=0,u=0,h=!1,g=t[Symbol.asyncIterator](),_=!1;try{for(;;){let t=await g.next();if(t.done){_=!0;break}let i=t.value;if(u+=1,!(f===void 0?u===1:u===f)){for await(let e of i);continue}h=!0;let a=0,s=null;for await(let t of i){a+=1;let i=o(t.values);if(c&&s===null){if(a<l+1)continue;if(s=i.map(e=>e.trim()),s.every(e=>e===``))throw new r(a);e(s);continue}n+=1;let u={};if(s)for(let e=0;e<s.length;e+=1){let t=s[e];t&&(u[t]=i[e]??``)}else for(let e=0;e<i.length;e+=1)u[String(e)]=i[e]??``;yield{rowNumber:n,row:u}}break}}finally{try{for(;!_;){let e=await g.next();if(e.done)break;for await(let t of e.value);}}catch{}}if(f!==void 0&&!h)throw Error(`xlsx worksheet ${f} not found`)}finally{m?.destroy(),await p.close().catch(()=>{})}}export{r as XlsxEmptyHeaderError,i as XlsxNotAFileError,c as streamXlsx};
2
+ //# sourceMappingURL=xlsx-reader-D9Ntxm29.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xlsx-reader-D9Ntxm29.mjs","names":[],"sources":["../src/xlsx-reader.ts"],"sourcesContent":["/**\n * Streaming XLSX reader (commerce-demo phase 02, D005) — the exceljs branch of\n * the feed reader. Yields the SAME `AsyncIterable<{ rowNumber, row }>` contract as\n * the csv-parse `streamFeed`, so the runner / transform layer downstream is\n * format-agnostic.\n *\n * **exceljs over SheetJS** (R02): we parse operator-uploaded spreadsheets — the\n * exact threat model of the unfixed npm `xlsx` prototype-pollution CVE\n * (CVE-2023-30533). exceljs is MIT, ships its own types, has a real streaming\n * `WorkbookReader`, and carries no equivalent advisory.\n *\n * **exceljs is `await import()`-ed**, never statically imported, so it stays out\n * of this package's static module graph — heavy + Node-only, it must not be\n * inlinable into any `*-ui` server-pages bundle (CLAUDE.md bundle budgets). The\n * `read-feed` dispatcher additionally only loads THIS module for `format: 'xlsx'`.\n */\n\nimport { type FileHandle, open } from 'node:fs/promises'\nimport { Duplex } from 'node:stream'\nimport type { CellValue } from 'exceljs'\nimport { assertUniqueHeaders, type StreamFeedRow } from './streaming.js'\n\n/**\n * Thrown by {@link streamXlsx} when the configured header row parses to zero\n * readable columns — the signature of the silent-corruption defect documented\n * on the guard below.\n *\n * A distinct CLASS rather than a bare `Error` because the retroactive audit\n * (`auditEmptyHeaderRuns`, #842) has to tell \"this file's header is\n * unreadable\" apart from every other way reading a spreadsheet can fail\n * (missing object, unreadable zip, wrong sheet index). Matching on the message\n * would make that classification a regex over prose that anyone is free to\n * reword — which is exactly the kind of detector that silently stops detecting.\n * The message text is unchanged from the original throw.\n */\nexport class XlsxEmptyHeaderError extends Error {\n /** 1-based worksheet row the empty header was read from. */\n readonly headerRowNumber: number\n\n constructor(headerRowNumber: number) {\n super(\n `xlsx header row ${headerRowNumber} has no readable columns — the file may be corrupt, ` +\n 'or its shared strings failed to load. Refusing rather than importing empty rows.',\n )\n this.name = 'XlsxEmptyHeaderError'\n this.headerRowNumber = headerRowNumber\n }\n}\n\n/**\n * Thrown by {@link streamXlsx} when the path resolves to something that is not a\n * regular file — a directory, most often. `open()` SUCCEEDS on a directory on\n * Linux (POSIX allows `O_RDONLY` on one) and only the read fails, so this is a\n * check the reader has to make itself.\n *\n * Typed for the same reason {@link XlsxEmptyHeaderError} is: the #842 audit has\n * to tell \"the evidence is unreadable\" from \"the evidence is readable and bad\",\n * and matching prose is how a classifier quietly stops classifying.\n */\nexport class XlsxNotAFileError extends Error {\n constructor(filePath: string) {\n super(`xlsx path \"${filePath}\" is not a regular file`)\n this.name = 'XlsxNotAFileError'\n }\n}\n\nexport interface XlsxReadOptions {\n /** Path to the .xlsx file on local disk. */\n filePath: string\n /** First row is the header (column names). `false` → positional `{ \"0\": … }` keys. Default `true`. */\n hasHeader?: boolean\n /** 0-based index of the header row (rows before it are skipped). Default `0`. */\n headerRowIndex?: number\n /** Worksheet to read, as a 1-based index string. Omit → the first worksheet. */\n sheet?: string\n}\n\n/** Convert one exceljs cell value to a plain string (feeds are text/number cells). */\nfunction cellToString(v: CellValue): string {\n if (v === null || v === undefined) return ''\n if (typeof v === 'string') return v\n if (typeof v === 'number' || typeof v === 'boolean') return String(v)\n if (v instanceof Date) return v.toISOString()\n // Object cell values: rich text, hyperlink, formula result, error.\n if ('richText' in v && Array.isArray(v.richText)) {\n return v.richText.map((r) => r.text).join('')\n }\n if ('text' in v && typeof v.text === 'string') return v.text\n if ('result' in v && v.result !== undefined && v.result !== null) {\n const r = v.result\n if (r instanceof Date) return r.toISOString()\n // A nested error object (formula error) surfaces as empty; primitives stringify.\n return typeof r === 'object' ? '' : String(r)\n }\n return ''\n}\n\n/** Normalise an exceljs `row.values` (1-indexed array OR object form) to a 0-indexed string[]. */\nfunction rowCells(values: CellValue[] | { [key: string]: CellValue }): string[] {\n const out: string[] = []\n if (Array.isArray(values)) {\n // exceljs row arrays are 1-indexed (`values[0]` is empty); shift to 0-based.\n for (let i = 1; i < values.length; i += 1) out[i - 1] = cellToString(values[i])\n } else {\n for (const [k, v] of Object.entries(values)) {\n const idx = Number.parseInt(k, 10)\n if (!Number.isNaN(idx) && idx >= 1) out[idx - 1] = cellToString(v)\n }\n }\n // Fill any holes (sparse rows) with empty strings — the contract is \"missing\n // cell = ''\", matching streamFeed.\n for (let i = 0; i < out.length; i += 1) if (out[i] === undefined) out[i] = ''\n return out\n}\n\n/**\n * Stop unzipper's PREMATURE `'end'` from ending exceljs's entry loop while zip\n * entries are still buffered — the cause of the \"clean workbook reads as\n * corrupt\" flake (plan frontend-delivery F067 / F008), and a production hazard\n * for the same reason the `reader.model` seed below is one.\n *\n * The mechanism, read from source and reproduced deterministically:\n *\n * 1. unzipper 0.10's `Parse` (what exceljs pipes our source into,\n * `workbook-reader.js:81`) re-emits its WRITABLE side's `'finish'` as\n * `'end'` (`unzipper/lib/parse.js`, constructor) — i.e. \"all input bytes\n * consumed\", not \"every entry delivered\". Small entries fit their\n * PassThrough buffers, so `Parse` races through the whole zip, pushing\n * entry objects into its readable buffer, regardless of the consumer.\n * 2. exceljs's `iterateStream` PAUSES the zip while it handles an entry, and\n * for a worksheet that precedes `sharedStrings.xml` (exceljs's own write\n * order, and Excel's) \"handling\" is a `tmp.file()` + write — filesystem\n * round-trips. It treats the first `'end'` it hears as the end of the zip\n * and exits with the rest of the entries still sitting in the buffer.\n * 3. So when the temp-file write is slower than inflating the remaining\n * entries, `xl/sharedStrings.xml` is never parsed. Every string cell then\n * comes back as `{ sharedString: n }` (exceljs's no-table shape),\n * `cellToString` renders it `''`, and the header guard in `streamXlsx`\n * refuses a perfectly good file as `XlsxEmptyHeaderError`.\n *\n * Measured by delaying `tmp.file` inside exceljs: 0-1ms reads correctly,\n * 5ms+ loses the shared strings every time. A loaded CI runner or a busy\n * queue worker supplies those milliseconds; the regression test supplies them\n * on purpose (`xlsx-reader.premature-end.test.ts`).\n *\n * The fix drops an `'end'` only while the zip's readable buffer still holds\n * undelivered entries. By the time `Parse` finishes its writable side it has\n * reached the end-of-central-directory record and called `push(null)`, so\n * Node emits the REAL `'end'` itself once those entries have been read — this\n * delays the event, it never loses one. An `'end'` with an empty buffer passes\n * straight through, so a read that was already correct is untouched.\n *\n * Not a `pnpm patch` of exceljs/unzipper: a patch lives in THIS workspace's\n * install only, and `@murumets-ee/imports` is published — every consumer\n * would keep the defect. If a future exceljs stops piping into a `Duplex`,\n * the hook simply does not apply and the regression test goes red.\n */\nfunction holdPrematureZipEnd(source: ReturnType<FileHandle['createReadStream']>): void {\n const pipe = source.pipe.bind(source)\n source.pipe = <T extends NodeJS.WritableStream>(\n destination: T,\n options?: { end?: boolean },\n ): T => {\n if (destination instanceof Duplex) {\n const zip = destination\n const emit = zip.emit.bind(zip)\n zip.emit = (event: string | symbol, ...args: unknown[]): boolean => {\n if (event === 'end' && zip.readableLength > 0) return false\n return emit(event, ...args)\n }\n }\n return pipe(destination, options)\n }\n}\n\n/**\n * Async-iterable over the data rows of an .xlsx file. `rowNumber` is the 1-based\n * DATA row index (header excluded). Cell values are coerced to strings so the\n * mapping engine's per-column transforms (which expect raw string cells) apply\n * uniformly across csv/tsv/xlsx.\n */\nexport async function* streamXlsx(options: XlsxReadOptions): AsyncIterable<StreamFeedRow> {\n const { filePath, hasHeader = true, headerRowIndex = 0, sheet } = options\n const ExcelJS = await import('exceljs')\n\n // `WorksheetReader` doesn't expose its sheet id, so count emitted worksheets\n // (1-based) to match the configured `sheet`. Default: the first worksheet.\n // A provided-but-invalid sheet FAILS FAST rather than silently reading sheet 1\n // — and before we touch the filesystem, so a config typo costs no I/O.\n let targetSheetIndex: number | undefined\n if (sheet !== undefined) {\n targetSheetIndex = Number.parseInt(sheet, 10)\n if (Number.isNaN(targetSheetIndex) || targetSheetIndex < 1) {\n throw new Error(`Invalid xlsx sheet \"${sheet}\" — expected a 1-based worksheet index`)\n }\n }\n\n // OPEN THE FILE OURSELVES rather than handing exceljs a path, because a path\n // makes every filesystem failure an UNCAUGHT EXCEPTION that kills the process\n // instead of a rejection the caller can handle.\n //\n // `_getStream` does `fs.createReadStream(input)` for a string input and then\n // `stream.pipe(zip)` (`workbook-reader.js:38,81`). `pipe()` does not forward\n // SOURCE errors, and exceljs registers no `error` listener on that stream — so\n // an ENOENT / EACCES / EISDIR surfaces as `Unhandled 'error' event`. Verified\n // by execution, not inference: all three crash the process outright. In the\n // queue worker that kills the job mid-flight instead of routing through\n // `markFailed`; in the #842 audit one unreadable file discards the whole sweep.\n //\n // An fd fixes it at the root rather than patching the symptom:\n // - `open()` rejects normally on ENOENT and EACCES.\n // - a DIRECTORY still opens on Linux (checked — O_RDONLY on a dir succeeds\n // and only the read gives EISDIR), so the `isFile()` check below is\n // load-bearing. It runs against the fd, so it cannot be raced.\n // - once the fd is held, the inode survives `unlink` (checked: the read\n // still returns the bytes). That closes the window against the\n // `@every 1h` retention sweep, which deletes exactly these files and which\n // the audit is documented as racing.\n const handle = await open(filePath, 'r')\n // Held so the outer `finally` can destroy it BEFORE the fd goes away. With\n // `autoClose: false` nothing tears this stream down except reaching the end,\n // and the drain below deliberately swallows errors — so a malformed trailing\n // worksheet can leave the source mid-read while `handle.close()` invalidates\n // the descriptor underneath it. exceljs registers no `error` listener on the\n // stream it pipes (the whole reason this function opens the file itself), so\n // that EBADF would arrive as an uncaught event: the exact failure mode the fd\n // was introduced to eliminate, re-entering through the back door.\n let source: ReturnType<typeof handle.createReadStream> | undefined\n try {\n const stats = await handle.stat()\n if (!stats.isFile()) {\n throw new XlsxNotAFileError(filePath)\n }\n\n source = handle.createReadStream({ autoClose: false })\n holdPrematureZipEnd(source)\n const reader = new ExcelJS.stream.xlsx.WorkbookReader(source, {\n worksheets: 'emit',\n sharedStrings: 'cache',\n styles: 'ignore',\n hyperlinks: 'ignore',\n entries: 'ignore',\n })\n\n // Seed `model` so exceljs cannot dereference it before it has parsed\n // `xl/workbook.xml` — an UPSTREAM defect, and the cause of the xlsx-reader\n // \"flake\" that failed CI intermittently for months (#619, #835).\n //\n // Its streaming reader parses a worksheet INLINE, rather than deferring it to\n // a temp file, when `this.sharedStrings && this.workbookRels` are both set as\n // the entry arrives (`workbook-reader.js:109`). Neither implies\n // `xl/workbook.xml` has been read. The inline path then does\n // `matchingRel && (this.model.sheets || []).find(…)` (`:303`) — guarding\n // `this.workbookRels` on the line above and `this.model.sheets` not at all —\n // so any workbook whose zip orders `sharedStrings.xml` before the worksheet,\n // with `workbook.xml` after it, throws `Cannot read properties of undefined\n // (reading 'sheets')`.\n //\n // That is a PRODUCTION hazard, not a test artifact: this function reads\n // operator-uploaded spreadsheets and the writer chooses the entry order. It\n // presented as flakiness only because the fixtures our own tests write happen\n // to sit on the safe side of the condition.\n //\n // An empty `sheets` makes the lookup miss, so the worksheet keeps its default\n // id/name/state until `_parseWorkbook` overwrites `model` with the real one a\n // few entries later — which is exactly what the deferred path already does.\n // Preferred over a `pnpm patch` (exceljs 4.4.0 is the latest release, so there\n // is no upstream fix to take, but a patch is a standing maintenance cost and\n // this is one assignment that stays correct even if upstream fixes it).\n //\n // `sheets: []` rather than `{}` because `(this.model.sheets || [])` is what is\n // read.\n //\n // The double assertion is NOT laziness and a single `as typeof reader.model`\n // does not compile — checked, not assumed:\n //\n // TS2352: Conversion of type '{ sheets: never[]; }' to type 'WorkbookModel'\n // may be a mistake because neither type sufficiently overlaps with the\n // other. … missing the following properties: creator, lastModifiedBy,\n // lastPrinted, created, and 17 more.\n //\n // A deliberately PARTIAL seed is the whole point — exceljs overwrites it with\n // the real model a few entries later, and filling 21 fields with invented\n // values to satisfy the compiler would be worse than the assertion: it would\n // put fabricated workbook metadata one `_parseWorkbook` failure away from\n // being read as real.\n // toolkit-smell-allow: partial seed for a 21-field type; single assertion rejected by TS2352 (see above)\n reader.model = { sheets: [] } as unknown as typeof reader.model\n\n let dataRowNumber = 0\n let sheetIndex = 0\n let matchedTarget = false\n\n // Drive the worksheet iterator BY HAND rather than with `for await`, so the\n // `finally` below can resume it. Abandoning exceljs's `parse()` generator —\n // which `return`/`break` out of a `for await` does — LEAKS a temp file and an\n // fd per deferred worksheet, because `tempFileCleanupCallback()` sits after\n // the `yield*` with no `finally` of its own (`workbook-reader.js:140-149`).\n //\n // Measured, with a negative control: 25 early-returning reads of a two-sheet\n // deferred-order workbook leaked 50 fds and 50 temp files; the draining shape\n // below leaks 0 of each. `tmp`'s graceful-cleanup hook reclaims the files at\n // NORMAL process exit only, which is no help to a long-lived queue worker and\n // no help at all against the fd ceiling: at the #842 audit's 5000-run cap\n // this is an EMFILE, and an EMFILE arrives as the uncaught stream error the\n // `open()` above exists to prevent.\n //\n // THE COST IS PROPORTIONAL TO THE WORKSHEETS AFTER THE TARGET, which is zero\n // for the single-sheet feeds this reader mostly sees and 4.7× on a workbook\n // whose target is sheet 1 and whose sheet 2 holds 40k rows. Advancing the\n // parent iterator WITHOUT consuming each trailing worksheet is far cheaper\n // and does release the temp files — but it strands exceljs's\n // `createReadStream` on each one, i.e. it trades the disk leak for the fd\n // leak, and the fd leak is the one that ends in EMFILE. So: full drain.\n const worksheets = reader[Symbol.asyncIterator]()\n let readerExhausted = false\n try {\n while (true) {\n const next = await worksheets.next()\n if (next.done) {\n readerExhausted = true\n break\n }\n const worksheet = next.value\n sheetIndex += 1\n const isTarget =\n targetSheetIndex === undefined ? sheetIndex === 1 : sheetIndex === targetSheetIndex\n\n if (!isTarget) {\n // Drain a non-target worksheet so the underlying zip stream advances to the\n // next; exceljs's streaming reader stalls if a worksheet is left unconsumed.\n for await (const _skip of worksheet) {\n void _skip\n }\n continue\n }\n matchedTarget = true\n\n let excelRowNum = 0\n let header: string[] | null = null\n for await (const row of worksheet) {\n excelRowNum += 1\n const cells = rowCells(row.values)\n\n if (hasHeader && header === null) {\n // Skip rows before the configured header row, then capture it (trimmed).\n if (excelRowNum < headerRowIndex + 1) continue\n header = cells.map((c) => c.trim())\n // FAIL LOUDLY on an empty header, because the alternative is SILENT DATA\n // CORRUPTION and we have watched it happen.\n //\n // exceljs assigns `this.sharedStrings = []` at the TOP of\n // `_parseSharedStrings`, before parsing a single entry — and an empty\n // array is truthy, which is what the inline-worksheet guard tests. So a\n // shared-strings entry that yields nothing (a truncated or starved read;\n // observed in CI under load) leaves every string cell resolving to\n // `sharedStrings[index]` → `undefined`. The header parses to zero\n // columns, every data row maps to `{}`, and the import reports SUCCESS\n // with every value dropped. Reproduced deterministically by rebuilding a\n // workbook with an empty `sst`: two rows read, no values, no error.\n //\n // A header row with no usable column is never a legitimate import, so\n // there is no case to preserve. Refusing costs an operator a clear error\n // and saves them a silently empty dataset they would have to notice\n // themselves — the same posture the rest of this package takes toward\n // config mistakes.\n if (header.every((c) => c === '')) {\n throw new XlsxEmptyHeaderError(excelRowNum)\n }\n assertUniqueHeaders(header)\n continue\n }\n\n dataRowNumber += 1\n const rec: Record<string, string> = {}\n if (header) {\n for (let i = 0; i < header.length; i += 1) {\n const key = header[i]\n if (key) rec[key] = cells[i] ?? ''\n }\n } else {\n for (let i = 0; i < cells.length; i += 1) rec[String(i)] = cells[i] ?? ''\n }\n yield { rowNumber: dataRowNumber, row: rec }\n }\n\n // Target worksheet fully read. Stop yielding — the `finally` walks the\n // remaining worksheets so exceljs reaches its cleanup.\n break\n }\n } finally {\n // Runs on every exit: target read, an empty-header throw, or the CONSUMER\n // abandoning us mid-stream (a `break` in the caller's `for await` calls\n // `.return()`, which lands here). Whatever the reason, exceljs still owns\n // temp files it only releases as the consumer pulls past each worksheet.\n //\n // The whole body is CONTAINED, for the same reason `handle.close()` below\n // is: a throw from a `finally` REPLACES whatever the try block was\n // propagating. Trailing worksheets are parsed here, so a malformed one\n // would overwrite an `XlsxEmptyHeaderError` with an XML error — turning\n // the #842 audit's `corrupt` verdict into a meaningless `error` and\n // failing an import whose target sheet read perfectly. Measured: two of\n // four malformed-trailing-sheet variants masked the refusal before this\n // catch existed. Cleanup is best-effort by definition; the error the\n // caller came for is not.\n try {\n while (!readerExhausted) {\n const rest = await worksheets.next()\n if (rest.done) break\n for await (const _skip of rest.value) {\n void _skip\n }\n }\n } catch {\n // Deliberately swallowed — see above. A trailing worksheet we only read\n // to satisfy exceljs's cleanup contract cannot be allowed to speak for\n // the read the caller actually asked for. Worst case we leak the temp\n // files this drain existed to release, which is what `main` did on\n // EVERY read.\n }\n }\n\n // Reached only when a specific sheet was requested but never matched — the\n // first-sheet default always matches on a non-empty workbook.\n if (targetSheetIndex !== undefined && !matchedTarget) {\n throw new Error(`xlsx worksheet ${targetSheetIndex} not found`)\n }\n } finally {\n // Order matters: destroy the reader of the fd before closing the fd.\n source?.destroy()\n await handle.close().catch(() => {\n // Swallowed deliberately, and biome's `noUnsafeFinally` agrees: a throw\n // here would REPLACE whatever the try block was propagating, and what it\n // propagates is the point of this reader — an empty-header refusal has to\n // reach the caller intact. Closing a read-only fd we are finished with can\n // fail only in ways that are not actionable, and the fd is reclaimed at\n // process exit regardless.\n })\n }\n}\n"],"mappings":"0HAmCA,IAAa,EAAb,cAA0C,KAAM,CAE9C,gBAEA,YAAY,EAAyB,CACnC,MACE,mBAAmB,EAAgB,qIAErC,EACA,KAAK,KAAO,uBACZ,KAAK,gBAAkB,CACzB,CACF,EAYa,EAAb,cAAuC,KAAM,CAC3C,YAAY,EAAkB,CAC5B,MAAM,cAAc,EAAS,wBAAwB,EACrD,KAAK,KAAO,mBACd,CACF,EAcA,SAAS,EAAa,EAAsB,CAC1C,GAAI,GAAM,KAAyB,MAAO,GAC1C,GAAI,OAAO,GAAM,SAAU,OAAO,EAClC,GAAI,OAAO,GAAM,UAAY,OAAO,GAAM,UAAW,OAAO,OAAO,CAAC,EACpE,GAAI,aAAa,KAAM,OAAO,EAAE,YAAY,EAE5C,GAAI,aAAc,GAAK,MAAM,QAAQ,EAAE,QAAQ,EAC7C,OAAO,EAAE,SAAS,IAAK,GAAM,EAAE,IAAI,CAAC,CAAC,KAAK,EAAE,EAE9C,GAAI,SAAU,GAAK,OAAO,EAAE,MAAS,SAAU,OAAO,EAAE,KACxD,GAAI,WAAY,GAAK,EAAE,SAAW,IAAA,IAAa,EAAE,SAAW,KAAM,CAChE,IAAM,EAAI,EAAE,OAGZ,OAFI,aAAa,KAAa,EAAE,YAAY,EAErC,OAAO,GAAM,SAAW,GAAK,OAAO,CAAC,CAC9C,CACA,MAAO,EACT,CAGA,SAAS,EAAS,EAA8D,CAC9E,IAAM,EAAgB,CAAC,EACvB,GAAI,MAAM,QAAQ,CAAM,EAEtB,IAAK,IAAI,EAAI,EAAG,EAAI,EAAO,OAAQ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W,IAAM,KAAS,EAAK,OAGjC,CACF,MAAQ,CAMR,CACF,CAIA,GAAI,IAAqB,IAAA,IAAa,CAAC,EACrC,MAAU,MAAM,kBAAkB,EAAiB,WAAW,CAElE,QAAU,CAER,GAAQ,QAAQ,EAChB,MAAM,EAAO,MAAM,CAAC,CAAC,UAAY,CAOjC,CAAC,CACH,CACF"}
package/package.json ADDED
@@ -0,0 +1,81 @@
1
+ {
2
+ "name": "@murumets-ee/imports",
3
+ "version": "0.0.0-preview-20261014110621",
4
+ "license": "Elastic-2.0",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.mts",
9
+ "import": "./dist/index.mjs"
10
+ },
11
+ "./analyze": {
12
+ "types": "./dist/analyze/index.d.mts",
13
+ "import": "./dist/analyze/index.mjs"
14
+ },
15
+ "./mapping": {
16
+ "types": "./dist/mapping/index.d.mts",
17
+ "import": "./dist/mapping/index.mjs"
18
+ },
19
+ "./matching": {
20
+ "types": "./dist/matching/index.d.mts",
21
+ "import": "./dist/matching/index.mjs"
22
+ },
23
+ "./plugin": {
24
+ "types": "./dist/plugin.d.mts",
25
+ "import": "./dist/plugin.mjs"
26
+ },
27
+ "./worker": {
28
+ "types": "./dist/worker.d.mts",
29
+ "import": "./dist/worker.mjs"
30
+ },
31
+ "./transforms": {
32
+ "types": "./dist/transforms.d.mts",
33
+ "import": "./dist/transforms.mjs"
34
+ },
35
+ "./storage-resolver": {
36
+ "types": "./dist/storage-resolver.d.mts",
37
+ "import": "./dist/storage-resolver.mjs"
38
+ },
39
+ "./storage": {
40
+ "types": "./dist/storage.d.mts",
41
+ "import": "./dist/storage.mjs"
42
+ },
43
+ "./realtime": {
44
+ "types": "./dist/realtime/index.d.mts",
45
+ "import": "./dist/realtime/index.mjs"
46
+ }
47
+ },
48
+ "files": [
49
+ "dist"
50
+ ],
51
+ "dependencies": {
52
+ "csv-parse": "^5.5.3",
53
+ "drizzle-orm": "^0.45.2",
54
+ "exceljs": "^4.4.0",
55
+ "zod": "^3.24.1",
56
+ "@murumets-ee/core": "0.0.0-preview-20261014110621",
57
+ "@murumets-ee/db": "0.0.0-preview-20261014110621",
58
+ "@murumets-ee/entity": "0.0.0-preview-20261014110621",
59
+ "@murumets-ee/logging": "0.0.0-preview-20261014110621",
60
+ "@murumets-ee/search-elasticsearch": "0.0.0-preview-20261014110621",
61
+ "@murumets-ee/queue": "0.0.0-preview-20261014110621",
62
+ "@murumets-ee/storage": "0.0.0-preview-20261014110621"
63
+ },
64
+ "devDependencies": {
65
+ "@types/node": "^20.19.42",
66
+ "jszip": "3.10.1",
67
+ "tsdown": "^0.22.2",
68
+ "typescript": "^5.7.3",
69
+ "vitest": "^2.1.8"
70
+ },
71
+ "typeCoverage": {
72
+ "atLeast": 100
73
+ },
74
+ "scripts": {
75
+ "build": "tsdown",
76
+ "dev": "tsdown --watch",
77
+ "test": "vitest run",
78
+ "test:watch": "vitest",
79
+ "test:integration": "vitest run --config vitest.integration.config.ts"
80
+ }
81
+ }