@12-apps/marketplace 1.2.0 → 1.3.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.
Files changed (56) hide show
  1. package/ADOPTING.md +29 -4
  2. package/README.md +92 -3
  3. package/dist/99food/index.d.ts +48 -2
  4. package/dist/99food/index.js +84 -1
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-_iuSxvVD.d.ts → adapter-0l_EmuJA.d.ts} +172 -2
  7. package/dist/{chunk-CRYFYDQ2.js → chunk-AYYBRQJV.js} +28 -4
  8. package/dist/chunk-AYYBRQJV.js.map +1 -0
  9. package/dist/chunk-M2V4RFMA.js +23 -0
  10. package/dist/chunk-M2V4RFMA.js.map +1 -0
  11. package/dist/{chunk-24RQZPSV.js → chunk-RVBTARIY.js} +1 -1
  12. package/dist/chunk-RVBTARIY.js.map +1 -0
  13. package/dist/{chunk-D2X7TOR6.js → chunk-XUAFXNOH.js} +449 -85
  14. package/dist/chunk-XUAFXNOH.js.map +1 -0
  15. package/dist/{engine-D-a4mttc.d.ts → engine-CZsP8KWd.d.ts} +222 -2
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +2 -2
  18. package/dist/ifood/index.d.ts +10 -2
  19. package/dist/ifood/index.js +246 -69
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +30 -4
  22. package/dist/index.js +148 -9
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/server.d.ts +3 -2
  25. package/dist/manifest/server.js +2 -2
  26. package/dist/rappi/index.d.ts +1 -1
  27. package/dist/rappi/index.js +7 -1
  28. package/dist/rappi/index.js.map +1 -1
  29. package/dist/server/index.d.ts +12 -8
  30. package/dist/server/index.js +2 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +92 -1
  33. package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
  34. package/src/99food/catalogue.ts +117 -0
  35. package/src/99food/index.ts +4 -0
  36. package/src/99food/outbound.ts +3 -3
  37. package/src/core/adapter.ts +10 -1
  38. package/src/core/catalogue-category.ts +119 -0
  39. package/src/core/catalogue-ids.ts +23 -0
  40. package/src/core/catalogue-job.ts +332 -0
  41. package/src/core/catalogue-port.ts +173 -0
  42. package/src/core/catalogue-store.ts +172 -0
  43. package/src/core/catalogue-sweep.ts +43 -0
  44. package/src/core/catalogue.ts +226 -0
  45. package/src/core/engine.ts +46 -0
  46. package/src/core/outbound-sweep.ts +7 -2
  47. package/src/core/ports.ts +36 -0
  48. package/src/ifood/catalogue.ts +273 -0
  49. package/src/ifood/index.ts +4 -0
  50. package/src/ifood/outbound.ts +9 -6
  51. package/src/index.ts +40 -0
  52. package/src/rappi/index.ts +6 -0
  53. package/src/server/jobs.ts +39 -9
  54. package/dist/chunk-24RQZPSV.js.map +0 -1
  55. package/dist/chunk-CRYFYDQ2.js.map +0 -1
  56. package/dist/chunk-D2X7TOR6.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,9 +1,15 @@
1
1
  import {
2
+ CATALOGUE_GIVE_UP_MS,
3
+ CATALOGUE_ROW_SELECT,
4
+ CATALOGUE_STALE_MS,
2
5
  CLAIM_SELECT,
6
+ CatalogueRetryError,
3
7
  FetchOrderRetryError,
8
+ MARKETPLACE_CATALOGUE_JOB,
4
9
  MARKETPLACE_FETCH_ORDER_JOB,
5
10
  MARKETPLACE_OUTBOUND_JOB,
6
11
  MarketplaceAdapterRegistrationError,
12
+ NO_FAILURE,
7
13
  NO_STANDING_REQUEST,
8
14
  OUTBOUND_GIVE_UP_MS,
9
15
  OUTBOUND_STALE_MS,
@@ -11,9 +17,13 @@ import {
11
17
  PROVIDER_ID_PATTERN,
12
18
  awaitOrderBody,
13
19
  cancelAcceptance,
20
+ catalogueConnection,
21
+ catalogueDedupeKey,
22
+ catalogueTable,
14
23
  connectionMerchantId,
15
24
  createAdapterRegistry,
16
25
  deferInboxEvent,
26
+ enqueueCatalogue,
17
27
  enqueueOutbound,
18
28
  expireLapsedAcceptances,
19
29
  failCancellationRequest,
@@ -35,6 +45,7 @@ import {
35
45
  resolveIngestionTarget,
36
46
  resolveReason,
37
47
  resolveTenantByMerchant,
48
+ runCatalogue,
38
49
  runFetchOrder,
39
50
  runOutbound,
40
51
  saveMarketplaceIntegration,
@@ -42,12 +53,16 @@ import {
42
53
  suggestReason,
43
54
  sweepOutbound,
44
55
  tellCancellationFailed,
45
- upsertLink
46
- } from "./chunk-D2X7TOR6.js";
56
+ upsertLink,
57
+ viewOf
58
+ } from "./chunk-XUAFXNOH.js";
59
+ import {
60
+ stableUuid
61
+ } from "./chunk-M2V4RFMA.js";
47
62
  import {
48
63
  answered,
49
64
  outboundResultOf
50
- } from "./chunk-24RQZPSV.js";
65
+ } from "./chunk-RVBTARIY.js";
51
66
  import {
52
67
  __name
53
68
  } from "./chunk-7QVYU63E.js";
@@ -238,7 +253,7 @@ function requestOnly(ctx, plan) {
238
253
  __name(requestOnly, "requestOnly");
239
254
  async function admitAndClaim(ctx, clientId, planned, validateOnly) {
240
255
  await ctx.ports.transaction(async (tx) => {
241
- const refused = [];
256
+ const refused2 = [];
242
257
  for (const one of planned) {
243
258
  const admission = one.input.decision === "ACCEPT" ? one.input.admission ?? {} : {};
244
259
  const answer = await ctx.ports.order.admit({
@@ -250,18 +265,18 @@ async function admitAndClaim(ctx, clientId, planned, validateOnly) {
250
265
  });
251
266
  if (!answer.admitted) {
252
267
  const host = { code: answer.code, message: answer.message, details: answer.details };
253
- refused.push({ path: ["decisions", one.index], code: "HOST_REFUSED", host });
268
+ refused2.push({ path: ["decisions", one.index], code: "HOST_REFUSED", host });
254
269
  }
255
270
  }
256
- if (refused.length > 0) throw new Rollback(refused);
271
+ if (refused2.length > 0) throw new Rollback(refused2);
257
272
  for (const one of planned) {
258
273
  const claimed = await tx.marketplaceAcceptance.updateMany({
259
274
  where: { orderId: one.input.orderId, clientId, status: "AWAITING", ...NO_STANDING_REQUEST },
260
275
  data: one.data
261
276
  });
262
- if (claimed.count === 0) refused.push({ path: ["decisions", one.index, "orderId"], code: "CONFLICT" });
277
+ if (claimed.count === 0) refused2.push({ path: ["decisions", one.index, "orderId"], code: "CONFLICT" });
263
278
  }
264
- if (refused.length > 0) throw new Rollback(refused);
279
+ if (refused2.length > 0) throw new Rollback(refused2);
265
280
  if (validateOnly) throw new Rollback(null);
266
281
  });
267
282
  }
@@ -372,6 +387,117 @@ async function claimStoreCancellation(ctx, input, row, plan) {
372
387
  }
373
388
  __name(claimStoreCancellation, "claimStoreCancellation");
374
389
 
390
+ // src/core/catalogue.ts
391
+ var refused = /* @__PURE__ */ __name((code) => ({ kind: "refused", code }), "refused");
392
+ async function usableTable(ctx, provider) {
393
+ if (!ctx.ports.catalogue || !ctx.registry.get(provider)?.catalogue) return null;
394
+ return catalogueTable(ctx);
395
+ }
396
+ __name(usableTable, "usableTable");
397
+ async function findRow(table, target) {
398
+ return await table.findFirst({
399
+ where: { clientId: target.clientId, provider: target.provider, productId: target.productId },
400
+ select: CATALOGUE_ROW_SELECT
401
+ });
402
+ }
403
+ __name(findRow, "findRow");
404
+ async function queue(ctx, row, action) {
405
+ const payload = { clientId: row.clientId, publicationId: row.id, action };
406
+ await enqueueCatalogue(ctx, payload, catalogueDedupeKey(payload, row.requestedAt));
407
+ ctx.ports.publishChanged(row.clientId);
408
+ return { kind: "queued", publication: viewOf(row) };
409
+ }
410
+ __name(queue, "queue");
411
+ var validPrice = /* @__PURE__ */ __name((price) => price === void 0 || price === null || Number.isInteger(price) && price > 0, "validPrice");
412
+ async function publishRefusal(ctx, input) {
413
+ if (!validPrice(input.priceCents)) return "INVALID_PRICE";
414
+ if ("problem" in await catalogueConnection(ctx, input.clientId, input.provider)) return "NOT_CONNECTED";
415
+ const items = await ctx.ports.catalogue?.items(input.clientId, [input.productId]);
416
+ return items?.has(input.productId) ? null : "UNKNOWN_PRODUCT";
417
+ }
418
+ __name(publishRefusal, "publishRefusal");
419
+ async function publishToCatalogue(ctx, input) {
420
+ const table = await usableTable(ctx, input.provider);
421
+ if (!table) return refused("UNSUPPORTED");
422
+ const refusal = await publishRefusal(ctx, input);
423
+ if (refusal) return refused(refusal);
424
+ const existing = await findRow(table, input);
425
+ const now = ctx.ports.clock.now();
426
+ const price = input.priceCents === void 0 ? {} : { priceCents: input.priceCents };
427
+ const samePrice = input.priceCents === void 0 || input.priceCents === existing?.priceCents;
428
+ const asked = existing?.status === "PUBLISHING" && samePrice ? {} : { requestedAt: now };
429
+ const row = await table.upsert({
430
+ where: { clientId_provider_productId: { clientId: input.clientId, provider: input.provider, productId: input.productId } },
431
+ create: { clientId: input.clientId, provider: input.provider, productId: input.productId, status: "PUBLISHING", requestedAt: now, ...price },
432
+ update: { status: "PUBLISHING", ...NO_FAILURE, ...asked, ...price },
433
+ select: CATALOGUE_ROW_SELECT
434
+ });
435
+ return queue(ctx, row, "publish");
436
+ }
437
+ __name(publishToCatalogue, "publishToCatalogue");
438
+ async function withdrawFromCatalogue(ctx, target) {
439
+ const table = await usableTable(ctx, target.provider);
440
+ if (!table) return refused("UNSUPPORTED");
441
+ const existing = await findRow(table, target);
442
+ if (!existing || existing.status === "WITHDRAWN") return { kind: "unchanged", publication: existing && viewOf(existing) };
443
+ if (existing.status === "WITHDRAWING") return queue(ctx, existing, "withdraw");
444
+ const now = ctx.ports.clock.now();
445
+ const local = await connectionMerchantId(ctx, target.clientId, target.provider) === null;
446
+ const data = local ? { status: "WITHDRAWN", withdrawnAt: now, requestedAt: now, ...NO_FAILURE } : { status: "WITHDRAWING", requestedAt: now, ...NO_FAILURE };
447
+ const moved = await table.updateMany({ where: { id: existing.id, status: existing.status }, data });
448
+ const row = await findRow(table, target) ?? existing;
449
+ if (moved.count === 0 || local) {
450
+ ctx.ports.publishChanged(target.clientId);
451
+ return { kind: "unchanged", publication: viewOf(row) };
452
+ }
453
+ return queue(ctx, row, "withdraw");
454
+ }
455
+ __name(withdrawFromCatalogue, "withdrawFromCatalogue");
456
+ async function readCatalogueState(ctx, input) {
457
+ const table = await catalogueTable(ctx);
458
+ if (!table || input.productIds.length === 0) return [];
459
+ const rows = await table.findMany({
460
+ where: {
461
+ clientId: input.clientId,
462
+ productId: { in: [...input.productIds] },
463
+ ...input.providers ? { provider: { in: [...input.providers] } } : {}
464
+ },
465
+ select: CATALOGUE_ROW_SELECT
466
+ });
467
+ return rows.map(viewOf);
468
+ }
469
+ __name(readCatalogueState, "readCatalogueState");
470
+ var IN_MENU = ["PUBLISHING", "PUBLISHED", "FAILED"];
471
+ function menuPrice(row, storePrice) {
472
+ if (row.status !== "FAILED") return row.priceCents ?? storePrice;
473
+ const live = row.publishedAt !== null && (row.withdrawnAt === null || row.withdrawnAt < row.publishedAt);
474
+ const republishFailed = row.failedAction === "PUBLISH" && live;
475
+ return republishFailed ? row.sentPriceCents ?? row.priceCents ?? storePrice : null;
476
+ }
477
+ __name(menuPrice, "menuPrice");
478
+ async function readCatalogueDocument(ctx, input) {
479
+ const catalogue = ctx.registry.get(input.provider)?.catalogue;
480
+ const table = await usableTable(ctx, input.provider);
481
+ if (!table || catalogue?.mode !== "pull") return { kind: "refused", code: "UNSUPPORTED" };
482
+ const connection = await catalogueConnection(ctx, input.clientId, input.provider);
483
+ if ("problem" in connection) return { kind: "refused", code: "NOT_CONNECTED" };
484
+ const rows = await table.findMany({
485
+ where: { clientId: input.clientId, provider: input.provider, status: { in: IN_MENU } },
486
+ select: CATALOGUE_ROW_SELECT,
487
+ orderBy: { createdAt: "asc" }
488
+ });
489
+ const items = await ctx.ports.catalogue?.items(input.clientId, rows.map((row) => row.productId)) ?? /* @__PURE__ */ new Map();
490
+ const entries = rows.flatMap((row) => {
491
+ const item = items.get(row.productId);
492
+ const priceCents = item ? menuPrice(row, item.priceCents) : null;
493
+ if (!item || priceCents === null) return [];
494
+ return [{ ...item, priceCents, ref: row.id, productId: row.productId, externalId: row.externalId, storedImage: null }];
495
+ });
496
+ const document = catalogue.menuDocument({ externalMerchantId: connection.externalMerchantId, entries, options: input.options });
497
+ return { kind: "document", document };
498
+ }
499
+ __name(readCatalogueDocument, "readCatalogueDocument");
500
+
375
501
  // src/core/pipeline.ts
376
502
  function normalizeEvent(ctx, provider, payload) {
377
503
  return ctx.registry.get(provider)?.normalize(payload) ?? null;
@@ -563,12 +689,23 @@ function createMarketplaceEngine(config) {
563
689
  reprocess: /* @__PURE__ */ __name((event) => reprocessStoredDelivery(ctx, event), "reprocess"),
564
690
  sweepOutbound: /* @__PURE__ */ __name((now) => sweepOutbound(ctx, now ?? ports.clock.now()), "sweepOutbound"),
565
691
  runOutbound: /* @__PURE__ */ __name((payload, attempt) => runOutbound(ctx, payload, attempt), "runOutbound"),
566
- runFetchOrder: /* @__PURE__ */ __name((payload, attempt) => runFetchOrder(ctx, payload, attempt), "runFetchOrder")
692
+ runFetchOrder: /* @__PURE__ */ __name((payload, attempt) => runFetchOrder(ctx, payload, attempt), "runFetchOrder"),
693
+ // Null too when the host bound no catalogue port: nothing could be published.
694
+ catalogueMode: /* @__PURE__ */ __name((provider) => ports.catalogue ? registry.get(provider)?.catalogue?.mode ?? null : null, "catalogueMode"),
695
+ publish: /* @__PURE__ */ __name((input) => publishToCatalogue(ctx, input), "publish"),
696
+ withdraw: /* @__PURE__ */ __name((input) => withdrawFromCatalogue(ctx, input), "withdraw"),
697
+ catalogueState: /* @__PURE__ */ __name((input) => readCatalogueState(ctx, input), "catalogueState"),
698
+ catalogueDocument: /* @__PURE__ */ __name((input) => readCatalogueDocument(ctx, input), "catalogueDocument"),
699
+ runCatalogue: /* @__PURE__ */ __name((payload, attempt) => runCatalogue(ctx, payload, attempt), "runCatalogue")
567
700
  };
568
701
  }
569
702
  __name(createMarketplaceEngine, "createMarketplaceEngine");
570
703
  export {
704
+ CATALOGUE_GIVE_UP_MS,
705
+ CATALOGUE_STALE_MS,
706
+ CatalogueRetryError,
571
707
  FetchOrderRetryError,
708
+ MARKETPLACE_CATALOGUE_JOB,
572
709
  MARKETPLACE_FETCH_ORDER_JOB,
573
710
  MARKETPLACE_OUTBOUND_JOB,
574
711
  MarketplaceAdapterRegistrationError,
@@ -577,11 +714,13 @@ export {
577
714
  OutboundRetryError,
578
715
  PROVIDER_ID_PATTERN,
579
716
  answered,
717
+ catalogueDedupeKey,
580
718
  createAdapterRegistry,
581
719
  createMarketplaceEngine,
582
720
  outboundDedupeKey,
583
721
  outboundResultOf,
584
722
  resolveReason,
723
+ stableUuid,
585
724
  suggestReason
586
725
  };
587
726
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/bulk.ts","../src/core/decisions.ts","../src/core/pipeline.ts","../src/core/state.ts","../src/core/engine.ts"],"sourcesContent":["import {\n listMarketplaceIntegrations,\n saveMarketplaceIntegration,\n type MarketplaceIntegrationView,\n type SaveMarketplaceIntegrationInput,\n} from \"./integration\";\nimport { upsertLink, type MarketplaceMenuLinkView } from \"./menu-links\";\nimport type { EngineContext, MarketplaceAuditEntry, MarketplaceDb } from \"./ports\";\n\n/**\n * The bulk writes: one call, many rows, all-or-nothing.\n *\n * Every row is validated first (cross-row duplicates, unknown providers, a\n * catalog id that is not the store's, an archive of nothing) and every problem\n * is returned with its path; any problem writes nothing. Then ONE transaction\n * writes every row, or none. `validateOnly` validates and writes nothing.\n * Idempotent on the natural key: a connection is `(store, provider)`, a SKU\n * link `(store, provider, externalSku)`.\n */\n\n/** Why a bulk row was refused. Vocabulary, not copy. */\nexport type BulkProblemCode =\n | \"DUPLICATE\"\n | \"UNKNOWN_PROVIDER\"\n | \"NOTHING_TO_UPDATE\"\n | \"NOT_FOUND\"\n | \"CATALOG_ITEM_NOT_FOUND\";\n\nexport interface BulkProblem {\n path: (string | number)[];\n code: BulkProblemCode;\n}\n\nexport type BulkResult<T> =\n | { kind: \"saved\"; validateOnly: boolean; rows: T[] }\n | { kind: \"refused\"; problems: BulkProblem[] };\n\n/** One connection row: an upsert of its settings, an archive, or an unarchive. */\nexport type IntegrationRowInput =\n | ({ operation?: \"upsert\" } & Omit<SaveMarketplaceIntegrationInput, \"clientId\">)\n | { operation: \"archive\" | \"unarchive\"; provider: string; reason?: string | null };\n\n/** One SKU link: map it to a catalog id, or unmap it with `menuItemId: null`. */\nexport interface MenuLinkRowInput {\n provider: string;\n externalSku: string;\n externalName?: string;\n menuItemId: string | null;\n}\n\n/** The key of each row seen twice, as problems. */\nfunction duplicates<T>(rows: readonly T[], keyOf: (row: T) => string, list: string, field: string): BulkProblem[] {\n const seen = new Set<string>();\n return rows.flatMap((row, index) => {\n const key = keyOf(row);\n if (!seen.has(key)) {\n seen.add(key);\n return [];\n }\n return [{ path: [list, index, field], code: \"DUPLICATE\" as const }];\n });\n}\n\nfunction unknownProviders(ctx: EngineContext, rows: readonly { provider: string }[], list: string): BulkProblem[] {\n return rows.flatMap((row, index) =>\n ctx.registry.has(row.provider) ? [] : [{ path: [list, index, \"provider\"], code: \"UNKNOWN_PROVIDER\" as const }],\n );\n}\n\nconst SETTING_KEYS = [\"enabled\", \"environment\", \"externalMerchantId\", \"autoAccept\", \"ackSlaSeconds\", \"credentials\"] as const;\n\nfunction integrationRowProblems(\n row: IntegrationRowInput,\n index: number,\n existing: ReadonlySet<string>,\n): BulkProblem[] {\n if (row.operation === \"archive\" || row.operation === \"unarchive\") {\n return existing.has(row.provider) ? [] : [{ path: [\"integrations\", index, \"provider\"], code: \"NOT_FOUND\" }];\n }\n const settings = row as Partial<Record<(typeof SETTING_KEYS)[number], unknown>>;\n const changes = SETTING_KEYS.some((key) => settings[key] !== undefined);\n return changes ? [] : [{ path: [\"integrations\", index], code: \"NOTHING_TO_UPDATE\" }];\n}\n\n/** Thrown inside the transaction to roll a `validateOnly` call back. */\nclass ValidateOnly extends Error {\n constructor() {\n super(\"validate only\");\n }\n}\n\n/** Run `write` in one transaction; a `validateOnly` call is rolled back. */\nasync function inTransaction<T>(ctx: EngineContext, validateOnly: boolean, write: (db: MarketplaceDb) => Promise<T>): Promise<T | null> {\n let written: T | null = null;\n try {\n await ctx.ports.transaction(async (db) => {\n written = await write(db);\n if (validateOnly) throw new ValidateOnly();\n });\n } catch (error) {\n if (!(error instanceof ValidateOnly)) throw error;\n }\n return written;\n}\n\nasync function writeIntegration(\n ctx: EngineContext,\n db: MarketplaceDb,\n clientId: string,\n row: IntegrationRowInput,\n now: Date,\n): Promise<MarketplaceIntegrationView | null> {\n if (row.operation === \"archive\" || row.operation === \"unarchive\") {\n await db.marketplaceIntegration.updateMany({\n where: { clientId, provider: row.provider },\n data: { archivedAt: row.operation === \"archive\" ? now : null },\n });\n return null;\n }\n const settings: Omit<IntegrationRowInput, \"operation\"> & { operation?: unknown } = { ...row };\n delete settings.operation;\n return saveMarketplaceIntegration(ctx, { clientId, ...(settings as Omit<SaveMarketplaceIntegrationInput, \"clientId\">) }, db);\n}\n\n/**\n * Create, patch, archive or unarchive many connections at once. A connection\n * is never deleted: archiving is reversible, and each archive and unarchive is\n * an audit line through the host's `audit` port, in the same transaction.\n */\nexport async function upsertIntegrations(\n ctx: EngineContext,\n input: { clientId: string; actorId: string | null; rows: readonly IntegrationRowInput[]; validateOnly?: boolean },\n): Promise<BulkResult<MarketplaceIntegrationView>> {\n const existing = new Set(\n (await listMarketplaceIntegrations(ctx, input.clientId, { includeArchived: true })).map((row) => row.provider),\n );\n const problems = [\n ...duplicates(input.rows, (row) => row.provider, \"integrations\", \"provider\"),\n ...unknownProviders(ctx, input.rows, \"integrations\"),\n ...input.rows.flatMap((row, index) => integrationRowProblems(row, index, existing)),\n ];\n if (problems.length > 0) return { kind: \"refused\", problems };\n\n const validateOnly = input.validateOnly === true;\n const now = ctx.ports.clock.now();\n // The audit lines are written INSIDE the archive's transaction, through its\n // client: an archive never lands without its line, and an audit that fails\n // rolls the archive back. A `validateOnly` call rolls both back.\n await inTransaction(ctx, validateOnly, async (db) => {\n for (const row of input.rows) await writeIntegration(ctx, db, input.clientId, row, now);\n await auditArchives(ctx, db, input, now);\n });\n const providers = input.rows.map((row) => row.provider);\n const rows = validateOnly\n ? []\n : await listMarketplaceIntegrations(ctx, input.clientId, { providers, includeArchived: true });\n return { kind: \"saved\", validateOnly, rows };\n}\n\nasync function auditArchives(\n ctx: EngineContext,\n db: MarketplaceDb,\n input: { clientId: string; actorId: string | null; rows: readonly IntegrationRowInput[] },\n now: Date,\n): Promise<void> {\n for (const row of input.rows) {\n if (row.operation !== \"archive\" && row.operation !== \"unarchive\") continue;\n const entry: MarketplaceAuditEntry = {\n clientId: input.clientId,\n actorId: input.actorId,\n action: row.operation === \"archive\" ? \"marketplace.integration.archive\" : \"marketplace.integration.unarchive\",\n provider: row.provider,\n reason: row.reason ?? null,\n at: now,\n };\n await ctx.ports.audit.record(entry, db);\n }\n}\n\n/** Map or unmap many SKUs at once; every catalog id must be the store's. */\nexport async function upsertMenuLinks(\n ctx: EngineContext,\n input: { clientId: string; rows: readonly MenuLinkRowInput[]; validateOnly?: boolean },\n): Promise<BulkResult<MarketplaceMenuLinkView>> {\n const problems = [\n ...duplicates(input.rows, (row) => `${row.provider}\\u0000${row.externalSku}`, \"links\", \"externalSku\"),\n ...unknownProviders(ctx, input.rows, \"links\"),\n ];\n for (const [index, row] of input.rows.entries()) {\n if (row.menuItemId !== null && !(await ctx.ports.order.catalogHas(input.clientId, row.menuItemId))) {\n problems.push({ path: [\"links\", index, \"menuItemId\"], code: \"CATALOG_ITEM_NOT_FOUND\" });\n }\n }\n if (problems.length > 0) return { kind: \"refused\", problems };\n\n const validateOnly = input.validateOnly === true;\n const written = await inTransaction(ctx, validateOnly, async (db) => {\n const rows: MarketplaceMenuLinkView[] = [];\n for (const row of input.rows) rows.push(await upsertLink(db, { clientId: input.clientId, ...row }));\n return rows;\n });\n return { kind: \"saved\", validateOnly, rows: written ?? [] };\n}\n","import type { AcceptanceStatus, CancellationStatus } from \"./acceptance\";\nimport {\n CLAIM_SELECT,\n NO_STANDING_REQUEST,\n notPendingProblem,\n planCancellation,\n refusalData,\n requestData,\n type CancellationPlan,\n type ClaimRow,\n type DecisionProblem,\n type DecisionProblemCode,\n} from \"./cancellation\";\nimport { requestsFirst, tellCancellationFailed } from \"./cancellation-outcome\";\nimport { enqueueOutbound } from \"./outbound-queue\";\nimport type { EngineContext, MarketplaceAdmission, MarketplaceDb } from \"./ports\";\n\n/**\n * The store's decisions on orders on the clock — ONE path for every surface\n * (the host's board, the admin route, the MCP tool), and all-or-nothing:\n *\n * 1. every decision is validated against its row (still AWAITING, the reason\n * the marketplace's, the offending SKUs the order's) before anything runs;\n * 2. inside ONE transaction the host ADMITS each decision (`order.admit`: the\n * stock ask, the draw) and the engine claims each row on `AWAITING`. A\n * host refusal or a lost claim rolls the whole call back;\n * 3. after the commit, each outbound call is QUEUED FIRST, then the host's\n * half runs (`onAccepted` / `onRefused`). A host half that throws cannot\n * lose the call; it is logged, and the decision stands.\n *\n * A queue that refuses the job loses nothing either: the outbound sweep\n * (`./outbound-sweep.ts`) re-queues every request still owed.\n */\n\n/** The two things a person can do to an order on the clock. */\nexport type AcceptanceDecision = \"ACCEPT\" | \"REJECT\";\n\n/** One decision, as a caller states it. */\nexport type DecisionInput =\n | {\n orderId: string;\n decision: \"ACCEPT\";\n /** What the person confirmed, for the host's admission. */\n admission?: MarketplaceAdmission;\n /** Minutes to prepare, for a marketplace whose confirm states one. */\n preparationMinutes?: number | null;\n }\n | {\n orderId: string;\n decision: \"REJECT\";\n /** One of the marketplace's codes; its first reason when absent. */\n reasonCode?: string | null;\n /** The order's SKUs a reason that `needsItems` names. */\n offendingSkus?: readonly string[];\n };\n\n/**\n * One decided row. `status` is the row's status after the call: ACCEPTED or\n * REJECTED, or — for a refusal of a host that requests first (FUT-4758) —\n * the status it keeps (AWAITING, ACCEPTED) while `cancellation` waits.\n */\nexport interface DecidedRow {\n orderId: string;\n status: AcceptanceStatus;\n cancellation: CancellationStatus | null;\n reasonCode: string | null;\n offendingSkus: string[];\n}\n\n/** What a call did: every row decided, or nothing written and every problem named. */\nexport type DecideManyResult =\n | { kind: \"decided\"; validateOnly: boolean; rows: DecidedRow[] }\n | { kind: \"refused\"; problems: DecisionProblem[] };\n\n/** One decision's result, for a caller deciding one order. */\nexport type DecisionResult =\n | ({ kind: \"decided\" } & DecidedRow)\n | {\n kind: \"stale\";\n /** Why: gone, decided already (I4: answer it as done), expired, or lost to a race. */\n reason: Extract<DecisionProblemCode, \"NOT_FOUND\" | \"ALREADY_DECIDED\" | \"EXPIRED\" | \"CONFLICT\">;\n status: AcceptanceStatus | null;\n }\n | {\n kind: \"invalidReason\";\n problem: Extract<DecisionProblemCode, \"INVALID_REASON\" | \"ITEMS_REQUIRED\" | \"UNKNOWN_ITEM\">;\n validCodes: string[];\n }\n | { kind: \"refusedByHost\"; code: string; message: string; details?: unknown };\n\n/** A planned decision: the row, the claim's data, and what it becomes. */\ninterface PlannedDecision {\n input: DecisionInput;\n index: number;\n row: ClaimRow;\n data: Record<string, unknown>;\n decided: DecidedRow;\n /** A refusal that only REQUESTS the cancellation: the host cancels on the marketplace's confirmation. */\n requestOnly: boolean;\n}\n\n/** Thrown inside the transaction to roll it back, carrying the reason. */\nclass Rollback extends Error {\n constructor(readonly problems: DecisionProblem[] | null) {\n super(\"rollback\");\n }\n}\n\nfunction duplicateProblems(decisions: readonly DecisionInput[]): DecisionProblem[] {\n const seen = new Set<string>();\n return decisions.flatMap((decision, index) => {\n if (!seen.has(decision.orderId)) {\n seen.add(decision.orderId);\n return [];\n }\n return [{ path: [\"decisions\", index, \"orderId\"], code: \"DUPLICATE\" as const }];\n });\n}\n\nfunction decidedOf(input: DecisionInput, plan: CancellationPlan | null, keptStatus?: string): DecidedRow {\n const decided: AcceptanceStatus = input.decision === \"ACCEPT\" ? \"ACCEPTED\" : \"REJECTED\";\n return {\n orderId: input.orderId,\n status: (keptStatus as AcceptanceStatus | undefined) ?? decided,\n cancellation: plan?.status ?? null,\n reasonCode: plan?.reason?.code ?? null,\n offendingSkus: plan?.skus ?? [],\n };\n}\n\n/**\n * The columns of a request that no longer stands, cleared, but for its\n * TOMBSTONE: `cancellation_requested_at` stays, naming the request that was\n * made (FUT-4765, R3-N2).\n *\n * A synchronous marketplace answers a cancellation in the call's response,\n * never by event. When the sweep times a request out while that call is still\n * in flight and the store then accepts the order, the late answer must still\n * find the request it answers: \"cancelled\" means the marketplace cancelled the\n * order, and dropping it would leave the order ACCEPTED here and cancelled\n * there. The outbound job matches a status-less row by this instant\n * (`stampConfirmedCancellation`); nothing else reads it without a status.\n */\nconst CLEARED_REQUEST = {\n cancellationStatus: null,\n cancellationReasonCode: null,\n cancellationOffendingSkus: null,\n cancellationFailureReason: null,\n} as const;\n\n/** Plan one decision against its row, or name what is wrong with it. */\nfunction planOne(\n ctx: EngineContext,\n input: DecisionInput,\n index: number,\n row: ClaimRow | undefined,\n now: Date,\n): PlannedDecision | DecisionProblem[] {\n const path = [\"decisions\", index];\n const stale = notPendingProblem(row, path);\n if (stale || !row) return stale ? [stale] : [];\n if (input.decision === \"ACCEPT\") {\n // An accept after a FAILED request (FUT-4758) leaves no request behind it,\n // only its tombstone (see CLEARED_REQUEST).\n const data = {\n status: \"ACCEPTED\",\n acknowledgedAt: now,\n preparationMinutes: input.preparationMinutes ?? null,\n ...(row.cancellationStatus === null ? {} : CLEARED_REQUEST),\n };\n return { input, index, row, data, decided: decidedOf(input, null), requestOnly: false };\n }\n const plan = planCancellation(ctx.registry.get(row.provider), input, row, path);\n if (Array.isArray(plan)) return plan;\n if (requestOnly(ctx, plan)) {\n return { input, index, row, data: requestData(plan, now), decided: decidedOf(input, plan, row.status), requestOnly: true };\n }\n return { input, index, row, data: refusalData(plan, row.status, now), decided: decidedOf(input, plan), requestOnly: false };\n}\n\n/**\n * Whether a refusal only REQUESTS the cancellation (FUT-4758): the host\n * requests first (it binds `onCancellationConfirmed`), and there is a request\n * to make — PENDING, or FAILED at once for a marketplace that cannot take it\n * through its API (a person cancels in its app, and its event confirms). A\n * provider with no adapter has nothing to ask: refused at once, as ever.\n */\nfunction requestOnly(ctx: EngineContext, plan: CancellationPlan): boolean {\n return requestsFirst(ctx) && plan.status !== null;\n}\n\n/** Admit every decision through the host, then claim every row, in one transaction. */\nasync function admitAndClaim(\n ctx: EngineContext,\n clientId: string,\n planned: readonly PlannedDecision[],\n validateOnly: boolean,\n): Promise<void> {\n await ctx.ports.transaction(async (tx: MarketplaceDb) => {\n const refused: DecisionProblem[] = [];\n for (const one of planned) {\n const admission = one.input.decision === \"ACCEPT\" ? (one.input.admission ?? {}) : {};\n const answer = await ctx.ports.order.admit({\n clientId,\n orderId: one.input.orderId,\n decision: one.input.decision,\n admission,\n db: tx,\n });\n if (!answer.admitted) {\n const host = { code: answer.code, message: answer.message, details: answer.details };\n refused.push({ path: [\"decisions\", one.index], code: \"HOST_REFUSED\", host });\n }\n }\n if (refused.length > 0) throw new Rollback(refused);\n for (const one of planned) {\n const claimed = await tx.marketplaceAcceptance.updateMany({\n where: { orderId: one.input.orderId, clientId, status: \"AWAITING\", ...NO_STANDING_REQUEST },\n data: one.data,\n });\n if (claimed.count === 0) refused.push({ path: [\"decisions\", one.index, \"orderId\"], code: \"CONFLICT\" });\n }\n if (refused.length > 0) throw new Rollback(refused);\n if (validateOnly) throw new Rollback(null);\n });\n}\n\n/** After the commit: queue each owed call FIRST, then the host's half, which may not lose it. */\nasync function afterCommit(ctx: EngineContext, clientId: string, planned: readonly PlannedDecision[]): Promise<void> {\n for (const one of planned) {\n const { orderId } = one.input;\n if (one.input.decision === \"ACCEPT\") {\n await enqueueOutbound(ctx, { clientId, orderId, action: \"confirm\" }, one.row.provider);\n } else if (one.decided.cancellation === \"PENDING\") {\n await enqueueOutbound(ctx, { clientId, orderId, action: \"requestCancellation\" }, one.row.provider);\n }\n try {\n if (one.decided.status === \"ACCEPTED\" && one.input.decision === \"ACCEPT\") await ctx.ports.order.onAccepted(clientId, orderId);\n else if (!one.requestOnly) await ctx.ports.order.onRefused(clientId, orderId, \"REJECTED\");\n // A request the marketplace cannot take through its API failed at once:\n // the order stays, and a person cancels it in the marketplace's app.\n else if (one.decided.cancellation === \"FAILED\") await tellCancellationFailed(ctx, clientId, orderId, \"REFUSED\");\n } catch (error) {\n ctx.ports.logger.error(\n `marketplace.decide: order ${orderId} is ${one.decided.status} but the host's half failed: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n }\n ctx.ports.publishChanged(clientId);\n}\n\n/** Read every row a call names, in one statement. */\nasync function readRows(ctx: EngineContext, clientId: string, orderIds: string[]): Promise<Map<string, ClaimRow>> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceAcceptance.findMany({\n where: { clientId, orderId: { in: orderIds } },\n select: CLAIM_SELECT,\n })) as ClaimRow[];\n return new Map(rows.map((row) => [row.orderId, row]));\n}\n\n/**\n * Decide many orders at once, all-or-nothing. `validateOnly` runs everything —\n * the host's admission included — and rolls it back.\n */\nexport async function decideMany(\n ctx: EngineContext,\n input: { clientId: string; decisions: readonly DecisionInput[]; validateOnly?: boolean; now?: Date },\n): Promise<DecideManyResult> {\n const duplicates = duplicateProblems(input.decisions);\n if (duplicates.length > 0) return { kind: \"refused\", problems: duplicates };\n const now = input.now ?? ctx.ports.clock.now();\n const rows = await readRows(ctx, input.clientId, input.decisions.map((decision) => decision.orderId));\n\n const planned: PlannedDecision[] = [];\n const problems: DecisionProblem[] = [];\n input.decisions.forEach((decision, index) => {\n const plan = planOne(ctx, decision, index, rows.get(decision.orderId), now);\n if (Array.isArray(plan)) problems.push(...plan);\n else planned.push(plan);\n });\n if (problems.length > 0) return { kind: \"refused\", problems };\n\n const validateOnly = input.validateOnly === true;\n try {\n await admitAndClaim(ctx, input.clientId, planned, validateOnly);\n } catch (error) {\n if (!(error instanceof Rollback)) throw error;\n if (error.problems) return { kind: \"refused\", problems: error.problems };\n }\n if (!validateOnly) await afterCommit(ctx, input.clientId, planned);\n return { kind: \"decided\", validateOnly, rows: planned.map((one) => one.decided) };\n}\n\nconst STALE_CODES = new Set<DecisionProblemCode>([\"NOT_FOUND\", \"ALREADY_DECIDED\", \"EXPIRED\", \"CONFLICT\"]);\n\n/** One decision's problem, as the single-order result names it. */\nfunction resultOfProblem(problem: DecisionProblem): DecisionResult {\n if (problem.code === \"HOST_REFUSED\") {\n const host = problem.host ?? { code: \"\", message: \"\" };\n return { kind: \"refusedByHost\", code: host.code, message: host.message, details: host.details };\n }\n if (STALE_CODES.has(problem.code)) {\n const reason = problem.code as Extract<DecisionResult, { kind: \"stale\" }>[\"reason\"];\n return { kind: \"stale\", reason, status: problem.status ?? null };\n }\n const invalid = problem.code as Extract<DecisionResult, { kind: \"invalidReason\" }>[\"problem\"];\n return { kind: \"invalidReason\", problem: invalid, validCodes: problem.validCodes ?? [] };\n}\n\n/** Decide ONE order: `decideMany` with one decision. */\nexport async function decideOne(\n ctx: EngineContext,\n input: { clientId: string; now?: Date } & DecisionInput,\n): Promise<DecisionResult> {\n const { clientId, now, ...decision } = input;\n const result = await decideMany(ctx, { clientId, decisions: [decision as DecisionInput], now });\n if (result.kind === \"decided\") {\n const [row] = result.rows;\n if (row) return { kind: \"decided\", ...row };\n }\n const [problem] = result.kind === \"refused\" ? result.problems : [];\n return problem ? resultOfProblem(problem) : { kind: \"stale\", reason: \"CONFLICT\", status: null };\n}\n\n/**\n * The STORE asks to cancel an order — before or after accepting it. Stamps\n * the request the marketplace must hear and queues it; the engine neither\n * admits nor calls `onRefused`: it records and queues, and nothing else.\n *\n * REQUEST FIRST (FUT-4758), for a host that binds `onCancellationConfirmed`:\n * only the request moves. The decision status stays AWAITING or ACCEPTED while\n * the marketplace answers, so the host keeps the order as it was until then,\n * and a refused or timed-out request (`onCancellationFailed`) leaves it\n * acceptable. The marketplace's confirmation moves it to REJECTED. A FAILED\n * request may be asked again. A host that binds no `onCancellationConfirmed`\n * cancelled first and gets 1.0.0's stamps exactly: REJECTED at once.\n *\n * The returned row's `status` is the row's after the call.\n *\n * `stale` (ALREADY_DECIDED) when the marketplace already cancelled it, the\n * clock lapsed (EXPIRED), or a request is already waiting.\n */\nexport async function recordStoreCancellation(\n ctx: EngineContext,\n input: { clientId: string; orderId: string; reasonCode?: string | null; offendingSkus?: readonly string[]; now?: Date },\n): Promise<DecisionResult> {\n const row = (await readRows(ctx, input.clientId, [input.orderId])).get(input.orderId);\n const stale = notPendingProblem(row, [], [\"AWAITING\", \"ACCEPTED\"]);\n if (stale || !row) return stale ? resultOfProblem(stale) : { kind: \"stale\", reason: \"NOT_FOUND\", status: null };\n const plan = planCancellation(ctx.registry.get(row.provider), input, row, []);\n if (Array.isArray(plan)) return resultOfProblem(plan[0]!);\n\n return claimStoreCancellation(ctx, input, row, plan);\n}\n\n/** Stamp the store's cancellation (the request alone, or 1.0.0's REJECTED), queue it, and tell the host. */\nasync function claimStoreCancellation(\n ctx: EngineContext,\n input: { clientId: string; orderId: string; now?: Date },\n row: ClaimRow,\n plan: CancellationPlan,\n): Promise<DecisionResult> {\n const now = input.now ?? ctx.ports.clock.now();\n const db = await ctx.ports.db();\n const only = requestOnly(ctx, plan);\n const claimed = await db.marketplaceAcceptance.updateMany({\n where: { orderId: input.orderId, clientId: input.clientId, status: row.status, ...NO_STANDING_REQUEST },\n data: only ? requestData(plan, now) : refusalData(plan, row.status, now),\n });\n if (claimed.count === 0) return { kind: \"stale\", reason: \"CONFLICT\", status: null };\n if (plan.status === \"PENDING\") {\n await enqueueOutbound(ctx, { clientId: input.clientId, orderId: input.orderId, action: \"requestCancellation\" }, row.provider);\n }\n ctx.ports.publishChanged(input.clientId);\n if (only && plan.status === \"FAILED\") await tellCancellationFailed(ctx, input.clientId, input.orderId, \"REFUSED\");\n return { kind: \"decided\", ...decidedOf({ orderId: input.orderId, decision: \"REJECT\" }, plan, only ? row.status : undefined) };\n}\n","import { cancelAcceptance } from \"./acceptance\";\nimport { failCancellationRequest } from \"./cancellation\";\nimport { awaitOrderBody, merchantMismatch, requeueOwedFetch } from \"./fetch-order\";\nimport { deferInboxEvent, recordInboxEvent, settleInboxEvent } from \"./inbox\";\nimport { ingestMarketplaceOrder, type IngestSettings } from \"./ingest\";\nimport { connectionMerchantId, resolveIngestionTarget } from \"./integration\";\nimport { markCancelledBeforeIngest } from \"./order-fetch-marks\";\nimport type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from \"./types\";\n\n/**\n * One delivery, start to finish: normalize → inbox → ingest.\n *\n * The ONE path both producers use. The webhook calls it, and so does the\n * reconciliation retry sweep — which is the whole reason it is a module rather\n * than the body of a route handler. Two producers with two copies of this\n * sequence is how a webhook and a poll come to disagree about what an order is,\n * and the disagreement only shows up on the orders that took the unlucky path.\n */\n\n/**\n * Normalize a raw payload through the provider's adapter, or null when no\n * adapter is registered for it or the adapter refuses the payload. The\n * registry is the only dispatch: there is no provider branch here.\n */\nexport function normalizeEvent(\n ctx: EngineContext,\n provider: MarketplaceProvider,\n payload: unknown,\n): NormalizedEvent | null {\n return ctx.registry.get(provider)?.normalize(payload) ?? null;\n}\n\n/** How a delivery ended. `duplicate` and `ignored` are both ordinary outcomes. */\nexport type DeliveryOutcome =\n | { kind: \"ingested\"; orderId: string; unmappedSkus: string[] }\n | { kind: \"cancelled\" }\n | { kind: \"cancellationFailed\" }\n /** Recorded; the order body is fetched by the `marketplace.fetch-order` job. */\n | { kind: \"awaitingOrder\" }\n | { kind: \"duplicate\" }\n | { kind: \"ignored\"; reason: string }\n | { kind: \"failed\"; reason: string };\n\n/**\n * Process one delivery for one tenant.\n *\n * NEVER throws. Every failure is caught, recorded on the inbox row, and\n * returned — because the caller is a webhook handler whose answer decides\n * whether the marketplace redelivers, and a 500 out of here would make an\n * ingestion bug indistinguishable from a network one while multiplying the\n * traffic that hits it.\n *\n * The delivery is recorded BEFORE it is processed. That ordering is the durable\n * part of the durable inbox: a process that dies mid-ingest leaves a PENDING\n * row the sweep will retry, whereas processing first and recording after loses\n * the event entirely on exactly the crashes worth surviving.\n */\nexport async function processDelivery(\n ctx: EngineContext,\n input: {\n clientId: string | null;\n event: NormalizedEvent;\n payload: unknown;\n settings: IngestSettings | null;\n now?: Date;\n },\n): Promise<DeliveryOutcome> {\n const { clientId, event, settings } = input;\n const record = await recordInboxEvent(ctx, { clientId, event, payload: input.payload });\n if (!record.fresh) return { kind: \"duplicate\" };\n\n if (!clientId || !settings) {\n // Stored, not dropped, and the two reasons are kept apart because only one\n // of them is a problem. An order naming a merchant no tenant claims is the\n // loudest possible symptom of a half-finished onboarding, and it is only\n // findable later because the row survived. An order for a store that has\n // simply switched the channel off is not a fault at all — it stays PENDING\n // for the retry sweep to pick up if the store switches it back on.\n const reason = clientId ? \"integration is not enabled\" : \"no tenant claims this merchant\";\n if (clientId) await deferInboxEvent(ctx, record.id, reason);\n else await settleInboxEvent(ctx, record.id, \"IGNORED\", reason);\n return { kind: \"ignored\", reason };\n }\n\n try {\n return await applyEvent(ctx, record.id, clientId, event, settings, input.now);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n await settleInboxEvent(ctx, record.id, \"FAILED\", reason);\n return { kind: \"failed\", reason };\n }\n}\n\n/** The event names an order whose body the marketplace serves apart (`orderToFetch`). */\nfunction announcesOrderToFetch(event: NormalizedEvent): boolean {\n return event.order === null && event.orderToFetch === true && event.externalOrderId !== null;\n}\n\n/**\n * Why an order the event CARRIES must not be ingested for this store: it names\n * another merchant than the connection's (a wrong webhook URL, a replay), the\n * rule a fetched order is held to. Read only for an order that names its\n * merchant (an adapter that sets `externalMerchantId` on the order); an order\n * that names none costs no read.\n */\nasync function carriedOrderMismatch(\n ctx: EngineContext,\n clientId: string,\n order: NormalizedMarketplaceOrder,\n): Promise<string | null> {\n if (!order.externalMerchantId) return null;\n // The one column, never the whole target: no credentials opened per order.\n return merchantMismatch(order, await connectionMerchantId(ctx, clientId, order.provider));\n}\n\n/**\n * Act on one recorded delivery: cancel, ingest, or deliberately nothing.\n *\n * Extracted so both producers share the ACTION as well as the recording — the\n * webhook and the retry sweep differ only in how they arrived here and in what\n * they do with a throw, never in what an event MEANS.\n */\nasync function applyEvent(\n ctx: EngineContext,\n inboxId: string,\n clientId: string,\n event: NormalizedEvent,\n settings: IngestSettings,\n now: Date | undefined,\n): Promise<DeliveryOutcome> {\n const outcome = event.cancellationOutcome ?? (event.cancelled ? \"CONFIRMED\" : null);\n if (outcome === \"FAILED\" && event.externalOrderId) {\n // The marketplace refused the store's own cancellation request. Understood\n // and recorded, never IGNORED: it is what tells a person to finish the\n // cancellation on the marketplace's side.\n await failCancellationRequest(ctx, {\n clientId,\n provider: event.provider,\n externalOrderId: event.externalOrderId,\n });\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n return { kind: \"cancellationFailed\" };\n }\n\n if (event.cancelled && event.externalOrderId) {\n const order = { clientId, provider: event.provider, externalOrderId: event.externalOrderId };\n // A cancellation that outran a fetched order's body leaves its marker, so\n // the fetch that follows ingests nothing.\n if (!(await cancelAcceptance(ctx, { ...order, now }))) await markCancelledBeforeIngest(ctx, order);\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n return { kind: \"cancelled\" };\n }\n\n if (announcesOrderToFetch(event)) {\n // The event announces an order whose body the marketplace serves apart.\n // Fetching is a call to the marketplace, so it is a job's, never this\n // request's: the row waits PENDING and the fetch is queued.\n await awaitOrderBody(ctx, clientId, inboxId);\n return { kind: \"awaitingOrder\" };\n }\n\n if (!event.order) {\n // An event type this ingestion does not act on. Marketplaces emit a wide\n // stream (dispatched, concluded, driver assigned…) and most of it is not an\n // order; IGNORED says \"understood, nothing to do\" and keeps it out of the\n // retry sweep, which FAILED would not.\n const reason = `no order body on ${event.eventType}`;\n await settleInboxEvent(ctx, inboxId, \"IGNORED\", reason);\n return { kind: \"ignored\", reason };\n }\n\n return ingestCarried(ctx, inboxId, clientId, event.order, settings, now);\n}\n\n/** Ingest the order an event carries, unless it names another merchant than the connection's. */\nasync function ingestCarried(\n ctx: EngineContext,\n inboxId: string,\n clientId: string,\n order: NormalizedMarketplaceOrder,\n settings: IngestSettings,\n now: Date | undefined,\n): Promise<DeliveryOutcome> {\n const mismatch = await carriedOrderMismatch(ctx, clientId, order);\n if (mismatch) {\n // FAILED, so the reconciliation sweep retries it once the connection's\n // merchant id is corrected, within the inbox's attempt bound.\n await settleInboxEvent(ctx, inboxId, \"FAILED\", mismatch);\n ctx.ports.logger.error(`marketplace.ingest: inbox row ${inboxId} refused: ${mismatch}`);\n return { kind: \"failed\", reason: mismatch };\n }\n const result = await ingestMarketplaceOrder(ctx, { clientId, order, settings, now });\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n return { kind: \"ingested\", orderId: result.orderId, unmappedSkus: result.unmappedSkus };\n}\n\n/**\n * Re-run a delivery already sitting in the inbox.\n *\n * Used by the retry sweep. It re-reads the store's CURRENT settings rather than\n * whatever they were when the event first arrived — a store that connected the\n * channel properly an hour after the first order came in should have that order\n * ingested on the retry, which is the case this exists for.\n */\nexport async function reprocessStoredDelivery(\n ctx: EngineContext,\n input: { id: string; clientId: string; provider: MarketplaceProvider; payload: unknown; receivedAt?: Date | null },\n): Promise<DeliveryOutcome> {\n const event = normalizeEvent(ctx, input.provider, input.payload);\n if (!event) {\n const reason = \"payload no longer normalizes\";\n await settleInboxEvent(ctx, input.id, \"IGNORED\", reason);\n return { kind: \"ignored\", reason };\n }\n const target = await resolveIngestionTarget(ctx, input.clientId, input.provider);\n if (!target?.enabled) {\n // Still not ready. Deferred rather than settled, for the same reason as on\n // arrival — and the attempt counter is what eventually retires it, so a\n // store that never switches the channel on does not have its inbox re-read\n // forever.\n const reason = \"integration is not enabled\";\n await deferInboxEvent(ctx, input.id, reason);\n return { kind: \"ignored\", reason };\n }\n // A row waiting for its order body is the fetch job's: re-queued, never fetched here.\n if (announcesOrderToFetch(event)) return requeueOwedFetch(ctx, input);\n try {\n return await applyEvent(\n ctx,\n input.id,\n input.clientId,\n event,\n { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds },\n undefined,\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n await settleInboxEvent(ctx, input.id, \"FAILED\", reason);\n return { kind: \"failed\", reason };\n }\n}\n","import type { AcceptanceStatus, CancellationStatus } from \"./acceptance\";\nimport type { CancellationFailureReason, EngineContext } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * What the host's order reads need to draw a marketplace order: where its\n * aceite and its cancellation request stand, and where a person goes when the\n * API could not do it. One read for a batch, so a list stays one statement.\n */\nexport interface MarketplaceOrderState {\n orderId: string;\n provider: MarketplaceProvider;\n externalOrderId: string;\n externalDisplayId: string | null;\n status: AcceptanceStatus;\n confirmedAt: Date | null;\n confirmFailedAt: Date | null;\n cancellation: CancellationStatus | null;\n cancellationReasonCode: string | null;\n /** Why the request FAILED (REFUSED or TIMEOUT); null unless `cancellation` is FAILED, and on rows from before it. */\n cancellationFailure: CancellationFailureReason | null;\n /** The adapter's app link, or null when no adapter is registered for it. */\n appUrl: string | null;\n}\n\ninterface StateRow {\n orderId: string;\n provider: string;\n externalOrderId: string;\n externalDisplayId: string | null;\n status: string;\n confirmedAt: Date | null;\n confirmFailedAt: Date | null;\n cancellationStatus: string | null;\n cancellationReasonCode: string | null;\n cancellationFailureReason: string | null;\n}\n\n/** The state of each of these orders that is a marketplace order, keyed by id. */\nexport async function readOrderStates(\n ctx: EngineContext,\n clientId: string,\n orderIds: readonly string[],\n): Promise<Map<string, MarketplaceOrderState>> {\n if (orderIds.length === 0) return new Map();\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceAcceptance.findMany({\n where: { clientId, orderId: { in: [...orderIds] } },\n select: {\n orderId: true,\n provider: true,\n externalOrderId: true,\n externalDisplayId: true,\n status: true,\n confirmedAt: true,\n confirmFailedAt: true,\n cancellationStatus: true,\n cancellationReasonCode: true,\n cancellationFailureReason: true,\n },\n })) as StateRow[];\n return new Map(\n rows.map((row) => {\n const adapter = ctx.registry.get(row.provider);\n const state: MarketplaceOrderState = {\n orderId: row.orderId,\n provider: row.provider,\n externalOrderId: row.externalOrderId,\n externalDisplayId: row.externalDisplayId,\n status: row.status as AcceptanceStatus,\n confirmedAt: row.confirmedAt,\n confirmFailedAt: row.confirmFailedAt,\n cancellation: row.cancellationStatus as CancellationStatus | null,\n cancellationReasonCode: row.cancellationReasonCode,\n cancellationFailure: row.cancellationFailureReason as CancellationFailureReason | null,\n appUrl: adapter ? adapter.appLink(row) : null,\n };\n return [row.orderId, state];\n }),\n );\n}\n","import {\n cancelAcceptance,\n expireLapsedAcceptances,\n listPendingAcceptances,\n type ExpirySweepResult,\n type PendingAcceptance,\n} from \"./acceptance\";\nimport {\n upsertIntegrations,\n upsertMenuLinks,\n type BulkResult,\n type IntegrationRowInput,\n type MenuLinkRowInput,\n} from \"./bulk\";\nimport {\n decideMany,\n decideOne,\n recordStoreCancellation,\n type DecideManyResult,\n type DecisionInput,\n type DecisionResult,\n} from \"./decisions\";\nimport {\n runFetchOrder,\n type FetchOrderJobPayload,\n type FetchOrderOutcome,\n} from \"./fetch-order\";\nimport { sweepOutbound, type OutboundSweepResult } from \"./outbound-sweep\";\nimport type {\n AdapterTokenCache,\n CancellationReason,\n MarketplaceAdapter,\n OutboundOrderRef,\n} from \"./adapter\";\nimport { listRetryableInboxEvents, type PendingInboxEvent } from \"./inbox\";\nimport { ingestMarketplaceOrder, type IngestResult, type IngestSettings } from \"./ingest\";\nimport {\n listMarketplaceIntegrations,\n resolveIngestionTarget,\n resolveTenantByMerchant,\n saveMarketplaceIntegration,\n type IngestionTarget,\n type MarketplaceIntegrationView,\n type SaveMarketplaceIntegrationInput,\n} from \"./integration\";\nimport { listMarketplaceMenuLinks, type MarketplaceMenuLinkView } from \"./menu-links\";\nimport { runOutbound, type OutboundAttempt, type OutboundOutcome } from \"./outbound\";\nimport type { OutboundJobPayload } from \"./outbound-queue\";\nimport {\n normalizeEvent,\n processDelivery,\n reprocessStoredDelivery,\n type DeliveryOutcome,\n} from \"./pipeline\";\nimport type { EngineContext, MarketplaceEngineConfig } from \"./ports\";\nimport { createAdapterRegistry, suggestReason } from \"./registry\";\nimport { readOrderStates, type MarketplaceOrderState } from \"./state\";\nimport type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from \"./types\";\n\n/** Everything the mounted engine can do, with the ports and adapters bound in. */\nexport interface MarketplaceEngine {\n /** Every registered marketplace, in registration order. */\n providers(): readonly MarketplaceProvider[];\n /** Whether a provider id (a URL segment, a body field) names a registered adapter. */\n knows(provider: string): provider is MarketplaceProvider;\n /** The adapter itself: its capabilities, reasons and app link. Null when unknown. */\n adapter(provider: string): MarketplaceAdapter | null;\n /** The marketplace's reasons, static and offline. Empty when unknown. */\n reasons(provider: string): readonly CancellationReason[];\n /** The reason a host preselects, given whether the order is short of an item. */\n suggestReason(provider: string, input: { itemUnavailable: boolean }): CancellationReason | null;\n /** Where a person goes to act on the marketplace's side. Null when unknown. */\n appLink(provider: string, order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string | null;\n\n /** Turn a raw payload into the canonical shape, or null if nothing does. */\n normalize(provider: string, payload: unknown): NormalizedEvent | null;\n /** Read the provider's signature header off a request. */\n readSignature(provider: string, header: (name: string) => string | null): string | null;\n /** Verify a delivery. An unknown provider is never verified, so never accepted. */\n verifySignature(provider: string, rawBody: string, signature: string | null, secret: string | null): boolean;\n /** Which tenant a delivery belongs to, from the merchant id it names. */\n tenantFor(provider: MarketplaceProvider, externalMerchantId: string): Promise<string | null>;\n /** The connection behind one (tenant, marketplace), for the ingestion path. */\n target(clientId: string, provider: MarketplaceProvider): Promise<IngestionTarget | null>;\n /** Ingest ONE already-normalized order, bypassing the inbox. Idempotent. */\n ingest(input: {\n clientId: string;\n order: NormalizedMarketplaceOrder;\n settings: IngestSettings;\n now?: Date;\n }): Promise<IngestResult>;\n /** Record and act on one delivery. Never throws. */\n deliver(input: {\n clientId: string | null;\n event: NormalizedEvent;\n payload: unknown;\n settings: IngestSettings | null;\n now?: Date;\n }): Promise<DeliveryOutcome>;\n\n /** This store's connections, secrets withheld; archived ones only when asked. */\n integrations(\n clientId: string,\n options?: { providers?: readonly string[]; includeArchived?: boolean },\n ): Promise<MarketplaceIntegrationView[]>;\n /** Create or patch ONE connection (the bulk call's single-row form, with no audit). */\n saveIntegration(input: SaveMarketplaceIntegrationInput): Promise<MarketplaceIntegrationView>;\n /** Create, patch, archive or unarchive many connections, all-or-nothing. */\n upsertIntegrations(input: {\n clientId: string;\n actorId: string | null;\n rows: readonly IntegrationRowInput[];\n validateOnly?: boolean;\n }): Promise<BulkResult<MarketplaceIntegrationView>>;\n\n /** The SKU map. `unmappedOnly` is the store's attention list; `ids` narrows. */\n menuLinks(input: {\n clientId: string;\n provider?: MarketplaceProvider;\n unmappedOnly?: boolean;\n ids?: readonly string[];\n }): Promise<MarketplaceMenuLinkView[]>;\n /** Map or unmap many SKUs, all-or-nothing. */\n upsertMenuLinks(input: {\n clientId: string;\n rows: readonly MenuLinkRowInput[];\n validateOnly?: boolean;\n }): Promise<BulkResult<MarketplaceMenuLinkView>>;\n /** Map or unmap ONE SKU. `null` = the catalog id is not this tenant's. */\n setMenuLink(input: { clientId: string } & MenuLinkRowInput): Promise<MarketplaceMenuLinkView | null>;\n\n /** Orders still on the clock, soonest deadline first; `orderIds` narrows. */\n pending(clientId: string, orderIds?: readonly string[]): Promise<PendingAcceptance[]>;\n /** Decide many orders, all-or-nothing, the host admitting each inside the claim's transaction. */\n decideMany(input: {\n clientId: string;\n decisions: readonly DecisionInput[];\n validateOnly?: boolean;\n now?: Date;\n }): Promise<DecideManyResult>;\n /** Decide ONE order (`decideMany` with one decision). */\n decide(input: { clientId: string; now?: Date } & DecisionInput): Promise<DecisionResult>;\n /** The store cancelled through the host's own cancel: stamp and queue the request. */\n recordStoreCancellation(input: {\n clientId: string;\n orderId: string;\n reasonCode?: string | null;\n offendingSkus?: readonly string[];\n now?: Date;\n }): Promise<DecisionResult>;\n /** The marketplace cancelled an order we already have. */\n cancel(input: {\n clientId: string;\n provider: MarketplaceProvider;\n externalOrderId: string;\n now?: Date;\n }): Promise<boolean>;\n /** Where each of these orders' acceptance and cancellation stand. */\n orderStates(clientId: string, orderIds: readonly string[]): Promise<Map<string, MarketplaceOrderState>>;\n\n /** Expire every order whose deadline has passed, across all tenants. */\n expireLapsed(now?: Date): Promise<ExpirySweepResult>;\n /** Deliveries recorded but never processed, oldest first. */\n retryable(): Promise<PendingInboxEvent[]>;\n /** Re-run one stored delivery against the store's CURRENT settings. */\n reprocess(event: PendingInboxEvent): Promise<DeliveryOutcome>;\n /** Re-queue every outbound call still owed (the `marketplace.outbound-sweep` job's body). */\n sweepOutbound(now?: Date): Promise<OutboundSweepResult>;\n /** Run one queued outbound call (the `marketplace.outbound` job's body). */\n runOutbound(payload: OutboundJobPayload, attempt: OutboundAttempt): Promise<OutboundOutcome>;\n /** Fetch and ingest one announced order (the `marketplace.fetch-order` job's body). */\n runFetchOrder(payload: FetchOrderJobPayload, attempt: OutboundAttempt): Promise<FetchOrderOutcome>;\n}\n\n/**\n * Mount the engine onto a host.\n *\n * Every port is REQUIRED and there are no defaults: a default would let a\n * second host silently inherit the first one's answers. The adapter list is\n * validated here (`createAdapterRegistry`), so a malformed adapter fails at\n * boot rather than on the first order it would have mangled.\n */\nexport function createMarketplaceEngine(config: MarketplaceEngineConfig): MarketplaceEngine {\n const { adapters, ...ports } = config;\n const registry = createAdapterRegistry(adapters);\n const tokens: AdapterTokenCache = new Map();\n const ctx: EngineContext = { ports, registry, tokens };\n\n return {\n providers: () => registry.providers(),\n knows: (provider): provider is MarketplaceProvider => registry.has(provider),\n adapter: (provider) => registry.get(provider),\n reasons: (provider) => registry.get(provider)?.cancellationReasons() ?? [],\n suggestReason: (provider, input) => {\n const adapter = registry.get(provider);\n return adapter ? suggestReason(adapter, input) : null;\n },\n appLink: (provider, order) => registry.get(provider)?.appLink(order) ?? null,\n\n normalize: (provider, payload) => normalizeEvent(ctx, provider, payload),\n readSignature: (provider, header) => registry.get(provider)?.readSignature(header) ?? null,\n // An unknown provider cannot be verified, so it is not accepted: trusting\n // what cannot be checked is how an unsigned endpoint ships by omission.\n verifySignature: (provider, rawBody, signature, secret) =>\n registry.get(provider)?.verifySignature(rawBody, signature, secret) ?? false,\n tenantFor: (provider, externalMerchantId) =>\n resolveTenantByMerchant(ctx, provider, externalMerchantId),\n target: (clientId, provider) => resolveIngestionTarget(ctx, clientId, provider),\n ingest: (input) => ingestMarketplaceOrder(ctx, input),\n deliver: (input) => processDelivery(ctx, input),\n\n integrations: (clientId, options) => listMarketplaceIntegrations(ctx, clientId, options),\n saveIntegration: async (input) => saveMarketplaceIntegration(ctx, input, await ports.db()),\n upsertIntegrations: (input) => upsertIntegrations(ctx, input),\n\n menuLinks: (input) => listMarketplaceMenuLinks(ctx, input),\n upsertMenuLinks: (input) => upsertMenuLinks(ctx, input),\n setMenuLink: async ({ clientId, ...row }) => {\n const result = await upsertMenuLinks(ctx, { clientId, rows: [row] });\n return result.kind === \"saved\" ? (result.rows[0] ?? null) : null;\n },\n\n pending: (clientId, orderIds) => listPendingAcceptances(ctx, clientId, orderIds),\n decideMany: (input) => decideMany(ctx, input),\n decide: (input) => decideOne(ctx, input),\n recordStoreCancellation: (input) => recordStoreCancellation(ctx, input),\n cancel: (input) => cancelAcceptance(ctx, input),\n orderStates: (clientId, orderIds) => readOrderStates(ctx, clientId, orderIds),\n\n expireLapsed: (now) => expireLapsedAcceptances(ctx, now ?? ports.clock.now()),\n retryable: () => listRetryableInboxEvents(ctx),\n reprocess: (event) => reprocessStoredDelivery(ctx, event),\n sweepOutbound: (now) => sweepOutbound(ctx, now ?? ports.clock.now()),\n runOutbound: (payload, attempt) => runOutbound(ctx, payload, attempt),\n runFetchOrder: (payload, attempt) => runFetchOrder(ctx, payload, attempt),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAS,WAAc,MAAoB,OAA2B,MAAc,OAA8B;AAChH,QAAM,OAAO,oBAAI,IAAY;AAC7B,SAAO,KAAK,QAAQ,CAAC,KAAK,UAAU;AAClC,UAAM,MAAM,MAAM,GAAG;AACrB,QAAI,CAAC,KAAK,IAAI,GAAG,GAAG;AAClB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ates"]}
1
+ {"version":3,"sources":["../src/core/bulk.ts","../src/core/decisions.ts","../src/core/catalogue.ts","../src/core/pipeline.ts","../src/core/state.ts","../src/core/engine.ts"],"sourcesContent":["import {\n listMarketplaceIntegrations,\n saveMarketplaceIntegration,\n type MarketplaceIntegrationView,\n type SaveMarketplaceIntegrationInput,\n} from \"./integration\";\nimport { upsertLink, type MarketplaceMenuLinkView } from \"./menu-links\";\nimport type { EngineContext, MarketplaceAuditEntry, MarketplaceDb } from \"./ports\";\n\n/**\n * The bulk writes: one call, many rows, all-or-nothing.\n *\n * Every row is validated first (cross-row duplicates, unknown providers, a\n * catalog id that is not the store's, an archive of nothing) and every problem\n * is returned with its path; any problem writes nothing. Then ONE transaction\n * writes every row, or none. `validateOnly` validates and writes nothing.\n * Idempotent on the natural key: a connection is `(store, provider)`, a SKU\n * link `(store, provider, externalSku)`.\n */\n\n/** Why a bulk row was refused. Vocabulary, not copy. */\nexport type BulkProblemCode =\n | \"DUPLICATE\"\n | \"UNKNOWN_PROVIDER\"\n | \"NOTHING_TO_UPDATE\"\n | \"NOT_FOUND\"\n | \"CATALOG_ITEM_NOT_FOUND\";\n\nexport interface BulkProblem {\n path: (string | number)[];\n code: BulkProblemCode;\n}\n\nexport type BulkResult<T> =\n | { kind: \"saved\"; validateOnly: boolean; rows: T[] }\n | { kind: \"refused\"; problems: BulkProblem[] };\n\n/** One connection row: an upsert of its settings, an archive, or an unarchive. */\nexport type IntegrationRowInput =\n | ({ operation?: \"upsert\" } & Omit<SaveMarketplaceIntegrationInput, \"clientId\">)\n | { operation: \"archive\" | \"unarchive\"; provider: string; reason?: string | null };\n\n/** One SKU link: map it to a catalog id, or unmap it with `menuItemId: null`. */\nexport interface MenuLinkRowInput {\n provider: string;\n externalSku: string;\n externalName?: string;\n menuItemId: string | null;\n}\n\n/** The key of each row seen twice, as problems. */\nfunction duplicates<T>(rows: readonly T[], keyOf: (row: T) => string, list: string, field: string): BulkProblem[] {\n const seen = new Set<string>();\n return rows.flatMap((row, index) => {\n const key = keyOf(row);\n if (!seen.has(key)) {\n seen.add(key);\n return [];\n }\n return [{ path: [list, index, field], code: \"DUPLICATE\" as const }];\n });\n}\n\nfunction unknownProviders(ctx: EngineContext, rows: readonly { provider: string }[], list: string): BulkProblem[] {\n return rows.flatMap((row, index) =>\n ctx.registry.has(row.provider) ? [] : [{ path: [list, index, \"provider\"], code: \"UNKNOWN_PROVIDER\" as const }],\n );\n}\n\nconst SETTING_KEYS = [\"enabled\", \"environment\", \"externalMerchantId\", \"autoAccept\", \"ackSlaSeconds\", \"credentials\"] as const;\n\nfunction integrationRowProblems(\n row: IntegrationRowInput,\n index: number,\n existing: ReadonlySet<string>,\n): BulkProblem[] {\n if (row.operation === \"archive\" || row.operation === \"unarchive\") {\n return existing.has(row.provider) ? [] : [{ path: [\"integrations\", index, \"provider\"], code: \"NOT_FOUND\" }];\n }\n const settings = row as Partial<Record<(typeof SETTING_KEYS)[number], unknown>>;\n const changes = SETTING_KEYS.some((key) => settings[key] !== undefined);\n return changes ? [] : [{ path: [\"integrations\", index], code: \"NOTHING_TO_UPDATE\" }];\n}\n\n/** Thrown inside the transaction to roll a `validateOnly` call back. */\nclass ValidateOnly extends Error {\n constructor() {\n super(\"validate only\");\n }\n}\n\n/** Run `write` in one transaction; a `validateOnly` call is rolled back. */\nasync function inTransaction<T>(ctx: EngineContext, validateOnly: boolean, write: (db: MarketplaceDb) => Promise<T>): Promise<T | null> {\n let written: T | null = null;\n try {\n await ctx.ports.transaction(async (db) => {\n written = await write(db);\n if (validateOnly) throw new ValidateOnly();\n });\n } catch (error) {\n if (!(error instanceof ValidateOnly)) throw error;\n }\n return written;\n}\n\nasync function writeIntegration(\n ctx: EngineContext,\n db: MarketplaceDb,\n clientId: string,\n row: IntegrationRowInput,\n now: Date,\n): Promise<MarketplaceIntegrationView | null> {\n if (row.operation === \"archive\" || row.operation === \"unarchive\") {\n await db.marketplaceIntegration.updateMany({\n where: { clientId, provider: row.provider },\n data: { archivedAt: row.operation === \"archive\" ? now : null },\n });\n return null;\n }\n const settings: Omit<IntegrationRowInput, \"operation\"> & { operation?: unknown } = { ...row };\n delete settings.operation;\n return saveMarketplaceIntegration(ctx, { clientId, ...(settings as Omit<SaveMarketplaceIntegrationInput, \"clientId\">) }, db);\n}\n\n/**\n * Create, patch, archive or unarchive many connections at once. A connection\n * is never deleted: archiving is reversible, and each archive and unarchive is\n * an audit line through the host's `audit` port, in the same transaction.\n */\nexport async function upsertIntegrations(\n ctx: EngineContext,\n input: { clientId: string; actorId: string | null; rows: readonly IntegrationRowInput[]; validateOnly?: boolean },\n): Promise<BulkResult<MarketplaceIntegrationView>> {\n const existing = new Set(\n (await listMarketplaceIntegrations(ctx, input.clientId, { includeArchived: true })).map((row) => row.provider),\n );\n const problems = [\n ...duplicates(input.rows, (row) => row.provider, \"integrations\", \"provider\"),\n ...unknownProviders(ctx, input.rows, \"integrations\"),\n ...input.rows.flatMap((row, index) => integrationRowProblems(row, index, existing)),\n ];\n if (problems.length > 0) return { kind: \"refused\", problems };\n\n const validateOnly = input.validateOnly === true;\n const now = ctx.ports.clock.now();\n // The audit lines are written INSIDE the archive's transaction, through its\n // client: an archive never lands without its line, and an audit that fails\n // rolls the archive back. A `validateOnly` call rolls both back.\n await inTransaction(ctx, validateOnly, async (db) => {\n for (const row of input.rows) await writeIntegration(ctx, db, input.clientId, row, now);\n await auditArchives(ctx, db, input, now);\n });\n const providers = input.rows.map((row) => row.provider);\n const rows = validateOnly\n ? []\n : await listMarketplaceIntegrations(ctx, input.clientId, { providers, includeArchived: true });\n return { kind: \"saved\", validateOnly, rows };\n}\n\nasync function auditArchives(\n ctx: EngineContext,\n db: MarketplaceDb,\n input: { clientId: string; actorId: string | null; rows: readonly IntegrationRowInput[] },\n now: Date,\n): Promise<void> {\n for (const row of input.rows) {\n if (row.operation !== \"archive\" && row.operation !== \"unarchive\") continue;\n const entry: MarketplaceAuditEntry = {\n clientId: input.clientId,\n actorId: input.actorId,\n action: row.operation === \"archive\" ? \"marketplace.integration.archive\" : \"marketplace.integration.unarchive\",\n provider: row.provider,\n reason: row.reason ?? null,\n at: now,\n };\n await ctx.ports.audit.record(entry, db);\n }\n}\n\n/** Map or unmap many SKUs at once; every catalog id must be the store's. */\nexport async function upsertMenuLinks(\n ctx: EngineContext,\n input: { clientId: string; rows: readonly MenuLinkRowInput[]; validateOnly?: boolean },\n): Promise<BulkResult<MarketplaceMenuLinkView>> {\n const problems = [\n ...duplicates(input.rows, (row) => `${row.provider}\\u0000${row.externalSku}`, \"links\", \"externalSku\"),\n ...unknownProviders(ctx, input.rows, \"links\"),\n ];\n for (const [index, row] of input.rows.entries()) {\n if (row.menuItemId !== null && !(await ctx.ports.order.catalogHas(input.clientId, row.menuItemId))) {\n problems.push({ path: [\"links\", index, \"menuItemId\"], code: \"CATALOG_ITEM_NOT_FOUND\" });\n }\n }\n if (problems.length > 0) return { kind: \"refused\", problems };\n\n const validateOnly = input.validateOnly === true;\n const written = await inTransaction(ctx, validateOnly, async (db) => {\n const rows: MarketplaceMenuLinkView[] = [];\n for (const row of input.rows) rows.push(await upsertLink(db, { clientId: input.clientId, ...row }));\n return rows;\n });\n return { kind: \"saved\", validateOnly, rows: written ?? [] };\n}\n","import type { AcceptanceStatus, CancellationStatus } from \"./acceptance\";\nimport {\n CLAIM_SELECT,\n NO_STANDING_REQUEST,\n notPendingProblem,\n planCancellation,\n refusalData,\n requestData,\n type CancellationPlan,\n type ClaimRow,\n type DecisionProblem,\n type DecisionProblemCode,\n} from \"./cancellation\";\nimport { requestsFirst, tellCancellationFailed } from \"./cancellation-outcome\";\nimport { enqueueOutbound } from \"./outbound-queue\";\nimport type { EngineContext, MarketplaceAdmission, MarketplaceDb } from \"./ports\";\n\n/**\n * The store's decisions on orders on the clock — ONE path for every surface\n * (the host's board, the admin route, the MCP tool), and all-or-nothing:\n *\n * 1. every decision is validated against its row (still AWAITING, the reason\n * the marketplace's, the offending SKUs the order's) before anything runs;\n * 2. inside ONE transaction the host ADMITS each decision (`order.admit`: the\n * stock ask, the draw) and the engine claims each row on `AWAITING`. A\n * host refusal or a lost claim rolls the whole call back;\n * 3. after the commit, each outbound call is QUEUED FIRST, then the host's\n * half runs (`onAccepted` / `onRefused`). A host half that throws cannot\n * lose the call; it is logged, and the decision stands.\n *\n * A queue that refuses the job loses nothing either: the outbound sweep\n * (`./outbound-sweep.ts`) re-queues every request still owed.\n */\n\n/** The two things a person can do to an order on the clock. */\nexport type AcceptanceDecision = \"ACCEPT\" | \"REJECT\";\n\n/** One decision, as a caller states it. */\nexport type DecisionInput =\n | {\n orderId: string;\n decision: \"ACCEPT\";\n /** What the person confirmed, for the host's admission. */\n admission?: MarketplaceAdmission;\n /** Minutes to prepare, for a marketplace whose confirm states one. */\n preparationMinutes?: number | null;\n }\n | {\n orderId: string;\n decision: \"REJECT\";\n /** One of the marketplace's codes; its first reason when absent. */\n reasonCode?: string | null;\n /** The order's SKUs a reason that `needsItems` names. */\n offendingSkus?: readonly string[];\n };\n\n/**\n * One decided row. `status` is the row's status after the call: ACCEPTED or\n * REJECTED, or — for a refusal of a host that requests first (FUT-4758) —\n * the status it keeps (AWAITING, ACCEPTED) while `cancellation` waits.\n */\nexport interface DecidedRow {\n orderId: string;\n status: AcceptanceStatus;\n cancellation: CancellationStatus | null;\n reasonCode: string | null;\n offendingSkus: string[];\n}\n\n/** What a call did: every row decided, or nothing written and every problem named. */\nexport type DecideManyResult =\n | { kind: \"decided\"; validateOnly: boolean; rows: DecidedRow[] }\n | { kind: \"refused\"; problems: DecisionProblem[] };\n\n/** One decision's result, for a caller deciding one order. */\nexport type DecisionResult =\n | ({ kind: \"decided\" } & DecidedRow)\n | {\n kind: \"stale\";\n /** Why: gone, decided already (I4: answer it as done), expired, or lost to a race. */\n reason: Extract<DecisionProblemCode, \"NOT_FOUND\" | \"ALREADY_DECIDED\" | \"EXPIRED\" | \"CONFLICT\">;\n status: AcceptanceStatus | null;\n }\n | {\n kind: \"invalidReason\";\n problem: Extract<DecisionProblemCode, \"INVALID_REASON\" | \"ITEMS_REQUIRED\" | \"UNKNOWN_ITEM\">;\n validCodes: string[];\n }\n | { kind: \"refusedByHost\"; code: string; message: string; details?: unknown };\n\n/** A planned decision: the row, the claim's data, and what it becomes. */\ninterface PlannedDecision {\n input: DecisionInput;\n index: number;\n row: ClaimRow;\n data: Record<string, unknown>;\n decided: DecidedRow;\n /** A refusal that only REQUESTS the cancellation: the host cancels on the marketplace's confirmation. */\n requestOnly: boolean;\n}\n\n/** Thrown inside the transaction to roll it back, carrying the reason. */\nclass Rollback extends Error {\n constructor(readonly problems: DecisionProblem[] | null) {\n super(\"rollback\");\n }\n}\n\nfunction duplicateProblems(decisions: readonly DecisionInput[]): DecisionProblem[] {\n const seen = new Set<string>();\n return decisions.flatMap((decision, index) => {\n if (!seen.has(decision.orderId)) {\n seen.add(decision.orderId);\n return [];\n }\n return [{ path: [\"decisions\", index, \"orderId\"], code: \"DUPLICATE\" as const }];\n });\n}\n\nfunction decidedOf(input: DecisionInput, plan: CancellationPlan | null, keptStatus?: string): DecidedRow {\n const decided: AcceptanceStatus = input.decision === \"ACCEPT\" ? \"ACCEPTED\" : \"REJECTED\";\n return {\n orderId: input.orderId,\n status: (keptStatus as AcceptanceStatus | undefined) ?? decided,\n cancellation: plan?.status ?? null,\n reasonCode: plan?.reason?.code ?? null,\n offendingSkus: plan?.skus ?? [],\n };\n}\n\n/**\n * The columns of a request that no longer stands, cleared, but for its\n * TOMBSTONE: `cancellation_requested_at` stays, naming the request that was\n * made (FUT-4765, R3-N2).\n *\n * A synchronous marketplace answers a cancellation in the call's response,\n * never by event. When the sweep times a request out while that call is still\n * in flight and the store then accepts the order, the late answer must still\n * find the request it answers: \"cancelled\" means the marketplace cancelled the\n * order, and dropping it would leave the order ACCEPTED here and cancelled\n * there. The outbound job matches a status-less row by this instant\n * (`stampConfirmedCancellation`); nothing else reads it without a status.\n */\nconst CLEARED_REQUEST = {\n cancellationStatus: null,\n cancellationReasonCode: null,\n cancellationOffendingSkus: null,\n cancellationFailureReason: null,\n} as const;\n\n/** Plan one decision against its row, or name what is wrong with it. */\nfunction planOne(\n ctx: EngineContext,\n input: DecisionInput,\n index: number,\n row: ClaimRow | undefined,\n now: Date,\n): PlannedDecision | DecisionProblem[] {\n const path = [\"decisions\", index];\n const stale = notPendingProblem(row, path);\n if (stale || !row) return stale ? [stale] : [];\n if (input.decision === \"ACCEPT\") {\n // An accept after a FAILED request (FUT-4758) leaves no request behind it,\n // only its tombstone (see CLEARED_REQUEST).\n const data = {\n status: \"ACCEPTED\",\n acknowledgedAt: now,\n preparationMinutes: input.preparationMinutes ?? null,\n ...(row.cancellationStatus === null ? {} : CLEARED_REQUEST),\n };\n return { input, index, row, data, decided: decidedOf(input, null), requestOnly: false };\n }\n const plan = planCancellation(ctx.registry.get(row.provider), input, row, path);\n if (Array.isArray(plan)) return plan;\n if (requestOnly(ctx, plan)) {\n return { input, index, row, data: requestData(plan, now), decided: decidedOf(input, plan, row.status), requestOnly: true };\n }\n return { input, index, row, data: refusalData(plan, row.status, now), decided: decidedOf(input, plan), requestOnly: false };\n}\n\n/**\n * Whether a refusal only REQUESTS the cancellation (FUT-4758): the host\n * requests first (it binds `onCancellationConfirmed`), and there is a request\n * to make — PENDING, or FAILED at once for a marketplace that cannot take it\n * through its API (a person cancels in its app, and its event confirms). A\n * provider with no adapter has nothing to ask: refused at once, as ever.\n */\nfunction requestOnly(ctx: EngineContext, plan: CancellationPlan): boolean {\n return requestsFirst(ctx) && plan.status !== null;\n}\n\n/** Admit every decision through the host, then claim every row, in one transaction. */\nasync function admitAndClaim(\n ctx: EngineContext,\n clientId: string,\n planned: readonly PlannedDecision[],\n validateOnly: boolean,\n): Promise<void> {\n await ctx.ports.transaction(async (tx: MarketplaceDb) => {\n const refused: DecisionProblem[] = [];\n for (const one of planned) {\n const admission = one.input.decision === \"ACCEPT\" ? (one.input.admission ?? {}) : {};\n const answer = await ctx.ports.order.admit({\n clientId,\n orderId: one.input.orderId,\n decision: one.input.decision,\n admission,\n db: tx,\n });\n if (!answer.admitted) {\n const host = { code: answer.code, message: answer.message, details: answer.details };\n refused.push({ path: [\"decisions\", one.index], code: \"HOST_REFUSED\", host });\n }\n }\n if (refused.length > 0) throw new Rollback(refused);\n for (const one of planned) {\n const claimed = await tx.marketplaceAcceptance.updateMany({\n where: { orderId: one.input.orderId, clientId, status: \"AWAITING\", ...NO_STANDING_REQUEST },\n data: one.data,\n });\n if (claimed.count === 0) refused.push({ path: [\"decisions\", one.index, \"orderId\"], code: \"CONFLICT\" });\n }\n if (refused.length > 0) throw new Rollback(refused);\n if (validateOnly) throw new Rollback(null);\n });\n}\n\n/** After the commit: queue each owed call FIRST, then the host's half, which may not lose it. */\nasync function afterCommit(ctx: EngineContext, clientId: string, planned: readonly PlannedDecision[]): Promise<void> {\n for (const one of planned) {\n const { orderId } = one.input;\n if (one.input.decision === \"ACCEPT\") {\n await enqueueOutbound(ctx, { clientId, orderId, action: \"confirm\" }, one.row.provider);\n } else if (one.decided.cancellation === \"PENDING\") {\n await enqueueOutbound(ctx, { clientId, orderId, action: \"requestCancellation\" }, one.row.provider);\n }\n try {\n if (one.decided.status === \"ACCEPTED\" && one.input.decision === \"ACCEPT\") await ctx.ports.order.onAccepted(clientId, orderId);\n else if (!one.requestOnly) await ctx.ports.order.onRefused(clientId, orderId, \"REJECTED\");\n // A request the marketplace cannot take through its API failed at once:\n // the order stays, and a person cancels it in the marketplace's app.\n else if (one.decided.cancellation === \"FAILED\") await tellCancellationFailed(ctx, clientId, orderId, \"REFUSED\");\n } catch (error) {\n ctx.ports.logger.error(\n `marketplace.decide: order ${orderId} is ${one.decided.status} but the host's half failed: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n }\n ctx.ports.publishChanged(clientId);\n}\n\n/** Read every row a call names, in one statement. */\nasync function readRows(ctx: EngineContext, clientId: string, orderIds: string[]): Promise<Map<string, ClaimRow>> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceAcceptance.findMany({\n where: { clientId, orderId: { in: orderIds } },\n select: CLAIM_SELECT,\n })) as ClaimRow[];\n return new Map(rows.map((row) => [row.orderId, row]));\n}\n\n/**\n * Decide many orders at once, all-or-nothing. `validateOnly` runs everything —\n * the host's admission included — and rolls it back.\n */\nexport async function decideMany(\n ctx: EngineContext,\n input: { clientId: string; decisions: readonly DecisionInput[]; validateOnly?: boolean; now?: Date },\n): Promise<DecideManyResult> {\n const duplicates = duplicateProblems(input.decisions);\n if (duplicates.length > 0) return { kind: \"refused\", problems: duplicates };\n const now = input.now ?? ctx.ports.clock.now();\n const rows = await readRows(ctx, input.clientId, input.decisions.map((decision) => decision.orderId));\n\n const planned: PlannedDecision[] = [];\n const problems: DecisionProblem[] = [];\n input.decisions.forEach((decision, index) => {\n const plan = planOne(ctx, decision, index, rows.get(decision.orderId), now);\n if (Array.isArray(plan)) problems.push(...plan);\n else planned.push(plan);\n });\n if (problems.length > 0) return { kind: \"refused\", problems };\n\n const validateOnly = input.validateOnly === true;\n try {\n await admitAndClaim(ctx, input.clientId, planned, validateOnly);\n } catch (error) {\n if (!(error instanceof Rollback)) throw error;\n if (error.problems) return { kind: \"refused\", problems: error.problems };\n }\n if (!validateOnly) await afterCommit(ctx, input.clientId, planned);\n return { kind: \"decided\", validateOnly, rows: planned.map((one) => one.decided) };\n}\n\nconst STALE_CODES = new Set<DecisionProblemCode>([\"NOT_FOUND\", \"ALREADY_DECIDED\", \"EXPIRED\", \"CONFLICT\"]);\n\n/** One decision's problem, as the single-order result names it. */\nfunction resultOfProblem(problem: DecisionProblem): DecisionResult {\n if (problem.code === \"HOST_REFUSED\") {\n const host = problem.host ?? { code: \"\", message: \"\" };\n return { kind: \"refusedByHost\", code: host.code, message: host.message, details: host.details };\n }\n if (STALE_CODES.has(problem.code)) {\n const reason = problem.code as Extract<DecisionResult, { kind: \"stale\" }>[\"reason\"];\n return { kind: \"stale\", reason, status: problem.status ?? null };\n }\n const invalid = problem.code as Extract<DecisionResult, { kind: \"invalidReason\" }>[\"problem\"];\n return { kind: \"invalidReason\", problem: invalid, validCodes: problem.validCodes ?? [] };\n}\n\n/** Decide ONE order: `decideMany` with one decision. */\nexport async function decideOne(\n ctx: EngineContext,\n input: { clientId: string; now?: Date } & DecisionInput,\n): Promise<DecisionResult> {\n const { clientId, now, ...decision } = input;\n const result = await decideMany(ctx, { clientId, decisions: [decision as DecisionInput], now });\n if (result.kind === \"decided\") {\n const [row] = result.rows;\n if (row) return { kind: \"decided\", ...row };\n }\n const [problem] = result.kind === \"refused\" ? result.problems : [];\n return problem ? resultOfProblem(problem) : { kind: \"stale\", reason: \"CONFLICT\", status: null };\n}\n\n/**\n * The STORE asks to cancel an order — before or after accepting it. Stamps\n * the request the marketplace must hear and queues it; the engine neither\n * admits nor calls `onRefused`: it records and queues, and nothing else.\n *\n * REQUEST FIRST (FUT-4758), for a host that binds `onCancellationConfirmed`:\n * only the request moves. The decision status stays AWAITING or ACCEPTED while\n * the marketplace answers, so the host keeps the order as it was until then,\n * and a refused or timed-out request (`onCancellationFailed`) leaves it\n * acceptable. The marketplace's confirmation moves it to REJECTED. A FAILED\n * request may be asked again. A host that binds no `onCancellationConfirmed`\n * cancelled first and gets 1.0.0's stamps exactly: REJECTED at once.\n *\n * The returned row's `status` is the row's after the call.\n *\n * `stale` (ALREADY_DECIDED) when the marketplace already cancelled it, the\n * clock lapsed (EXPIRED), or a request is already waiting.\n */\nexport async function recordStoreCancellation(\n ctx: EngineContext,\n input: { clientId: string; orderId: string; reasonCode?: string | null; offendingSkus?: readonly string[]; now?: Date },\n): Promise<DecisionResult> {\n const row = (await readRows(ctx, input.clientId, [input.orderId])).get(input.orderId);\n const stale = notPendingProblem(row, [], [\"AWAITING\", \"ACCEPTED\"]);\n if (stale || !row) return stale ? resultOfProblem(stale) : { kind: \"stale\", reason: \"NOT_FOUND\", status: null };\n const plan = planCancellation(ctx.registry.get(row.provider), input, row, []);\n if (Array.isArray(plan)) return resultOfProblem(plan[0]!);\n\n return claimStoreCancellation(ctx, input, row, plan);\n}\n\n/** Stamp the store's cancellation (the request alone, or 1.0.0's REJECTED), queue it, and tell the host. */\nasync function claimStoreCancellation(\n ctx: EngineContext,\n input: { clientId: string; orderId: string; now?: Date },\n row: ClaimRow,\n plan: CancellationPlan,\n): Promise<DecisionResult> {\n const now = input.now ?? ctx.ports.clock.now();\n const db = await ctx.ports.db();\n const only = requestOnly(ctx, plan);\n const claimed = await db.marketplaceAcceptance.updateMany({\n where: { orderId: input.orderId, clientId: input.clientId, status: row.status, ...NO_STANDING_REQUEST },\n data: only ? requestData(plan, now) : refusalData(plan, row.status, now),\n });\n if (claimed.count === 0) return { kind: \"stale\", reason: \"CONFLICT\", status: null };\n if (plan.status === \"PENDING\") {\n await enqueueOutbound(ctx, { clientId: input.clientId, orderId: input.orderId, action: \"requestCancellation\" }, row.provider);\n }\n ctx.ports.publishChanged(input.clientId);\n if (only && plan.status === \"FAILED\") await tellCancellationFailed(ctx, input.clientId, input.orderId, \"REFUSED\");\n return { kind: \"decided\", ...decidedOf({ orderId: input.orderId, decision: \"REJECT\" }, plan, only ? row.status : undefined) };\n}\n","import { catalogueDedupeKey, enqueueCatalogue, type CatalogueJobPayload } from \"./catalogue-job\";\nimport type { CatalogueMenuEntry, CatalogueMenuOptions } from \"./catalogue-port\";\nimport {\n CATALOGUE_ROW_SELECT,\n NO_FAILURE,\n catalogueConnection,\n catalogueTable,\n viewOf,\n type CataloguePublicationView,\n type CatalogueRow,\n type CatalogueTable,\n} from \"./catalogue-store\";\nimport { connectionMerchantId } from \"./integration\";\nimport type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * Catalogue publishing, as a host calls it (FUT-4768): from a product's page,\n * the store turns the product ON (`publish`) or OFF (`withdraw`) per connected\n * marketplace, with an optional price for that marketplace, and reads where\n * each stands (`catalogueState`, one read for a whole page).\n *\n * Nothing here calls a marketplace: a publish or withdraw stamps the row and\n * queues `marketplace.catalogue`, whose job makes the call. The host's product\n * is read through its `catalogue` port, never from a host table, and only the\n * job reads it for sending, so what goes out is the product as it is then.\n */\n\n/** Why a catalogue call was refused before anything was stamped. Vocabulary, not copy. */\nexport type CatalogueRefusalCode =\n /** The marketplace has no catalogue capability, or the host bound no catalogue port or table. */\n | \"UNSUPPORTED\"\n /** No live connection with credentials and a merchant id. */\n | \"NOT_CONNECTED\"\n /** The host's catalogue does not have this product. */\n | \"UNKNOWN_PRODUCT\"\n /** The price for the marketplace is not a positive integer of the smallest unit. */\n | \"INVALID_PRICE\";\n\n/** What `publish` and `withdraw` answer. */\nexport type CatalogueActionResult =\n /** Stamped and queued (or already on its way: a double tap is this, with nothing new queued). */\n | { kind: \"queued\"; publication: CataloguePublicationView }\n /** Nothing to do: the product is not in that marketplace's catalogue, or was never there. */\n | { kind: \"unchanged\"; publication: CataloguePublicationView | null }\n | { kind: \"refused\"; code: CatalogueRefusalCode };\n\n/** What a pull marketplace's menu document read answers. */\nexport type CatalogueDocumentResult =\n | { kind: \"document\"; document: unknown }\n | { kind: \"refused\"; code: Exclude<CatalogueRefusalCode, \"UNKNOWN_PRODUCT\" | \"INVALID_PRICE\"> };\n\n/** One product on one marketplace. */\nexport interface CatalogueTarget {\n clientId: string;\n provider: MarketplaceProvider;\n productId: string;\n}\n\n/** A publish: the target, and the price for this marketplace — absent keeps the stored one, null is the store's. */\nexport interface CataloguePublishInput extends CatalogueTarget {\n priceCents?: number | null;\n}\n\nconst refused = (code: CatalogueRefusalCode): CatalogueActionResult => ({ kind: \"refused\", code });\n\n/** The table, or why the catalogue cannot be used at all for this marketplace. */\nasync function usableTable(ctx: EngineContext, provider: string): Promise<CatalogueTable | null> {\n if (!ctx.ports.catalogue || !ctx.registry.get(provider)?.catalogue) return null;\n return catalogueTable(ctx);\n}\n\nasync function findRow(table: CatalogueTable, target: CatalogueTarget): Promise<CatalogueRow | null> {\n return (await table.findFirst({\n where: { clientId: target.clientId, provider: target.provider, productId: target.productId },\n select: CATALOGUE_ROW_SELECT,\n })) as CatalogueRow | null;\n}\n\nasync function queue(ctx: EngineContext, row: CatalogueRow, action: CatalogueJobPayload[\"action\"]): Promise<CatalogueActionResult> {\n const payload: CatalogueJobPayload = { clientId: row.clientId, publicationId: row.id, action };\n await enqueueCatalogue(ctx, payload, catalogueDedupeKey(payload, row.requestedAt));\n ctx.ports.publishChanged(row.clientId);\n return { kind: \"queued\", publication: viewOf(row) };\n}\n\nconst validPrice = (price: number | null | undefined): boolean =>\n price === undefined || price === null || (Number.isInteger(price) && price > 0);\n\n/** Why a publish cannot be asked, or null. */\nasync function publishRefusal(ctx: EngineContext, input: CataloguePublishInput): Promise<CatalogueRefusalCode | null> {\n if (!validPrice(input.priceCents)) return \"INVALID_PRICE\";\n if (\"problem\" in (await catalogueConnection(ctx, input.clientId, input.provider))) return \"NOT_CONNECTED\";\n const items = await ctx.ports.catalogue?.items(input.clientId, [input.productId]);\n return items?.has(input.productId) ? null : \"UNKNOWN_PRODUCT\";\n}\n\n/**\n * Put the product in the marketplace's catalogue, or send it again (a new\n * price, a retry after FAILED). A double tap while it is on its way keeps the\n * same ask and queues nothing new.\n */\nexport async function publishToCatalogue(ctx: EngineContext, input: CataloguePublishInput): Promise<CatalogueActionResult> {\n const table = await usableTable(ctx, input.provider);\n if (!table) return refused(\"UNSUPPORTED\");\n const refusal = await publishRefusal(ctx, input);\n if (refusal) return refused(refusal);\n const existing = await findRow(table, input);\n const now = ctx.ports.clock.now();\n const price = input.priceCents === undefined ? {} : { priceCents: input.priceCents };\n // A double tap keeps the ask on its way; a NEW price is a new ask, so the\n // run already queued (which reads the row's price at its own instant) misses\n // its stamp and the new run sends the new price.\n const samePrice = input.priceCents === undefined || input.priceCents === existing?.priceCents;\n const asked = existing?.status === \"PUBLISHING\" && samePrice ? {} : { requestedAt: now };\n const row = (await table.upsert({\n where: { clientId_provider_productId: { clientId: input.clientId, provider: input.provider, productId: input.productId } },\n create: { clientId: input.clientId, provider: input.provider, productId: input.productId, status: \"PUBLISHING\", requestedAt: now, ...price },\n update: { status: \"PUBLISHING\", ...NO_FAILURE, ...asked, ...price },\n select: CATALOGUE_ROW_SELECT,\n })) as CatalogueRow;\n return queue(ctx, row, \"publish\");\n}\n\n/**\n * Take the product out of the marketplace's catalogue. A product never\n * switched on (no row, or WITHDRAWN) is `unchanged`; a double tap while it is\n * on its way out queues nothing new; a withdraw while a publish is on its way\n * wins (the job re-withdraws a publish that lands after it).\n *\n * A withdraw is SENT even after a publish that FAILED: a call whose answer was\n * lost may have put the item there, and a marketplace answers a withdraw of\n * an item it does not have as done. Only a store with no live connection any\n * more (archived, removed) ends WITHDRAWN at once: there is nobody to tell.\n */\nexport async function withdrawFromCatalogue(ctx: EngineContext, target: CatalogueTarget): Promise<CatalogueActionResult> {\n const table = await usableTable(ctx, target.provider);\n if (!table) return refused(\"UNSUPPORTED\");\n const existing = await findRow(table, target);\n if (!existing || existing.status === \"WITHDRAWN\") return { kind: \"unchanged\", publication: existing && viewOf(existing) };\n if (existing.status === \"WITHDRAWING\") return queue(ctx, existing, \"withdraw\");\n const now = ctx.ports.clock.now();\n // No live connection (archived, removed): nothing to tell, so it is out here and now.\n const local = (await connectionMerchantId(ctx, target.clientId, target.provider)) === null;\n const data = local\n ? { status: \"WITHDRAWN\", withdrawnAt: now, requestedAt: now, ...NO_FAILURE }\n : { status: \"WITHDRAWING\", requestedAt: now, ...NO_FAILURE };\n const moved = await table.updateMany({ where: { id: existing.id, status: existing.status }, data });\n // Lost a race with another write: answer what the row now says.\n const row = (await findRow(table, target)) ?? existing;\n if (moved.count === 0 || local) {\n ctx.ports.publishChanged(target.clientId);\n return { kind: \"unchanged\", publication: viewOf(row) };\n }\n return queue(ctx, row, \"withdraw\");\n}\n\n/**\n * Where these products stand on these marketplaces, in ONE read: a product's\n * page asks for one product on every connected marketplace; a list asks for\n * many. Rows only for what was ever switched on.\n */\nexport async function readCatalogueState(\n ctx: EngineContext,\n input: { clientId: string; productIds: readonly string[]; providers?: readonly string[] },\n): Promise<CataloguePublicationView[]> {\n const table = await catalogueTable(ctx);\n if (!table || input.productIds.length === 0) return [];\n const rows = (await table.findMany({\n where: {\n clientId: input.clientId,\n productId: { in: [...input.productIds] },\n ...(input.providers ? { provider: { in: [...input.providers] } } : {}),\n },\n select: CATALOGUE_ROW_SELECT,\n })) as CatalogueRow[];\n return rows.map(viewOf);\n}\n\n/**\n * Every product a pull marketplace's menu lists: switched on, on its way, or\n * already published once and since FAILED to be published again (it stays,\n * at the price last sent, until it is withdrawn).\n */\nconst IN_MENU = [\"PUBLISHING\", \"PUBLISHED\", \"FAILED\"];\n\n/** Whether a row belongs in the served menu, and at which price. */\nfunction menuPrice(row: CatalogueRow, storePrice: number): number | null {\n if (row.status !== \"FAILED\") return row.priceCents ?? storePrice;\n // Published, and not withdrawn since: a withdraw → re-publish that FAILED is\n // not on the marketplace's menu, so it is not listed at an old price.\n const live = row.publishedAt !== null && (row.withdrawnAt === null || row.withdrawnAt < row.publishedAt);\n const republishFailed = row.failedAction === \"PUBLISH\" && live;\n return republishFailed ? (row.sentPriceCents ?? row.priceCents ?? storePrice) : null;\n}\n\n/**\n * The menu part of the document a pull marketplace reads, for the host to\n * serve (merged into the rest of that document, which is the host's). Built\n * from every product switched on for the connection, read through the host's\n * catalogue port; a product that no longer exists is left out.\n */\nexport async function readCatalogueDocument(\n ctx: EngineContext,\n input: { clientId: string; provider: MarketplaceProvider; options: CatalogueMenuOptions },\n): Promise<CatalogueDocumentResult> {\n const catalogue = ctx.registry.get(input.provider)?.catalogue;\n const table = await usableTable(ctx, input.provider);\n if (!table || catalogue?.mode !== \"pull\") return { kind: \"refused\", code: \"UNSUPPORTED\" };\n const connection = await catalogueConnection(ctx, input.clientId, input.provider);\n if (\"problem\" in connection) return { kind: \"refused\", code: \"NOT_CONNECTED\" };\n const rows = (await table.findMany({\n where: { clientId: input.clientId, provider: input.provider, status: { in: IN_MENU } },\n select: CATALOGUE_ROW_SELECT,\n orderBy: { createdAt: \"asc\" },\n })) as CatalogueRow[];\n const items = (await ctx.ports.catalogue?.items(input.clientId, rows.map((row) => row.productId))) ?? new Map();\n const entries: CatalogueMenuEntry[] = rows.flatMap((row) => {\n const item = items.get(row.productId);\n const priceCents = item ? menuPrice(row, item.priceCents) : null;\n if (!item || priceCents === null) return [];\n return [{ ...item, priceCents, ref: row.id, productId: row.productId, externalId: row.externalId, storedImage: null }];\n });\n const document = catalogue.menuDocument({ externalMerchantId: connection.externalMerchantId, entries, options: input.options });\n return { kind: \"document\", document };\n}\n","import { cancelAcceptance } from \"./acceptance\";\nimport { failCancellationRequest } from \"./cancellation\";\nimport { awaitOrderBody, merchantMismatch, requeueOwedFetch } from \"./fetch-order\";\nimport { deferInboxEvent, recordInboxEvent, settleInboxEvent } from \"./inbox\";\nimport { ingestMarketplaceOrder, type IngestSettings } from \"./ingest\";\nimport { connectionMerchantId, resolveIngestionTarget } from \"./integration\";\nimport { markCancelledBeforeIngest } from \"./order-fetch-marks\";\nimport type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from \"./types\";\n\n/**\n * One delivery, start to finish: normalize → inbox → ingest.\n *\n * The ONE path both producers use. The webhook calls it, and so does the\n * reconciliation retry sweep — which is the whole reason it is a module rather\n * than the body of a route handler. Two producers with two copies of this\n * sequence is how a webhook and a poll come to disagree about what an order is,\n * and the disagreement only shows up on the orders that took the unlucky path.\n */\n\n/**\n * Normalize a raw payload through the provider's adapter, or null when no\n * adapter is registered for it or the adapter refuses the payload. The\n * registry is the only dispatch: there is no provider branch here.\n */\nexport function normalizeEvent(\n ctx: EngineContext,\n provider: MarketplaceProvider,\n payload: unknown,\n): NormalizedEvent | null {\n return ctx.registry.get(provider)?.normalize(payload) ?? null;\n}\n\n/** How a delivery ended. `duplicate` and `ignored` are both ordinary outcomes. */\nexport type DeliveryOutcome =\n | { kind: \"ingested\"; orderId: string; unmappedSkus: string[] }\n | { kind: \"cancelled\" }\n | { kind: \"cancellationFailed\" }\n /** Recorded; the order body is fetched by the `marketplace.fetch-order` job. */\n | { kind: \"awaitingOrder\" }\n | { kind: \"duplicate\" }\n | { kind: \"ignored\"; reason: string }\n | { kind: \"failed\"; reason: string };\n\n/**\n * Process one delivery for one tenant.\n *\n * NEVER throws. Every failure is caught, recorded on the inbox row, and\n * returned — because the caller is a webhook handler whose answer decides\n * whether the marketplace redelivers, and a 500 out of here would make an\n * ingestion bug indistinguishable from a network one while multiplying the\n * traffic that hits it.\n *\n * The delivery is recorded BEFORE it is processed. That ordering is the durable\n * part of the durable inbox: a process that dies mid-ingest leaves a PENDING\n * row the sweep will retry, whereas processing first and recording after loses\n * the event entirely on exactly the crashes worth surviving.\n */\nexport async function processDelivery(\n ctx: EngineContext,\n input: {\n clientId: string | null;\n event: NormalizedEvent;\n payload: unknown;\n settings: IngestSettings | null;\n now?: Date;\n },\n): Promise<DeliveryOutcome> {\n const { clientId, event, settings } = input;\n const record = await recordInboxEvent(ctx, { clientId, event, payload: input.payload });\n if (!record.fresh) return { kind: \"duplicate\" };\n\n if (!clientId || !settings) {\n // Stored, not dropped, and the two reasons are kept apart because only one\n // of them is a problem. An order naming a merchant no tenant claims is the\n // loudest possible symptom of a half-finished onboarding, and it is only\n // findable later because the row survived. An order for a store that has\n // simply switched the channel off is not a fault at all — it stays PENDING\n // for the retry sweep to pick up if the store switches it back on.\n const reason = clientId ? \"integration is not enabled\" : \"no tenant claims this merchant\";\n if (clientId) await deferInboxEvent(ctx, record.id, reason);\n else await settleInboxEvent(ctx, record.id, \"IGNORED\", reason);\n return { kind: \"ignored\", reason };\n }\n\n try {\n return await applyEvent(ctx, record.id, clientId, event, settings, input.now);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n await settleInboxEvent(ctx, record.id, \"FAILED\", reason);\n return { kind: \"failed\", reason };\n }\n}\n\n/** The event names an order whose body the marketplace serves apart (`orderToFetch`). */\nfunction announcesOrderToFetch(event: NormalizedEvent): boolean {\n return event.order === null && event.orderToFetch === true && event.externalOrderId !== null;\n}\n\n/**\n * Why an order the event CARRIES must not be ingested for this store: it names\n * another merchant than the connection's (a wrong webhook URL, a replay), the\n * rule a fetched order is held to. Read only for an order that names its\n * merchant (an adapter that sets `externalMerchantId` on the order); an order\n * that names none costs no read.\n */\nasync function carriedOrderMismatch(\n ctx: EngineContext,\n clientId: string,\n order: NormalizedMarketplaceOrder,\n): Promise<string | null> {\n if (!order.externalMerchantId) return null;\n // The one column, never the whole target: no credentials opened per order.\n return merchantMismatch(order, await connectionMerchantId(ctx, clientId, order.provider));\n}\n\n/**\n * Act on one recorded delivery: cancel, ingest, or deliberately nothing.\n *\n * Extracted so both producers share the ACTION as well as the recording — the\n * webhook and the retry sweep differ only in how they arrived here and in what\n * they do with a throw, never in what an event MEANS.\n */\nasync function applyEvent(\n ctx: EngineContext,\n inboxId: string,\n clientId: string,\n event: NormalizedEvent,\n settings: IngestSettings,\n now: Date | undefined,\n): Promise<DeliveryOutcome> {\n const outcome = event.cancellationOutcome ?? (event.cancelled ? \"CONFIRMED\" : null);\n if (outcome === \"FAILED\" && event.externalOrderId) {\n // The marketplace refused the store's own cancellation request. Understood\n // and recorded, never IGNORED: it is what tells a person to finish the\n // cancellation on the marketplace's side.\n await failCancellationRequest(ctx, {\n clientId,\n provider: event.provider,\n externalOrderId: event.externalOrderId,\n });\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n return { kind: \"cancellationFailed\" };\n }\n\n if (event.cancelled && event.externalOrderId) {\n const order = { clientId, provider: event.provider, externalOrderId: event.externalOrderId };\n // A cancellation that outran a fetched order's body leaves its marker, so\n // the fetch that follows ingests nothing.\n if (!(await cancelAcceptance(ctx, { ...order, now }))) await markCancelledBeforeIngest(ctx, order);\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n return { kind: \"cancelled\" };\n }\n\n if (announcesOrderToFetch(event)) {\n // The event announces an order whose body the marketplace serves apart.\n // Fetching is a call to the marketplace, so it is a job's, never this\n // request's: the row waits PENDING and the fetch is queued.\n await awaitOrderBody(ctx, clientId, inboxId);\n return { kind: \"awaitingOrder\" };\n }\n\n if (!event.order) {\n // An event type this ingestion does not act on. Marketplaces emit a wide\n // stream (dispatched, concluded, driver assigned…) and most of it is not an\n // order; IGNORED says \"understood, nothing to do\" and keeps it out of the\n // retry sweep, which FAILED would not.\n const reason = `no order body on ${event.eventType}`;\n await settleInboxEvent(ctx, inboxId, \"IGNORED\", reason);\n return { kind: \"ignored\", reason };\n }\n\n return ingestCarried(ctx, inboxId, clientId, event.order, settings, now);\n}\n\n/** Ingest the order an event carries, unless it names another merchant than the connection's. */\nasync function ingestCarried(\n ctx: EngineContext,\n inboxId: string,\n clientId: string,\n order: NormalizedMarketplaceOrder,\n settings: IngestSettings,\n now: Date | undefined,\n): Promise<DeliveryOutcome> {\n const mismatch = await carriedOrderMismatch(ctx, clientId, order);\n if (mismatch) {\n // FAILED, so the reconciliation sweep retries it once the connection's\n // merchant id is corrected, within the inbox's attempt bound.\n await settleInboxEvent(ctx, inboxId, \"FAILED\", mismatch);\n ctx.ports.logger.error(`marketplace.ingest: inbox row ${inboxId} refused: ${mismatch}`);\n return { kind: \"failed\", reason: mismatch };\n }\n const result = await ingestMarketplaceOrder(ctx, { clientId, order, settings, now });\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n return { kind: \"ingested\", orderId: result.orderId, unmappedSkus: result.unmappedSkus };\n}\n\n/**\n * Re-run a delivery already sitting in the inbox.\n *\n * Used by the retry sweep. It re-reads the store's CURRENT settings rather than\n * whatever they were when the event first arrived — a store that connected the\n * channel properly an hour after the first order came in should have that order\n * ingested on the retry, which is the case this exists for.\n */\nexport async function reprocessStoredDelivery(\n ctx: EngineContext,\n input: { id: string; clientId: string; provider: MarketplaceProvider; payload: unknown; receivedAt?: Date | null },\n): Promise<DeliveryOutcome> {\n const event = normalizeEvent(ctx, input.provider, input.payload);\n if (!event) {\n const reason = \"payload no longer normalizes\";\n await settleInboxEvent(ctx, input.id, \"IGNORED\", reason);\n return { kind: \"ignored\", reason };\n }\n const target = await resolveIngestionTarget(ctx, input.clientId, input.provider);\n if (!target?.enabled) {\n // Still not ready. Deferred rather than settled, for the same reason as on\n // arrival — and the attempt counter is what eventually retires it, so a\n // store that never switches the channel on does not have its inbox re-read\n // forever.\n const reason = \"integration is not enabled\";\n await deferInboxEvent(ctx, input.id, reason);\n return { kind: \"ignored\", reason };\n }\n // A row waiting for its order body is the fetch job's: re-queued, never fetched here.\n if (announcesOrderToFetch(event)) return requeueOwedFetch(ctx, input);\n try {\n return await applyEvent(\n ctx,\n input.id,\n input.clientId,\n event,\n { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds },\n undefined,\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n await settleInboxEvent(ctx, input.id, \"FAILED\", reason);\n return { kind: \"failed\", reason };\n }\n}\n","import type { AcceptanceStatus, CancellationStatus } from \"./acceptance\";\nimport type { CancellationFailureReason, EngineContext } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * What the host's order reads need to draw a marketplace order: where its\n * aceite and its cancellation request stand, and where a person goes when the\n * API could not do it. One read for a batch, so a list stays one statement.\n */\nexport interface MarketplaceOrderState {\n orderId: string;\n provider: MarketplaceProvider;\n externalOrderId: string;\n externalDisplayId: string | null;\n status: AcceptanceStatus;\n confirmedAt: Date | null;\n confirmFailedAt: Date | null;\n cancellation: CancellationStatus | null;\n cancellationReasonCode: string | null;\n /** Why the request FAILED (REFUSED or TIMEOUT); null unless `cancellation` is FAILED, and on rows from before it. */\n cancellationFailure: CancellationFailureReason | null;\n /** The adapter's app link, or null when no adapter is registered for it. */\n appUrl: string | null;\n}\n\ninterface StateRow {\n orderId: string;\n provider: string;\n externalOrderId: string;\n externalDisplayId: string | null;\n status: string;\n confirmedAt: Date | null;\n confirmFailedAt: Date | null;\n cancellationStatus: string | null;\n cancellationReasonCode: string | null;\n cancellationFailureReason: string | null;\n}\n\n/** The state of each of these orders that is a marketplace order, keyed by id. */\nexport async function readOrderStates(\n ctx: EngineContext,\n clientId: string,\n orderIds: readonly string[],\n): Promise<Map<string, MarketplaceOrderState>> {\n if (orderIds.length === 0) return new Map();\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceAcceptance.findMany({\n where: { clientId, orderId: { in: [...orderIds] } },\n select: {\n orderId: true,\n provider: true,\n externalOrderId: true,\n externalDisplayId: true,\n status: true,\n confirmedAt: true,\n confirmFailedAt: true,\n cancellationStatus: true,\n cancellationReasonCode: true,\n cancellationFailureReason: true,\n },\n })) as StateRow[];\n return new Map(\n rows.map((row) => {\n const adapter = ctx.registry.get(row.provider);\n const state: MarketplaceOrderState = {\n orderId: row.orderId,\n provider: row.provider,\n externalOrderId: row.externalOrderId,\n externalDisplayId: row.externalDisplayId,\n status: row.status as AcceptanceStatus,\n confirmedAt: row.confirmedAt,\n confirmFailedAt: row.confirmFailedAt,\n cancellation: row.cancellationStatus as CancellationStatus | null,\n cancellationReasonCode: row.cancellationReasonCode,\n cancellationFailure: row.cancellationFailureReason as CancellationFailureReason | null,\n appUrl: adapter ? adapter.appLink(row) : null,\n };\n return [row.orderId, state];\n }),\n );\n}\n","import {\n cancelAcceptance,\n expireLapsedAcceptances,\n listPendingAcceptances,\n type ExpirySweepResult,\n type PendingAcceptance,\n} from \"./acceptance\";\nimport {\n upsertIntegrations,\n upsertMenuLinks,\n type BulkResult,\n type IntegrationRowInput,\n type MenuLinkRowInput,\n} from \"./bulk\";\nimport {\n decideMany,\n decideOne,\n recordStoreCancellation,\n type DecideManyResult,\n type DecisionInput,\n type DecisionResult,\n} from \"./decisions\";\nimport {\n publishToCatalogue,\n readCatalogueDocument,\n readCatalogueState,\n withdrawFromCatalogue,\n type CatalogueActionResult,\n type CatalogueDocumentResult,\n type CataloguePublishInput,\n type CatalogueTarget,\n} from \"./catalogue\";\nimport { runCatalogue, type CatalogueJobPayload, type CatalogueOutcome } from \"./catalogue-job\";\nimport type { CatalogueMenuOptions } from \"./catalogue-port\";\nimport type { CataloguePublicationView } from \"./catalogue-store\";\nimport {\n runFetchOrder,\n type FetchOrderJobPayload,\n type FetchOrderOutcome,\n} from \"./fetch-order\";\nimport { sweepOutbound, type OutboundSweepResult } from \"./outbound-sweep\";\nimport type {\n AdapterTokenCache,\n CancellationReason,\n MarketplaceAdapter,\n OutboundOrderRef,\n} from \"./adapter\";\nimport { listRetryableInboxEvents, type PendingInboxEvent } from \"./inbox\";\nimport { ingestMarketplaceOrder, type IngestResult, type IngestSettings } from \"./ingest\";\nimport {\n listMarketplaceIntegrations,\n resolveIngestionTarget,\n resolveTenantByMerchant,\n saveMarketplaceIntegration,\n type IngestionTarget,\n type MarketplaceIntegrationView,\n type SaveMarketplaceIntegrationInput,\n} from \"./integration\";\nimport { listMarketplaceMenuLinks, type MarketplaceMenuLinkView } from \"./menu-links\";\nimport { runOutbound, type OutboundAttempt, type OutboundOutcome } from \"./outbound\";\nimport type { OutboundJobPayload } from \"./outbound-queue\";\nimport {\n normalizeEvent,\n processDelivery,\n reprocessStoredDelivery,\n type DeliveryOutcome,\n} from \"./pipeline\";\nimport type { EngineContext, MarketplaceEngineConfig } from \"./ports\";\nimport { createAdapterRegistry, suggestReason } from \"./registry\";\nimport { readOrderStates, type MarketplaceOrderState } from \"./state\";\nimport type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from \"./types\";\n\n/** Everything the mounted engine can do, with the ports and adapters bound in. */\nexport interface MarketplaceEngine {\n /** Every registered marketplace, in registration order. */\n providers(): readonly MarketplaceProvider[];\n /** Whether a provider id (a URL segment, a body field) names a registered adapter. */\n knows(provider: string): provider is MarketplaceProvider;\n /** The adapter itself: its capabilities, reasons and app link. Null when unknown. */\n adapter(provider: string): MarketplaceAdapter | null;\n /** The marketplace's reasons, static and offline. Empty when unknown. */\n reasons(provider: string): readonly CancellationReason[];\n /** The reason a host preselects, given whether the order is short of an item. */\n suggestReason(provider: string, input: { itemUnavailable: boolean }): CancellationReason | null;\n /** Where a person goes to act on the marketplace's side. Null when unknown. */\n appLink(provider: string, order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string | null;\n\n /** Turn a raw payload into the canonical shape, or null if nothing does. */\n normalize(provider: string, payload: unknown): NormalizedEvent | null;\n /** Read the provider's signature header off a request. */\n readSignature(provider: string, header: (name: string) => string | null): string | null;\n /** Verify a delivery. An unknown provider is never verified, so never accepted. */\n verifySignature(provider: string, rawBody: string, signature: string | null, secret: string | null): boolean;\n /** Which tenant a delivery belongs to, from the merchant id it names. */\n tenantFor(provider: MarketplaceProvider, externalMerchantId: string): Promise<string | null>;\n /** The connection behind one (tenant, marketplace), for the ingestion path. */\n target(clientId: string, provider: MarketplaceProvider): Promise<IngestionTarget | null>;\n /** Ingest ONE already-normalized order, bypassing the inbox. Idempotent. */\n ingest(input: {\n clientId: string;\n order: NormalizedMarketplaceOrder;\n settings: IngestSettings;\n now?: Date;\n }): Promise<IngestResult>;\n /** Record and act on one delivery. Never throws. */\n deliver(input: {\n clientId: string | null;\n event: NormalizedEvent;\n payload: unknown;\n settings: IngestSettings | null;\n now?: Date;\n }): Promise<DeliveryOutcome>;\n\n /** This store's connections, secrets withheld; archived ones only when asked. */\n integrations(\n clientId: string,\n options?: { providers?: readonly string[]; includeArchived?: boolean },\n ): Promise<MarketplaceIntegrationView[]>;\n /** Create or patch ONE connection (the bulk call's single-row form, with no audit). */\n saveIntegration(input: SaveMarketplaceIntegrationInput): Promise<MarketplaceIntegrationView>;\n /** Create, patch, archive or unarchive many connections, all-or-nothing. */\n upsertIntegrations(input: {\n clientId: string;\n actorId: string | null;\n rows: readonly IntegrationRowInput[];\n validateOnly?: boolean;\n }): Promise<BulkResult<MarketplaceIntegrationView>>;\n\n /** The SKU map. `unmappedOnly` is the store's attention list; `ids` narrows. */\n menuLinks(input: {\n clientId: string;\n provider?: MarketplaceProvider;\n unmappedOnly?: boolean;\n ids?: readonly string[];\n }): Promise<MarketplaceMenuLinkView[]>;\n /** Map or unmap many SKUs, all-or-nothing. */\n upsertMenuLinks(input: {\n clientId: string;\n rows: readonly MenuLinkRowInput[];\n validateOnly?: boolean;\n }): Promise<BulkResult<MarketplaceMenuLinkView>>;\n /** Map or unmap ONE SKU. `null` = the catalog id is not this tenant's. */\n setMenuLink(input: { clientId: string } & MenuLinkRowInput): Promise<MarketplaceMenuLinkView | null>;\n\n /** Orders still on the clock, soonest deadline first; `orderIds` narrows. */\n pending(clientId: string, orderIds?: readonly string[]): Promise<PendingAcceptance[]>;\n /** Decide many orders, all-or-nothing, the host admitting each inside the claim's transaction. */\n decideMany(input: {\n clientId: string;\n decisions: readonly DecisionInput[];\n validateOnly?: boolean;\n now?: Date;\n }): Promise<DecideManyResult>;\n /** Decide ONE order (`decideMany` with one decision). */\n decide(input: { clientId: string; now?: Date } & DecisionInput): Promise<DecisionResult>;\n /** The store cancelled through the host's own cancel: stamp and queue the request. */\n recordStoreCancellation(input: {\n clientId: string;\n orderId: string;\n reasonCode?: string | null;\n offendingSkus?: readonly string[];\n now?: Date;\n }): Promise<DecisionResult>;\n /** The marketplace cancelled an order we already have. */\n cancel(input: {\n clientId: string;\n provider: MarketplaceProvider;\n externalOrderId: string;\n now?: Date;\n }): Promise<boolean>;\n /** Where each of these orders' acceptance and cancellation stand. */\n orderStates(clientId: string, orderIds: readonly string[]): Promise<Map<string, MarketplaceOrderState>>;\n\n /** Expire every order whose deadline has passed, across all tenants. */\n expireLapsed(now?: Date): Promise<ExpirySweepResult>;\n /** Deliveries recorded but never processed, oldest first. */\n retryable(): Promise<PendingInboxEvent[]>;\n /** Re-run one stored delivery against the store's CURRENT settings. */\n reprocess(event: PendingInboxEvent): Promise<DeliveryOutcome>;\n /** Re-queue every outbound call still owed (the `marketplace.outbound-sweep` job's body). */\n sweepOutbound(now?: Date): Promise<OutboundSweepResult>;\n /** Run one queued outbound call (the `marketplace.outbound` job's body). */\n runOutbound(payload: OutboundJobPayload, attempt: OutboundAttempt): Promise<OutboundOutcome>;\n /** Fetch and ingest one announced order (the `marketplace.fetch-order` job's body). */\n runFetchOrder(payload: FetchOrderJobPayload, attempt: OutboundAttempt): Promise<FetchOrderOutcome>;\n\n /**\n * How this marketplace's catalogue is published (`push`, `pull`), or null\n * when it cannot be: the adapter states no catalogue, or the host bound no\n * catalogue port (FUT-4768).\n */\n catalogueMode(provider: string): \"push\" | \"pull\" | null;\n /** Put a product in a marketplace's catalogue (or send it again), with an optional price for it. Queued. */\n publish(input: CataloguePublishInput): Promise<CatalogueActionResult>;\n /** Take a product out of a marketplace's catalogue. Queued. */\n withdraw(input: CatalogueTarget): Promise<CatalogueActionResult>;\n /** Where these products stand on these marketplaces, in one read. */\n catalogueState(input: {\n clientId: string;\n productIds: readonly string[];\n providers?: readonly string[];\n }): Promise<CataloguePublicationView[]>;\n /** The menu part of the document a PULL marketplace reads, for the host to serve. */\n catalogueDocument(input: {\n clientId: string;\n provider: MarketplaceProvider;\n options: CatalogueMenuOptions;\n }): Promise<CatalogueDocumentResult>;\n /** Run one queued publish or withdraw (the `marketplace.catalogue` job's body). */\n runCatalogue(payload: CatalogueJobPayload, attempt: OutboundAttempt): Promise<CatalogueOutcome>;\n}\n\n/**\n * Mount the engine onto a host.\n *\n * Every port is REQUIRED and there are no defaults: a default would let a\n * second host silently inherit the first one's answers. The adapter list is\n * validated here (`createAdapterRegistry`), so a malformed adapter fails at\n * boot rather than on the first order it would have mangled.\n */\nexport function createMarketplaceEngine(config: MarketplaceEngineConfig): MarketplaceEngine {\n const { adapters, ...ports } = config;\n const registry = createAdapterRegistry(adapters);\n const tokens: AdapterTokenCache = new Map();\n const ctx: EngineContext = { ports, registry, tokens };\n\n return {\n providers: () => registry.providers(),\n knows: (provider): provider is MarketplaceProvider => registry.has(provider),\n adapter: (provider) => registry.get(provider),\n reasons: (provider) => registry.get(provider)?.cancellationReasons() ?? [],\n suggestReason: (provider, input) => {\n const adapter = registry.get(provider);\n return adapter ? suggestReason(adapter, input) : null;\n },\n appLink: (provider, order) => registry.get(provider)?.appLink(order) ?? null,\n\n normalize: (provider, payload) => normalizeEvent(ctx, provider, payload),\n readSignature: (provider, header) => registry.get(provider)?.readSignature(header) ?? null,\n // An unknown provider cannot be verified, so it is not accepted: trusting\n // what cannot be checked is how an unsigned endpoint ships by omission.\n verifySignature: (provider, rawBody, signature, secret) =>\n registry.get(provider)?.verifySignature(rawBody, signature, secret) ?? false,\n tenantFor: (provider, externalMerchantId) =>\n resolveTenantByMerchant(ctx, provider, externalMerchantId),\n target: (clientId, provider) => resolveIngestionTarget(ctx, clientId, provider),\n ingest: (input) => ingestMarketplaceOrder(ctx, input),\n deliver: (input) => processDelivery(ctx, input),\n\n integrations: (clientId, options) => listMarketplaceIntegrations(ctx, clientId, options),\n saveIntegration: async (input) => saveMarketplaceIntegration(ctx, input, await ports.db()),\n upsertIntegrations: (input) => upsertIntegrations(ctx, input),\n\n menuLinks: (input) => listMarketplaceMenuLinks(ctx, input),\n upsertMenuLinks: (input) => upsertMenuLinks(ctx, input),\n setMenuLink: async ({ clientId, ...row }) => {\n const result = await upsertMenuLinks(ctx, { clientId, rows: [row] });\n return result.kind === \"saved\" ? (result.rows[0] ?? null) : null;\n },\n\n pending: (clientId, orderIds) => listPendingAcceptances(ctx, clientId, orderIds),\n decideMany: (input) => decideMany(ctx, input),\n decide: (input) => decideOne(ctx, input),\n recordStoreCancellation: (input) => recordStoreCancellation(ctx, input),\n cancel: (input) => cancelAcceptance(ctx, input),\n orderStates: (clientId, orderIds) => readOrderStates(ctx, clientId, orderIds),\n\n expireLapsed: (now) => expireLapsedAcceptances(ctx, now ?? ports.clock.now()),\n retryable: () => listRetryableInboxEvents(ctx),\n reprocess: (event) => reprocessStoredDelivery(ctx, event),\n sweepOutbound: (now) => sweepOutbound(ctx, now ?? ports.clock.now()),\n runOutbound: (payload, attempt) => runOutbound(ctx, payload, attempt),\n runFetchOrder: (payload, attempt) => runFetchOrder(ctx, payload, attempt),\n\n // Null too when the host bound no catalogue port: nothing could be published.\n catalogueMode: (provider) => (ports.catalogue ? (registry.get(provider)?.catalogue?.mode ?? null) : null),\n publish: (input) => publishToCatalogue(ctx, input),\n withdraw: (input) => withdrawFromCatalogue(ctx, input),\n catalogueState: (input) => readCatalogueState(ctx, input),\n catalogueDocument: (input) => readCatalogueDocument(ctx, input),\n runCatalogue: (payload, attempt) => runCatalogue(ctx, payload, attempt),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAS,WAAc,MAAoB,OAA2B,MAAc,OAA8B;AAChH,QAAM,OAAO,oBAAI,IAAY;AAC7B,SAAO,KAAK,QAAQ,CAAC,KAAK,UAAU;AAClC,UAAM,MAAM,MAAM,GAAG;AACrB,QAAI,CAAC,KAAK,IAAI,GAAG,GAAG;AAClB,WAAK,IAAI,GAAG;AACZ,aAAO,CAAC;AAAA,IACV;AACA,WAAO,CAAC,EAAE,MAAM,CAAC,MAAM,OAAO,KAAK,GAAG,MAAM,YAAqB,CAAC;AAAA,EACpE,CAAC;AACH;AAVS;AAYT,SAAS,iBAAiB,KAAoB,MAAuC,MAA6B;AAChH,SAAO,KAAK;AAAA,IAAQ,CAAC,KAAK,UACxB,IAAI,SAAS,IAAI,IAAI,QAAQ,IAAI,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,OAAO,UAAU,GAAG,MAAM,mBAA4B,CAAC;AAAA,EAC/G;AACF;AAJS;AAMT,IAAM,eAAe,CAAC,WAAW,eAAe,sBAAsB,cAAc,iBAAiB,aAAa;AAElH,SAAS,uBACP,KACA,OACA,UACe;AACf,MAAI,IAAI,cAAc,aAAa,IAAI,cAAc,aAAa;AAChE,WAAO,SAAS,IAAI,IAAI,QAAQ,IAAI,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,gBAAgB,OAAO,UAAU,GAAG,MAAM,YAAY,CAAC;AAAA,EAC5G;AACA,QAAM,WAAW;AACjB,QAAM,UAAU,aAAa,KAAK,CAAC,QAAQ,SAAS,GAAG,MAAM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