@12-apps/marketplace 1.7.0 → 1.8.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.
- package/ADOPTING.md +17 -0
- package/README.md +56 -0
- package/dist/99food/index.d.ts +4 -2
- package/dist/99food/index.js +32 -3
- package/dist/99food/index.js.map +1 -1
- package/dist/{adapter-DOjTak1H.d.ts → adapter-CYJzu1c9.d.ts} +45 -1
- package/dist/{chunk-YVUZHXUF.js → chunk-6N2HEV3U.js} +4 -4
- package/dist/chunk-6N2HEV3U.js.map +1 -0
- package/dist/{chunk-SJUKBCVO.js → chunk-BMCERPQX.js} +198 -12
- package/dist/chunk-BMCERPQX.js.map +1 -0
- package/dist/{chunk-L3DCOZUU.js → chunk-HEXLCTOG.js} +1 -1
- package/dist/chunk-HEXLCTOG.js.map +1 -0
- package/dist/{chunk-UYFYGGCS.js → chunk-NP4EYKPO.js} +3 -1
- package/dist/chunk-NP4EYKPO.js.map +1 -0
- package/dist/{engine-DG1fg43Y.d.ts → engine-wmW-VuBL.d.ts} +107 -4
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +3 -3
- package/dist/ifood/index.d.ts +1 -1
- package/dist/ifood/index.js +29 -3
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +104 -7
- package/dist/index.js.map +1 -1
- package/dist/manifest/index.d.ts +3 -0
- package/dist/manifest/index.js +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/manifest/server.js +3 -3
- package/dist/rappi/index.d.ts +7 -1
- package/dist/rappi/index.js +20 -3
- package/dist/rappi/index.js.map +1 -1
- package/dist/server/index.d.ts +6 -2
- package/dist/server/index.js +3 -3
- package/package.json +1 -1
- package/prisma/marketplace.prisma +45 -1
- package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
- package/src/99food/index.ts +6 -0
- package/src/99food/normalize.ts +7 -1
- package/src/99food/outbound.ts +55 -0
- package/src/core/adapter.ts +41 -1
- package/src/core/bulk.ts +1 -1
- package/src/core/engine.ts +9 -0
- package/src/core/ingest.ts +6 -0
- package/src/core/integration.ts +17 -0
- package/src/core/lifecycle-port.ts +16 -0
- package/src/core/lifecycle.ts +133 -0
- package/src/core/outbound-queue.ts +24 -4
- package/src/core/outbound-sweep.ts +49 -5
- package/src/core/outbound.ts +11 -0
- package/src/core/pipeline.ts +22 -2
- package/src/core/ports.ts +39 -3
- package/src/core/status-inform.ts +51 -0
- package/src/core/status-job.ts +207 -0
- package/src/core/status-store.ts +85 -0
- package/src/core/types.ts +14 -0
- package/src/ifood/index.ts +7 -1
- package/src/ifood/normalize.ts +17 -0
- package/src/ifood/outbound.ts +35 -0
- package/src/index.ts +6 -0
- package/src/rappi/index.ts +6 -1
- package/src/rappi/normalize.ts +6 -0
- package/src/rappi/outbound.ts +31 -2
- package/src/server/mcp.ts +2 -0
- package/src/server/webhook.ts +3 -1
- package/dist/chunk-L3DCOZUU.js.map +0 -1
- package/dist/chunk-SJUKBCVO.js.map +0 -1
- package/dist/chunk-UYFYGGCS.js.map +0 -1
- package/dist/chunk-YVUZHXUF.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/bulk.ts","../src/core/decisions.ts","../src/core/catalogue.ts","../src/core/catalogue-read.ts","../src/core/pause.ts","../src/core/pause-sweep.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 // (REFUSED: its own limit): the order stays, and a person cancels it in\n // 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 // The document needs only the merchant id: no credentials are opened to serve it.\n const externalMerchantId = await connectionMerchantId(ctx, input.clientId, input.provider);\n if (externalMerchantId === null) 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, entries, options: input.options });\n return { kind: \"document\", document };\n}\n","import type { CatalogueReadResult } from \"./catalogue-read-port\";\nimport { connectionMerchantId, readOutboundConnection } from \"./integration\";\nimport type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * Reading the menu a store keeps on a marketplace, as a host calls it\n * (FUT-951): through the store's OWN connection (its merchant id and its\n * sealed credentials), with the adapter's `catalogueReader`. Nothing is\n * stamped or queued: the read is a question the host asks while the store\n * waits, and it answers the snapshot or why there is none.\n */\nexport async function readMarketplaceCatalogue(\n ctx: EngineContext,\n input: { clientId: string; provider: MarketplaceProvider; now?: Date },\n): Promise<CatalogueReadResult> {\n const reader = ctx.registry.get(input.provider)?.catalogueReader;\n if (!reader) return engineRefusal(\"UNSUPPORTED\");\n const merchantId = await connectionMerchantId(ctx, input.clientId, input.provider);\n if (merchantId === null) return engineRefusal(\"NOT_CONNECTED\");\n let connection: Awaited<ReturnType<typeof readOutboundConnection>>;\n try {\n connection = await readOutboundConnection(ctx, input.clientId, input.provider);\n } catch (error) {\n ctx.ports.logger.error(\n `marketplace.catalogue-read: ${input.provider} credentials of ${input.clientId} do not open: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n return engineRefusal(\"CREDENTIALS\");\n }\n if (!connection) return engineRefusal(\"CREDENTIALS\");\n try {\n return await reader.read({\n ...connection,\n http: ctx.ports.http,\n tokens: ctx.tokens,\n now: input.now ?? ctx.ports.clock.now(),\n externalMerchantId: merchantId,\n });\n } catch (error) {\n // The port says an adapter never throws; one that does is asked again later, not crashed on.\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\nconst engineRefusal = (code: \"UNSUPPORTED\" | \"NOT_CONNECTED\" | \"CREDENTIALS\"): CatalogueReadResult => ({\n kind: \"refused\",\n code,\n status: null,\n message: null,\n});\n","import type { EngineContext } from \"./ports\";\nimport {\n availabilityDedupeKey,\n enqueueAvailability,\n holdsSomething,\n pauseTable,\n readPause,\n type StorePauseFailureCode,\n type StorePauseRow,\n type StorePauseState,\n type StorePauseWanted,\n} from \"./pause-store\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * The store pause, as the host calls it (FUT-4851): `pauseStore` when the\n * kitchen pauses and on every renewal, `resumeStore` the moment the pause is\n * over, `availabilityState` for the screen. The host owns the debounce; these\n * calls only record the ask and queue `marketplace.availability`, whose job\n * makes the calls (`./pause-job.ts`). No path that answers a request reaches\n * a marketplace.\n */\n\n/** What `pauseStore` did on one marketplace. */\nexport type PauseOutcome =\n /** The ask was recorded and the job queued. */\n | \"queued\"\n /** A pause with exactly this end already stands or is on its way. */\n | \"unchanged\"\n /** The marketplace's adapter cannot pause a store: the host says so. */\n | \"unsupported\"\n /** The connection has no credentials or no merchant id. */\n | \"not-connected\";\n\n/** What `resumeStore` did on one marketplace. */\nexport type ResumeOutcome =\n /** Something of ours stands on the marketplace: the job deletes it. */\n | \"queued\"\n /** Nothing of ours stands there: the record is OPEN, and nobody is called. */\n | \"open\"\n /** A resume is already on its way. */\n | \"unchanged\";\n\nexport interface PauseStoreInput {\n clientId: string;\n /** The kitchen's estimated reopening time: the end every marketplace is given. */\n until: Date;\n /** The host's words for the closure (its copy, in the store's language). */\n reason: string;\n /** The store's IANA time zone. */\n timeZone: string;\n now?: Date;\n}\n\nexport type PauseStoreResult =\n | { kind: \"invalid\"; code: \"UNTIL_NOT_FUTURE\" | \"TIME_ZONE_INVALID\" }\n | { kind: \"ok\"; marketplaces: { provider: MarketplaceProvider; outcome: PauseOutcome }[] };\n\n/** One marketplace's pause as the screen shows it. */\nexport interface StoreAvailabilityView {\n provider: MarketplaceProvider;\n /** The adapter can pause a store at all. */\n supported: boolean;\n /** `interruption` (an id and an end) or `switch` (on/off); null when unsupported. */\n kind: \"interruption\" | \"switch\" | null;\n /** The connection has credentials and a merchant id. */\n connected: boolean;\n state: StorePauseState;\n wanted: StorePauseWanted;\n /** The end the host asked for. */\n until: Date | null;\n /** The end the marketplace was given and confirmed. */\n sentUntil: Date | null;\n failureCode: StorePauseFailureCode | null;\n /** The marketplace's own words, verbatim and cut; never copy to show as is. */\n failureDetail: string | null;\n pausedAt: Date | null;\n resumedAt: Date | null;\n updatedAt: Date | null;\n}\n\ninterface ConnectionRow {\n provider: string;\n externalMerchantId: string | null;\n credentials: string;\n}\n\n/** The store's live connections (enabled, not archived), with whether each can be called. */\nasync function liveConnections(ctx: EngineContext, clientId: string): Promise<ConnectionRow[]> {\n const db = await ctx.ports.db();\n return (await db.marketplaceIntegration.findMany({\n where: { clientId, enabled: true, archivedAt: null },\n select: { provider: true, externalMerchantId: true, credentials: true },\n orderBy: { provider: \"asc\" },\n })) as ConnectionRow[];\n}\n\nconst isConnected = (row: ConnectionRow): boolean => row.credentials !== \"\" && Boolean(row.externalMerchantId);\n\n/** Whether an IANA zone name is one this runtime knows. */\nfunction validTimeZone(timeZone: string): boolean {\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone });\n return timeZone !== \"\";\n } catch {\n return false;\n }\n}\n\n/**\n * Whether a pause with exactly this end already stands, or is on its way. An\n * earlier end is asked like a later one: the store is never closed on a\n * marketplace longer than the kitchen's own pause.\n */\nfunction alreadyAsked(row: StorePauseRow | null, until: Date): boolean {\n if (!row || row.wanted !== \"PAUSED\") return false;\n if (row.state !== \"PAUSING\" && row.state !== \"PAUSED\") return false;\n return row.until !== null && row.until.getTime() === until.getTime();\n}\n\n/** Record one marketplace's pause and queue its job, unless it already stands. */\nasync function askPause(ctx: EngineContext, input: Required<PauseStoreInput>, provider: string): Promise<PauseOutcome> {\n const existing = await readPause(ctx, input.clientId, provider);\n if (alreadyAsked(existing, input.until)) return \"unchanged\";\n const table = pauseTable(await ctx.ports.db());\n const data = {\n wanted: \"PAUSED\",\n state: \"PAUSING\",\n until: input.until,\n reason: input.reason,\n timeZone: input.timeZone,\n requestedAt: input.now,\n // No key is minted here: the job writes one just before its call, so a\n // resume that lands first knows nothing of ours can stand there. A key\n // still in doubt stays on the row (its create may have landed).\n failureCode: null,\n failureDetail: null,\n failedAt: null,\n };\n await table.upsert({\n where: { clientId_provider: { clientId: input.clientId, provider } },\n create: { clientId: input.clientId, provider, ...data },\n update: data,\n });\n const payload = { clientId: input.clientId, provider };\n await enqueueAvailability(ctx, payload, availabilityDedupeKey(payload, input.now));\n return \"queued\";\n}\n\n/**\n * Pause the store on every live connection whose marketplace can be paused.\n * Idempotent: a pause already standing (or on its way) with exactly this end\n * does nothing; any other end renews it, an earlier one included. Called again\n * on every renewal of the kitchen's pause.\n */\nexport async function pauseStore(ctx: EngineContext, input: PauseStoreInput): Promise<PauseStoreResult> {\n const now = input.now ?? ctx.ports.clock.now();\n if (input.until.getTime() <= now.getTime()) return { kind: \"invalid\", code: \"UNTIL_NOT_FUTURE\" };\n if (!validTimeZone(input.timeZone)) return { kind: \"invalid\", code: \"TIME_ZONE_INVALID\" };\n pauseTable(await ctx.ports.db());\n const full = { ...input, now };\n const marketplaces: { provider: MarketplaceProvider; outcome: PauseOutcome }[] = [];\n for (const connection of await liveConnections(ctx, input.clientId)) {\n const adapter = ctx.registry.get(connection.provider);\n let outcome: PauseOutcome;\n if (!adapter?.availability) outcome = \"unsupported\";\n else if (!isConnected(connection)) outcome = \"not-connected\";\n else outcome = await askPause(ctx, full, connection.provider);\n marketplaces.push({ provider: connection.provider, outcome });\n }\n if (marketplaces.some((entry) => entry.outcome === \"queued\")) ctx.ports.publishChanged(input.clientId);\n return { kind: \"ok\", marketplaces };\n}\n\n/**\n * Rewrite one record's ask to OPEN; queue the job when something of ours\n * stands there OR may be on its way: a PAUSING record may have a call in\n * flight whose key the job wrote after this read. The write is predicated on\n * the key read, so a claim that lands in between makes this re-read.\n */\nasync function askResume(ctx: EngineContext, read: StorePauseRow, now: Date): Promise<ResumeOutcome> {\n let row: StorePauseRow | null = read;\n for (let tries = 0; row && tries < 3; tries += 1) {\n if (resumeAsked(row)) return \"unchanged\";\n const outcome = await writeResume(ctx, row, now);\n if (outcome !== null) return outcome;\n row = await readPause(ctx, read.clientId, read.provider);\n }\n return row ? forceResume(ctx, row, now) : \"unchanged\";\n}\n\n/**\n * Every predicated write missed (the row kept moving): the resume is never\n * lost. RESUMING with no predicate, and the job queued: it re-reads the row\n * and deletes whatever of ours stands, or finds nothing and settles OPEN.\n */\nasync function forceResume(ctx: EngineContext, row: StorePauseRow, now: Date): Promise<ResumeOutcome> {\n const table = pauseTable(await ctx.ports.db());\n await table.updateMany({\n where: { id: row.id },\n data: { wanted: \"OPEN\", state: \"RESUMING\", requestedAt: now, failureCode: null, failureDetail: null, failedAt: null },\n });\n const payload = { clientId: row.clientId, provider: row.provider };\n await enqueueAvailability(ctx, payload, availabilityDedupeKey(payload, now));\n return \"queued\";\n}\n\n/** Whether a resume already stands: on its way, or OPEN with nothing of ours left. */\nfunction resumeAsked(row: StorePauseRow): boolean {\n if (row.wanted !== \"OPEN\") return false;\n return row.state === \"RESUMING\" || (row.state === \"OPEN\" && !holdsSomething(row));\n}\n\n/** The resume's write, predicated on the key read; null when the row moved under it. */\nasync function writeResume(ctx: EngineContext, row: StorePauseRow, now: Date): Promise<ResumeOutcome | null> {\n const held = holdsSomething(row) || row.state === \"PAUSING\";\n const table = pauseTable(await ctx.ports.db());\n const moved = await table.updateMany({\n where: { id: row.id, attemptKey: row.attemptKey },\n data: {\n wanted: \"OPEN\",\n state: held ? \"RESUMING\" : \"OPEN\",\n requestedAt: now,\n failureCode: null,\n failureDetail: null,\n failedAt: null,\n ...(held ? {} : { resumedAt: now }),\n },\n });\n if (moved.count === 0) return null;\n if (!held) return \"open\";\n const payload = { clientId: row.clientId, provider: row.provider };\n await enqueueAvailability(ctx, payload, availabilityDedupeKey(payload, now));\n return \"queued\";\n}\n\n/**\n * The kitchen's pause is over: open the store again wherever the engine\n * closed it. Only what the engine created is deleted; a marketplace where\n * nothing of ours stands is not called at all. Every record is answered,\n * a connection disabled since the pause included.\n */\nexport async function resumeStore(\n ctx: EngineContext,\n input: { clientId: string; now?: Date },\n): Promise<{ marketplaces: { provider: MarketplaceProvider; outcome: ResumeOutcome }[] }> {\n const now = input.now ?? ctx.ports.clock.now();\n const table = pauseTable(await ctx.ports.db());\n const rows = (await table.findMany({\n where: { clientId: input.clientId },\n orderBy: { provider: \"asc\" },\n })) as StorePauseRow[];\n const marketplaces: { provider: MarketplaceProvider; outcome: ResumeOutcome }[] = [];\n for (const row of rows) marketplaces.push({ provider: row.provider, outcome: await askResume(ctx, row, now) });\n if (marketplaces.some((entry) => entry.outcome !== \"unchanged\")) ctx.ports.publishChanged(input.clientId);\n return { marketplaces };\n}\n\n/** What a marketplace with no record reads as: OPEN, never asked. */\nconst NEVER_ASKED: Omit<StoreAvailabilityView, \"provider\" | \"supported\" | \"kind\" | \"connected\"> = {\n state: \"OPEN\",\n wanted: \"OPEN\",\n until: null,\n sentUntil: null,\n failureCode: null,\n failureDetail: null,\n pausedAt: null,\n resumedAt: null,\n updatedAt: null,\n};\n\nfunction viewOf(ctx: EngineContext, provider: string, connection: ConnectionRow | undefined, row: StorePauseRow | undefined): StoreAvailabilityView {\n const availability = ctx.registry.get(provider)?.availability;\n const recorded = row\n ? {\n state: row.state,\n wanted: row.wanted,\n until: row.until,\n sentUntil: row.sentUntil,\n failureCode: row.failureCode,\n failureDetail: row.failureDetail,\n pausedAt: row.pausedAt,\n resumedAt: row.resumedAt,\n updatedAt: row.updatedAt,\n }\n : NEVER_ASKED;\n return {\n provider,\n supported: availability !== undefined,\n kind: availability?.kind ?? null,\n connected: connection !== undefined && isConnected(connection),\n ...recorded,\n };\n}\n\n/**\n * Where the store's pause stands on each marketplace: every live connection,\n * plus any record of a connection since disabled that still holds something.\n * A host on a database without the pause model reads every marketplace OPEN.\n */\nexport async function availabilityState(ctx: EngineContext, clientId: string): Promise<StoreAvailabilityView[]> {\n const db = await ctx.ports.db();\n const connections = await liveConnections(ctx, clientId);\n const rows = db.marketplaceStorePause\n ? ((await db.marketplaceStorePause.findMany({ where: { clientId } })) as StorePauseRow[])\n : [];\n const byProvider = new Map(rows.map((row) => [row.provider, row]));\n const views = connections.map((connection) =>\n viewOf(ctx, connection.provider, connection, byProvider.get(connection.provider)),\n );\n const live = new Set(connections.map((connection) => connection.provider));\n for (const row of rows) {\n if (!live.has(row.provider) && holdsSomething(row)) views.push(viewOf(ctx, row.provider, undefined, row));\n }\n return views;\n}\n","import { OUTBOUND_GIVE_UP_MS, OUTBOUND_STALE_MS } from \"./outbound-sweep\";\nimport {\n availabilityDedupeKey,\n enqueueAvailability,\n hasPauseTable,\n holdsSomething,\n pauseTable,\n type StorePauseRow,\n} from \"./pause-store\";\nimport type { EngineContext } from \"./ports\";\n\n/**\n * The availability sweep (`marketplace.availability-sweep`, every five\n * minutes): nothing the engine owes a marketplace for a store's pause is lost,\n * and no store stays closed past the kitchen's pause (FUT-4851).\n *\n * - **Expired**: a pause whose `until` has passed without a renewal is over.\n * The host stopped renewing (it died, or forgot to resume), so the engine\n * resumes on its own: the owner's \"never closed on a marketplace longer than\n * the kitchen's own pause\". An interruption has already ended on the\n * marketplace (its delete answers \"gone\", which is done); a switch would\n * otherwise stay off for good.\n * - **Stale**: an ask still PAUSING or RESUMING after the job's own retry span\n * (a refused enqueue, a dead process) is re-queued; past\n * {@link OUTBOUND_GIVE_UP_MS} it is FAILED as unanswered.\n * - **A failed resume that still holds something** is retried each pass until\n * the give-up: a store must not stay closed because one delete failed.\n * - **A replaced closure** an extend could not delete is retried.\n * - **An OPEN record that still holds something** (a pause call whose answer\n * was lost after a resume landed) goes back to RESUMING and is re-queued.\n *\n * Re-queued under a key of its own per pass, as the outbound sweep does. The\n * job is idempotent by the row and leased, so a duplicate run calls nobody\n * twice.\n */\n\n/** What one pass did. */\nexport interface AvailabilitySweepResult {\n /** Pauses past their `until`, turned into resumes. */\n expired: number;\n /** Asks re-queued. */\n requeued: number;\n /** Asks failed as unanswered past the give-up. */\n givenUp: number;\n}\n\nconst sweepKey = (row: StorePauseRow, now: Date): string =>\n availabilityDedupeKey({ clientId: row.clientId, provider: row.provider }, row.requestedAt, `:sweep:${now.getTime()}`);\n\nasync function requeue(ctx: EngineContext, rows: readonly StorePauseRow[], now: Date): Promise<number> {\n let queued = 0;\n for (const row of rows) {\n if (await enqueueAvailability(ctx, { clientId: row.clientId, provider: row.provider }, sweepKey(row, now))) queued += 1;\n }\n return queued;\n}\n\n/** Pauses past their end: resume them, predicated on nobody having renewed meanwhile. */\nasync function expire(ctx: EngineContext, now: Date): Promise<number> {\n const table = pauseTable(await ctx.ports.db());\n const rows = (await table.findMany({\n where: { wanted: \"PAUSED\", state: { in: [\"PAUSING\", \"PAUSED\", \"FAILED\"] }, until: { lt: now } },\n })) as StorePauseRow[];\n let expired = 0;\n for (const row of rows) {\n const held = holdsSomething(row);\n const moved = await table.updateMany({\n where: { id: row.id, wanted: \"PAUSED\", until: row.until },\n data: { wanted: \"OPEN\", state: held ? \"RESUMING\" : \"OPEN\", requestedAt: now, failureCode: null, failureDetail: null, failedAt: null },\n });\n if (moved.count === 0) continue;\n expired += 1;\n ctx.ports.publishChanged(row.clientId);\n if (held) await requeue(ctx, [{ ...row, requestedAt: now }], now);\n }\n return expired;\n}\n\n/** Asks waiting past the give-up: FAILED as unanswered. */\nasync function giveUp(ctx: EngineContext, cutoff: Date, now: Date): Promise<number> {\n const table = pauseTable(await ctx.ports.db());\n let failed = 0;\n for (const [state, code] of [[\"PAUSING\", \"PAUSE_UNANSWERED\"], [\"RESUMING\", \"RESUME_UNANSWERED\"]] as const) {\n const moved = await table.updateMany({\n where: { state, requestedAt: { lt: cutoff } },\n data: { state: \"FAILED\", failureCode: code, failureDetail: null, failedAt: now },\n });\n failed += moved.count;\n }\n return failed;\n}\n\n/** A failed resume that still holds something, failed for a while and asked inside the give-up: back to RESUMING. */\nasync function retryFailedResumes(ctx: EngineContext, stale: Date, cutoff: Date): Promise<StorePauseRow[]> {\n const table = pauseTable(await ctx.ports.db());\n const rows = (await table.findMany({\n where: { state: \"FAILED\", wanted: \"OPEN\", failedAt: { lt: stale }, requestedAt: { gte: cutoff } },\n })) as StorePauseRow[];\n const retried: StorePauseRow[] = [];\n for (const row of rows.filter(holdsSomething)) {\n const moved = await table.updateMany({ where: { id: row.id, state: \"FAILED\", wanted: \"OPEN\" }, data: { state: \"RESUMING\" } });\n if (moved.count > 0) retried.push(row);\n }\n return retried;\n}\n\n/**\n * An OPEN record that still holds something (a call whose answer was lost\n * after a resume landed): back to RESUMING, so the job deletes it.\n */\nasync function reopenOrphans(ctx: EngineContext, stale: Date): Promise<StorePauseRow[]> {\n const table = pauseTable(await ctx.ports.db());\n const rows = (await table.findMany({\n where: {\n state: \"OPEN\",\n wanted: \"OPEN\",\n requestedAt: { lt: stale },\n OR: [{ attemptKey: { not: null } }, { externalId: { not: null } }, { sentUntil: { not: null } }, { retiredExternalIds: { not: null } }],\n },\n })) as StorePauseRow[];\n const reopened: StorePauseRow[] = [];\n for (const row of rows) {\n const moved = await table.updateMany({ where: { id: row.id, state: \"OPEN\", wanted: \"OPEN\" }, data: { state: \"RESUMING\" } });\n if (moved.count > 0) reopened.push(row);\n }\n return reopened;\n}\n\n/** One sweep pass. A host whose database has no pause model sweeps nothing. */\nexport async function sweepAvailability(ctx: EngineContext, now: Date): Promise<AvailabilitySweepResult> {\n const db = await ctx.ports.db();\n if (!hasPauseTable(db)) return { expired: 0, requeued: 0, givenUp: 0 };\n const table = pauseTable(db);\n const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);\n const cutoff = new Date(now.getTime() - OUTBOUND_GIVE_UP_MS);\n\n const expired = await expire(ctx, now);\n const givenUp = await giveUp(ctx, cutoff, now);\n const waiting = (await table.findMany({\n where: { state: { in: [\"PAUSING\", \"RESUMING\"] }, requestedAt: { lt: stale, gte: cutoff } },\n })) as StorePauseRow[];\n const retired = (await table.findMany({ where: { state: \"PAUSED\", retiredExternalIds: { not: null } } })) as StorePauseRow[];\n const failedResumes = await retryFailedResumes(ctx, stale, cutoff);\n const orphans = await reopenOrphans(ctx, stale);\n const requeued = await requeue(ctx, [...waiting, ...retired, ...failedResumes, ...orphans], now);\n if (givenUp > 0) ctx.ports.logger.error(`marketplace.availability-sweep: gave up on ${givenUp} store pause ask(s).`);\n return { expired, requeued, givenUp };\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 { CANCELLED_BEFORE_INGEST_REASON, cancelledBeforeIngest, 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 // A CANCELLED that found nothing to cancel left its marker (an earlier\n // NEW_ORDER FAILED, so no acceptance existed). The retry sweep re-runs that\n // row: ingesting it now would send a cancelled order to the kitchen.\n if (await cancelledBeforeIngest(ctx, { clientId, provider: order.provider, externalOrderId: order.externalOrderId })) {\n await settleInboxEvent(ctx, inboxId, \"IGNORED\", CANCELLED_BEFORE_INGEST_REASON);\n return { kind: \"ignored\", reason: CANCELLED_BEFORE_INGEST_REASON };\n }\n const result = await ingestMarketplaceOrder(ctx, { clientId, order, settings, now });\n // A CANCELLED that read the acceptances while this ingest's transaction was\n // still open found none and left its marker: honour it now, through the\n // ordinary cancel path (the order is cancelled; no confirm is owed).\n const ref = { clientId, provider: order.provider, externalOrderId: order.externalOrderId };\n if (await cancelledBeforeIngest(ctx, ref)) await cancelAcceptance(ctx, ref);\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, UNREACHABLE 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 { readMarketplaceCatalogue } from \"./catalogue-read\";\nimport type { CatalogueReadResult } from \"./catalogue-read-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 {\n availabilityState,\n pauseStore,\n resumeStore,\n type PauseStoreInput,\n type PauseStoreResult,\n type ResumeOutcome,\n type StoreAvailabilityView,\n} from \"./pause\";\nimport { runAvailability, type AvailabilityOutcome } from \"./pause-job\";\nimport type { AvailabilityJobPayload } from \"./pause-store\";\nimport { sweepAvailability, type AvailabilitySweepResult } from \"./pause-sweep\";\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 /**\n * Read the menu the store keeps on a marketplace, through its own\n * connection (FUT-951): the snapshot, a final refusal, or a `retry` (429,\n * 5xx, a timeout). Calls the marketplace at once; nothing is queued.\n */\n readCatalogue(input: { clientId: string; provider: MarketplaceProvider; now?: Date }): Promise<CatalogueReadResult>;\n /** Run one queued publish or withdraw (the `marketplace.catalogue` job's body). */\n runCatalogue(payload: CatalogueJobPayload, attempt: OutboundAttempt): Promise<CatalogueOutcome>;\n\n /**\n * The kitchen paused (or renewed its pause): close the store until `until`\n * on every live connection whose marketplace can be paused (FUT-4851).\n * Idempotent: the `until` already standing does nothing; any other, an\n * earlier one included, renews the closure.\n */\n pauseStore(input: PauseStoreInput): Promise<PauseStoreResult>;\n /** The kitchen's pause is over: delete every closure the engine created, and nothing else. */\n resumeStore(input: {\n clientId: string;\n now?: Date;\n }): Promise<{ marketplaces: { provider: MarketplaceProvider; outcome: ResumeOutcome }[] }>;\n /** Where the store's pause stands on each marketplace, for the screen. */\n availabilityState(clientId: string): Promise<StoreAvailabilityView[]>;\n /** Bring one marketplace in line with the last ask (the `marketplace.availability` job's body). */\n runAvailability(payload: AvailabilityJobPayload, attempt: OutboundAttempt): Promise<AvailabilityOutcome>;\n /** Expire, re-queue and give up on store pauses (the `marketplace.availability-sweep` job's body). */\n sweepAvailability(now?: Date): Promise<AvailabilitySweepResult>;\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 readCatalogue: (input) => readMarketplaceCatalogue(ctx, input),\n\n pauseStore: (input) => pauseStore(ctx, input),\n resumeStore: (input) => resumeStore(ctx, input),\n availabilityState: (clientId) => availabilityState(ctx, clientId),\n runAvailability: (payload, attempt) => runAvailability(ctx, payload, attempt),\n sweepAvailability: (now) => sweepAvailability(ctx, now ?? ports.clock.now()),\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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,IACZ,aAAa,wBAAC,UAAU,YAAY,KAAK,KAAK,GAAjC;AAAA,IACb,mBAAmB,wBAAC,aAAa,kBAAkB,KAAK,QAAQ,GAA7C;AAAA,IACnB,iBAAiB,wBAAC,SAAS,YAAY,gBAAgB,KAAK,SAAS,OAAO,GAA3D;AAAA,IACjB,mBAAmB,wBAAC,QAAQ,kBAAkB,KAAK,OAAO,MAAM,MAAM,IAAI,CAAC,GAAxD;AAAA,EACrB;AACF;AArEgB;","names":["refused","duplicates","viewOf"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/bulk.ts","../src/core/decisions.ts","../src/core/catalogue.ts","../src/core/catalogue-read.ts","../src/core/status-inform.ts","../src/core/pause.ts","../src/core/pause-sweep.ts","../src/core/lifecycle.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\", \"followStatus\", \"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 // (REFUSED: its own limit): the order stays, and a person cancels it in\n // 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 // The document needs only the merchant id: no credentials are opened to serve it.\n const externalMerchantId = await connectionMerchantId(ctx, input.clientId, input.provider);\n if (externalMerchantId === null) 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, entries, options: input.options });\n return { kind: \"document\", document };\n}\n","import type { CatalogueReadResult } from \"./catalogue-read-port\";\nimport { connectionMerchantId, readOutboundConnection } from \"./integration\";\nimport type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * Reading the menu a store keeps on a marketplace, as a host calls it\n * (FUT-951): through the store's OWN connection (its merchant id and its\n * sealed credentials), with the adapter's `catalogueReader`. Nothing is\n * stamped or queued: the read is a question the host asks while the store\n * waits, and it answers the snapshot or why there is none.\n */\nexport async function readMarketplaceCatalogue(\n ctx: EngineContext,\n input: { clientId: string; provider: MarketplaceProvider; now?: Date },\n): Promise<CatalogueReadResult> {\n const reader = ctx.registry.get(input.provider)?.catalogueReader;\n if (!reader) return engineRefusal(\"UNSUPPORTED\");\n const merchantId = await connectionMerchantId(ctx, input.clientId, input.provider);\n if (merchantId === null) return engineRefusal(\"NOT_CONNECTED\");\n let connection: Awaited<ReturnType<typeof readOutboundConnection>>;\n try {\n connection = await readOutboundConnection(ctx, input.clientId, input.provider);\n } catch (error) {\n ctx.ports.logger.error(\n `marketplace.catalogue-read: ${input.provider} credentials of ${input.clientId} do not open: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n return engineRefusal(\"CREDENTIALS\");\n }\n if (!connection) return engineRefusal(\"CREDENTIALS\");\n try {\n return await reader.read({\n ...connection,\n http: ctx.ports.http,\n tokens: ctx.tokens,\n now: input.now ?? ctx.ports.clock.now(),\n externalMerchantId: merchantId,\n });\n } catch (error) {\n // The port says an adapter never throws; one that does is asked again later, not crashed on.\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\nconst engineRefusal = (code: \"UNSUPPORTED\" | \"NOT_CONNECTED\" | \"CREDENTIALS\"): CatalogueReadResult => ({\n kind: \"refused\",\n code,\n status: null,\n message: null,\n});\n","import type { StatusStep } from \"./adapter\";\nimport { MARKETPLACE_OUTBOUND_JOB, statusDedupeKey } from \"./outbound-queue\";\nimport type { EngineContext } from \"./ports\";\n\n/** What the host says when an order reaches a step (FUT-4653). */\nexport interface InformStatusInput {\n clientId: string;\n /** The host's order id. */\n orderId: string;\n step: StatusStep;\n /**\n * The instant of the move (the card's own timestamp), which makes the job's\n * key: a re-dispatch after an undo is another instant, and a queue keeps a\n * finished job's id and would swallow the same key.\n */\n at: Date;\n /** OPTIONAL. Run the job this much later: the board's undo window for a dispatch. */\n delayMs?: number;\n}\n\n/**\n * One enqueue and nothing else: no statement, no call to a marketplace, no\n * provider lookup (the host knows the order is a marketplace's, not whose).\n * The job asks the adapter whether it takes the step. A refused or throwing\n * queue is logged and answers false; nothing owed is recorded, so nothing is\n * re-queued (no row exists before the job, and writing one in the host's tap\n * would cost a statement on every move).\n */\nexport async function informStatus(ctx: EngineContext, input: InformStatusInput): Promise<boolean> {\n const payload = { clientId: input.clientId, orderId: input.orderId, action: \"status\" as const, step: input.step, claimKey: String(input.at.getTime()) };\n const options = {\n dedupeKey: statusDedupeKey(input.step, input.orderId, input.at),\n ...(input.delayMs === undefined ? {} : { delayMs: input.delayMs }),\n };\n try {\n const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, options);\n if (!outcome.enqueued) {\n ctx.ports.logger.warn(\n `${MARKETPLACE_OUTBOUND_JOB}: status ${input.step} for order ${input.orderId} was not queued` +\n (outcome.reason ? ` (${outcome.reason})` : \"\"),\n );\n }\n return outcome.enqueued;\n } catch (error) {\n ctx.ports.logger.warn(\n `${MARKETPLACE_OUTBOUND_JOB}: status ${input.step} for order ${input.orderId} was not queued: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n return false;\n }\n}\n","import type { EngineContext } from \"./ports\";\nimport {\n availabilityDedupeKey,\n enqueueAvailability,\n holdsSomething,\n pauseTable,\n readPause,\n type StorePauseFailureCode,\n type StorePauseRow,\n type StorePauseState,\n type StorePauseWanted,\n} from \"./pause-store\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * The store pause, as the host calls it (FUT-4851): `pauseStore` when the\n * kitchen pauses and on every renewal, `resumeStore` the moment the pause is\n * over, `availabilityState` for the screen. The host owns the debounce; these\n * calls only record the ask and queue `marketplace.availability`, whose job\n * makes the calls (`./pause-job.ts`). No path that answers a request reaches\n * a marketplace.\n */\n\n/** What `pauseStore` did on one marketplace. */\nexport type PauseOutcome =\n /** The ask was recorded and the job queued. */\n | \"queued\"\n /** A pause with exactly this end already stands or is on its way. */\n | \"unchanged\"\n /** The marketplace's adapter cannot pause a store: the host says so. */\n | \"unsupported\"\n /** The connection has no credentials or no merchant id. */\n | \"not-connected\";\n\n/** What `resumeStore` did on one marketplace. */\nexport type ResumeOutcome =\n /** Something of ours stands on the marketplace: the job deletes it. */\n | \"queued\"\n /** Nothing of ours stands there: the record is OPEN, and nobody is called. */\n | \"open\"\n /** A resume is already on its way. */\n | \"unchanged\";\n\nexport interface PauseStoreInput {\n clientId: string;\n /** The kitchen's estimated reopening time: the end every marketplace is given. */\n until: Date;\n /** The host's words for the closure (its copy, in the store's language). */\n reason: string;\n /** The store's IANA time zone. */\n timeZone: string;\n now?: Date;\n}\n\nexport type PauseStoreResult =\n | { kind: \"invalid\"; code: \"UNTIL_NOT_FUTURE\" | \"TIME_ZONE_INVALID\" }\n | { kind: \"ok\"; marketplaces: { provider: MarketplaceProvider; outcome: PauseOutcome }[] };\n\n/** One marketplace's pause as the screen shows it. */\nexport interface StoreAvailabilityView {\n provider: MarketplaceProvider;\n /** The adapter can pause a store at all. */\n supported: boolean;\n /** `interruption` (an id and an end) or `switch` (on/off); null when unsupported. */\n kind: \"interruption\" | \"switch\" | null;\n /** The connection has credentials and a merchant id. */\n connected: boolean;\n state: StorePauseState;\n wanted: StorePauseWanted;\n /** The end the host asked for. */\n until: Date | null;\n /** The end the marketplace was given and confirmed. */\n sentUntil: Date | null;\n failureCode: StorePauseFailureCode | null;\n /** The marketplace's own words, verbatim and cut; never copy to show as is. */\n failureDetail: string | null;\n pausedAt: Date | null;\n resumedAt: Date | null;\n updatedAt: Date | null;\n}\n\ninterface ConnectionRow {\n provider: string;\n externalMerchantId: string | null;\n credentials: string;\n}\n\n/** The store's live connections (enabled, not archived), with whether each can be called. */\nasync function liveConnections(ctx: EngineContext, clientId: string): Promise<ConnectionRow[]> {\n const db = await ctx.ports.db();\n return (await db.marketplaceIntegration.findMany({\n where: { clientId, enabled: true, archivedAt: null },\n select: { provider: true, externalMerchantId: true, credentials: true },\n orderBy: { provider: \"asc\" },\n })) as ConnectionRow[];\n}\n\nconst isConnected = (row: ConnectionRow): boolean => row.credentials !== \"\" && Boolean(row.externalMerchantId);\n\n/** Whether an IANA zone name is one this runtime knows. */\nfunction validTimeZone(timeZone: string): boolean {\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone });\n return timeZone !== \"\";\n } catch {\n return false;\n }\n}\n\n/**\n * Whether a pause with exactly this end already stands, or is on its way. An\n * earlier end is asked like a later one: the store is never closed on a\n * marketplace longer than the kitchen's own pause.\n */\nfunction alreadyAsked(row: StorePauseRow | null, until: Date): boolean {\n if (!row || row.wanted !== \"PAUSED\") return false;\n if (row.state !== \"PAUSING\" && row.state !== \"PAUSED\") return false;\n return row.until !== null && row.until.getTime() === until.getTime();\n}\n\n/** Record one marketplace's pause and queue its job, unless it already stands. */\nasync function askPause(ctx: EngineContext, input: Required<PauseStoreInput>, provider: string): Promise<PauseOutcome> {\n const existing = await readPause(ctx, input.clientId, provider);\n if (alreadyAsked(existing, input.until)) return \"unchanged\";\n const table = pauseTable(await ctx.ports.db());\n const data = {\n wanted: \"PAUSED\",\n state: \"PAUSING\",\n until: input.until,\n reason: input.reason,\n timeZone: input.timeZone,\n requestedAt: input.now,\n // No key is minted here: the job writes one just before its call, so a\n // resume that lands first knows nothing of ours can stand there. A key\n // still in doubt stays on the row (its create may have landed).\n failureCode: null,\n failureDetail: null,\n failedAt: null,\n };\n await table.upsert({\n where: { clientId_provider: { clientId: input.clientId, provider } },\n create: { clientId: input.clientId, provider, ...data },\n update: data,\n });\n const payload = { clientId: input.clientId, provider };\n await enqueueAvailability(ctx, payload, availabilityDedupeKey(payload, input.now));\n return \"queued\";\n}\n\n/**\n * Pause the store on every live connection whose marketplace can be paused.\n * Idempotent: a pause already standing (or on its way) with exactly this end\n * does nothing; any other end renews it, an earlier one included. Called again\n * on every renewal of the kitchen's pause.\n */\nexport async function pauseStore(ctx: EngineContext, input: PauseStoreInput): Promise<PauseStoreResult> {\n const now = input.now ?? ctx.ports.clock.now();\n if (input.until.getTime() <= now.getTime()) return { kind: \"invalid\", code: \"UNTIL_NOT_FUTURE\" };\n if (!validTimeZone(input.timeZone)) return { kind: \"invalid\", code: \"TIME_ZONE_INVALID\" };\n pauseTable(await ctx.ports.db());\n const full = { ...input, now };\n const marketplaces: { provider: MarketplaceProvider; outcome: PauseOutcome }[] = [];\n for (const connection of await liveConnections(ctx, input.clientId)) {\n const adapter = ctx.registry.get(connection.provider);\n let outcome: PauseOutcome;\n if (!adapter?.availability) outcome = \"unsupported\";\n else if (!isConnected(connection)) outcome = \"not-connected\";\n else outcome = await askPause(ctx, full, connection.provider);\n marketplaces.push({ provider: connection.provider, outcome });\n }\n if (marketplaces.some((entry) => entry.outcome === \"queued\")) ctx.ports.publishChanged(input.clientId);\n return { kind: \"ok\", marketplaces };\n}\n\n/**\n * Rewrite one record's ask to OPEN; queue the job when something of ours\n * stands there OR may be on its way: a PAUSING record may have a call in\n * flight whose key the job wrote after this read. The write is predicated on\n * the key read, so a claim that lands in between makes this re-read.\n */\nasync function askResume(ctx: EngineContext, read: StorePauseRow, now: Date): Promise<ResumeOutcome> {\n let row: StorePauseRow | null = read;\n for (let tries = 0; row && tries < 3; tries += 1) {\n if (resumeAsked(row)) return \"unchanged\";\n const outcome = await writeResume(ctx, row, now);\n if (outcome !== null) return outcome;\n row = await readPause(ctx, read.clientId, read.provider);\n }\n return row ? forceResume(ctx, row, now) : \"unchanged\";\n}\n\n/**\n * Every predicated write missed (the row kept moving): the resume is never\n * lost. RESUMING with no predicate, and the job queued: it re-reads the row\n * and deletes whatever of ours stands, or finds nothing and settles OPEN.\n */\nasync function forceResume(ctx: EngineContext, row: StorePauseRow, now: Date): Promise<ResumeOutcome> {\n const table = pauseTable(await ctx.ports.db());\n await table.updateMany({\n where: { id: row.id },\n data: { wanted: \"OPEN\", state: \"RESUMING\", requestedAt: now, failureCode: null, failureDetail: null, failedAt: null },\n });\n const payload = { clientId: row.clientId, provider: row.provider };\n await enqueueAvailability(ctx, payload, availabilityDedupeKey(payload, now));\n return \"queued\";\n}\n\n/** Whether a resume already stands: on its way, or OPEN with nothing of ours left. */\nfunction resumeAsked(row: StorePauseRow): boolean {\n if (row.wanted !== \"OPEN\") return false;\n return row.state === \"RESUMING\" || (row.state === \"OPEN\" && !holdsSomething(row));\n}\n\n/** The resume's write, predicated on the key read; null when the row moved under it. */\nasync function writeResume(ctx: EngineContext, row: StorePauseRow, now: Date): Promise<ResumeOutcome | null> {\n const held = holdsSomething(row) || row.state === \"PAUSING\";\n const table = pauseTable(await ctx.ports.db());\n const moved = await table.updateMany({\n where: { id: row.id, attemptKey: row.attemptKey },\n data: {\n wanted: \"OPEN\",\n state: held ? \"RESUMING\" : \"OPEN\",\n requestedAt: now,\n failureCode: null,\n failureDetail: null,\n failedAt: null,\n ...(held ? {} : { resumedAt: now }),\n },\n });\n if (moved.count === 0) return null;\n if (!held) return \"open\";\n const payload = { clientId: row.clientId, provider: row.provider };\n await enqueueAvailability(ctx, payload, availabilityDedupeKey(payload, now));\n return \"queued\";\n}\n\n/**\n * The kitchen's pause is over: open the store again wherever the engine\n * closed it. Only what the engine created is deleted; a marketplace where\n * nothing of ours stands is not called at all. Every record is answered,\n * a connection disabled since the pause included.\n */\nexport async function resumeStore(\n ctx: EngineContext,\n input: { clientId: string; now?: Date },\n): Promise<{ marketplaces: { provider: MarketplaceProvider; outcome: ResumeOutcome }[] }> {\n const now = input.now ?? ctx.ports.clock.now();\n const table = pauseTable(await ctx.ports.db());\n const rows = (await table.findMany({\n where: { clientId: input.clientId },\n orderBy: { provider: \"asc\" },\n })) as StorePauseRow[];\n const marketplaces: { provider: MarketplaceProvider; outcome: ResumeOutcome }[] = [];\n for (const row of rows) marketplaces.push({ provider: row.provider, outcome: await askResume(ctx, row, now) });\n if (marketplaces.some((entry) => entry.outcome !== \"unchanged\")) ctx.ports.publishChanged(input.clientId);\n return { marketplaces };\n}\n\n/** What a marketplace with no record reads as: OPEN, never asked. */\nconst NEVER_ASKED: Omit<StoreAvailabilityView, \"provider\" | \"supported\" | \"kind\" | \"connected\"> = {\n state: \"OPEN\",\n wanted: \"OPEN\",\n until: null,\n sentUntil: null,\n failureCode: null,\n failureDetail: null,\n pausedAt: null,\n resumedAt: null,\n updatedAt: null,\n};\n\nfunction viewOf(ctx: EngineContext, provider: string, connection: ConnectionRow | undefined, row: StorePauseRow | undefined): StoreAvailabilityView {\n const availability = ctx.registry.get(provider)?.availability;\n const recorded = row\n ? {\n state: row.state,\n wanted: row.wanted,\n until: row.until,\n sentUntil: row.sentUntil,\n failureCode: row.failureCode,\n failureDetail: row.failureDetail,\n pausedAt: row.pausedAt,\n resumedAt: row.resumedAt,\n updatedAt: row.updatedAt,\n }\n : NEVER_ASKED;\n return {\n provider,\n supported: availability !== undefined,\n kind: availability?.kind ?? null,\n connected: connection !== undefined && isConnected(connection),\n ...recorded,\n };\n}\n\n/**\n * Where the store's pause stands on each marketplace: every live connection,\n * plus any record of a connection since disabled that still holds something.\n * A host on a database without the pause model reads every marketplace OPEN.\n */\nexport async function availabilityState(ctx: EngineContext, clientId: string): Promise<StoreAvailabilityView[]> {\n const db = await ctx.ports.db();\n const connections = await liveConnections(ctx, clientId);\n const rows = db.marketplaceStorePause\n ? ((await db.marketplaceStorePause.findMany({ where: { clientId } })) as StorePauseRow[])\n : [];\n const byProvider = new Map(rows.map((row) => [row.provider, row]));\n const views = connections.map((connection) =>\n viewOf(ctx, connection.provider, connection, byProvider.get(connection.provider)),\n );\n const live = new Set(connections.map((connection) => connection.provider));\n for (const row of rows) {\n if (!live.has(row.provider) && holdsSomething(row)) views.push(viewOf(ctx, row.provider, undefined, row));\n }\n return views;\n}\n","import { OUTBOUND_GIVE_UP_MS, OUTBOUND_STALE_MS } from \"./outbound-sweep\";\nimport {\n availabilityDedupeKey,\n enqueueAvailability,\n hasPauseTable,\n holdsSomething,\n pauseTable,\n type StorePauseRow,\n} from \"./pause-store\";\nimport type { EngineContext } from \"./ports\";\n\n/**\n * The availability sweep (`marketplace.availability-sweep`, every five\n * minutes): nothing the engine owes a marketplace for a store's pause is lost,\n * and no store stays closed past the kitchen's pause (FUT-4851).\n *\n * - **Expired**: a pause whose `until` has passed without a renewal is over.\n * The host stopped renewing (it died, or forgot to resume), so the engine\n * resumes on its own: the owner's \"never closed on a marketplace longer than\n * the kitchen's own pause\". An interruption has already ended on the\n * marketplace (its delete answers \"gone\", which is done); a switch would\n * otherwise stay off for good.\n * - **Stale**: an ask still PAUSING or RESUMING after the job's own retry span\n * (a refused enqueue, a dead process) is re-queued; past\n * {@link OUTBOUND_GIVE_UP_MS} it is FAILED as unanswered.\n * - **A failed resume that still holds something** is retried each pass until\n * the give-up: a store must not stay closed because one delete failed.\n * - **A replaced closure** an extend could not delete is retried.\n * - **An OPEN record that still holds something** (a pause call whose answer\n * was lost after a resume landed) goes back to RESUMING and is re-queued.\n *\n * Re-queued under a key of its own per pass, as the outbound sweep does. The\n * job is idempotent by the row and leased, so a duplicate run calls nobody\n * twice.\n */\n\n/** What one pass did. */\nexport interface AvailabilitySweepResult {\n /** Pauses past their `until`, turned into resumes. */\n expired: number;\n /** Asks re-queued. */\n requeued: number;\n /** Asks failed as unanswered past the give-up. */\n givenUp: number;\n}\n\nconst sweepKey = (row: StorePauseRow, now: Date): string =>\n availabilityDedupeKey({ clientId: row.clientId, provider: row.provider }, row.requestedAt, `:sweep:${now.getTime()}`);\n\nasync function requeue(ctx: EngineContext, rows: readonly StorePauseRow[], now: Date): Promise<number> {\n let queued = 0;\n for (const row of rows) {\n if (await enqueueAvailability(ctx, { clientId: row.clientId, provider: row.provider }, sweepKey(row, now))) queued += 1;\n }\n return queued;\n}\n\n/** Pauses past their end: resume them, predicated on nobody having renewed meanwhile. */\nasync function expire(ctx: EngineContext, now: Date): Promise<number> {\n const table = pauseTable(await ctx.ports.db());\n const rows = (await table.findMany({\n where: { wanted: \"PAUSED\", state: { in: [\"PAUSING\", \"PAUSED\", \"FAILED\"] }, until: { lt: now } },\n })) as StorePauseRow[];\n let expired = 0;\n for (const row of rows) {\n const held = holdsSomething(row);\n const moved = await table.updateMany({\n where: { id: row.id, wanted: \"PAUSED\", until: row.until },\n data: { wanted: \"OPEN\", state: held ? \"RESUMING\" : \"OPEN\", requestedAt: now, failureCode: null, failureDetail: null, failedAt: null },\n });\n if (moved.count === 0) continue;\n expired += 1;\n ctx.ports.publishChanged(row.clientId);\n if (held) await requeue(ctx, [{ ...row, requestedAt: now }], now);\n }\n return expired;\n}\n\n/** Asks waiting past the give-up: FAILED as unanswered. */\nasync function giveUp(ctx: EngineContext, cutoff: Date, now: Date): Promise<number> {\n const table = pauseTable(await ctx.ports.db());\n let failed = 0;\n for (const [state, code] of [[\"PAUSING\", \"PAUSE_UNANSWERED\"], [\"RESUMING\", \"RESUME_UNANSWERED\"]] as const) {\n const moved = await table.updateMany({\n where: { state, requestedAt: { lt: cutoff } },\n data: { state: \"FAILED\", failureCode: code, failureDetail: null, failedAt: now },\n });\n failed += moved.count;\n }\n return failed;\n}\n\n/** A failed resume that still holds something, failed for a while and asked inside the give-up: back to RESUMING. */\nasync function retryFailedResumes(ctx: EngineContext, stale: Date, cutoff: Date): Promise<StorePauseRow[]> {\n const table = pauseTable(await ctx.ports.db());\n const rows = (await table.findMany({\n where: { state: \"FAILED\", wanted: \"OPEN\", failedAt: { lt: stale }, requestedAt: { gte: cutoff } },\n })) as StorePauseRow[];\n const retried: StorePauseRow[] = [];\n for (const row of rows.filter(holdsSomething)) {\n const moved = await table.updateMany({ where: { id: row.id, state: \"FAILED\", wanted: \"OPEN\" }, data: { state: \"RESUMING\" } });\n if (moved.count > 0) retried.push(row);\n }\n return retried;\n}\n\n/**\n * An OPEN record that still holds something (a call whose answer was lost\n * after a resume landed): back to RESUMING, so the job deletes it.\n */\nasync function reopenOrphans(ctx: EngineContext, stale: Date): Promise<StorePauseRow[]> {\n const table = pauseTable(await ctx.ports.db());\n const rows = (await table.findMany({\n where: {\n state: \"OPEN\",\n wanted: \"OPEN\",\n requestedAt: { lt: stale },\n OR: [{ attemptKey: { not: null } }, { externalId: { not: null } }, { sentUntil: { not: null } }, { retiredExternalIds: { not: null } }],\n },\n })) as StorePauseRow[];\n const reopened: StorePauseRow[] = [];\n for (const row of rows) {\n const moved = await table.updateMany({ where: { id: row.id, state: \"OPEN\", wanted: \"OPEN\" }, data: { state: \"RESUMING\" } });\n if (moved.count > 0) reopened.push(row);\n }\n return reopened;\n}\n\n/** One sweep pass. A host whose database has no pause model sweeps nothing. */\nexport async function sweepAvailability(ctx: EngineContext, now: Date): Promise<AvailabilitySweepResult> {\n const db = await ctx.ports.db();\n if (!hasPauseTable(db)) return { expired: 0, requeued: 0, givenUp: 0 };\n const table = pauseTable(db);\n const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);\n const cutoff = new Date(now.getTime() - OUTBOUND_GIVE_UP_MS);\n\n const expired = await expire(ctx, now);\n const givenUp = await giveUp(ctx, cutoff, now);\n const waiting = (await table.findMany({\n where: { state: { in: [\"PAUSING\", \"RESUMING\"] }, requestedAt: { lt: stale, gte: cutoff } },\n })) as StorePauseRow[];\n const retired = (await table.findMany({ where: { state: \"PAUSED\", retiredExternalIds: { not: null } } })) as StorePauseRow[];\n const failedResumes = await retryFailedResumes(ctx, stale, cutoff);\n const orphans = await reopenOrphans(ctx, stale);\n const requeued = await requeue(ctx, [...waiting, ...retired, ...failedResumes, ...orphans], now);\n if (givenUp > 0) ctx.ports.logger.error(`marketplace.availability-sweep: gave up on ${givenUp} store pause ask(s).`);\n return { expired, requeued, givenUp };\n}\n","import { deferInboxEvent, settleInboxEvent } from \"./inbox\";\nimport type { IngestSettings } from \"./ingest\";\nimport type { DeliveryOutcome } from \"./pipeline\";\nimport type { EngineContext } from \"./ports\";\nimport { readStatusRows, noteMarketplaceStep, statusTable } from \"./status-store\";\nimport type { MarketplaceDeliveredBy, MarketplaceLifecycle, NormalizedEvent } from \"./types\";\n\n/**\n * Inbound lifecycle (FUT-4653): the marketplace says the order was dispatched\n * or concluded, and the order follows, FORWARD only.\n *\n * What the engine owns, in order, each stopping the event with a reason the\n * inbox row keeps:\n *\n * 1. an order the engine does not hold yet is DEFERRED (PENDING, one attempt\n * counted), so the reconcile pass applies the event after the order's own\n * event ingests, and retires it after `maxInboxAttempts` like any row;\n * 2. an order that is not ACCEPTED is never moved: the aceite is where the\n * stock is judged, and an ended order is not revived;\n * 3. a cancellation request standing (PENDING or REQUESTED) is the store's\n * last word and nothing here contradicts it;\n * 4. an event that answers a step WE informed (a STORE row for DISPATCHED, or\n * for HANDED_OVER when the event is CONCLUDED) is an echo: the failure case\n * of forward-only alone is the store's undo, where the echo would\n * dispatch a card again with no courier.\n *\n * What the host owns (`onLifecycle`): whether the order can move, to where,\n * and how. Whatever it answers, the step is NOTED as the marketplace's, so our\n * own job never informs it back and nothing is informed after a CONCLUDED.\n *\n * A host that binds no `onLifecycle`, a connection with the switch OFF (or\n * settings built by hand without it) and a host without the status model get\n * `null`: the caller's old answer, \"no order body\", byte for byte.\n */\n\n/** The step of the table an event's echo is looked for under. */\nconst ECHO_OF: Record<MarketplaceLifecycle, \"DISPATCHED\" | \"HANDED_OVER\"> = {\n DISPATCHED: \"DISPATCHED\",\n CONCLUDED: \"HANDED_OVER\",\n};\n\ninterface HeldAcceptance {\n orderId: string;\n status: string;\n deliveredBy: string | null;\n cancellationStatus: string | null;\n}\n\n/** Settle the row IGNORED with a reason, and answer it. */\nasync function ignored(ctx: EngineContext, inboxId: string, reason: string): Promise<DeliveryOutcome> {\n await settleInboxEvent(ctx, inboxId, \"IGNORED\", reason);\n return { kind: \"ignored\", reason };\n}\n\n/** Why a held order is not moved by the marketplace's word, or null when it may be. */\nfunction refusal(held: HeldAcceptance): string | null {\n if (held.status !== \"ACCEPTED\") return `the order is ${held.status}, not ACCEPTED`;\n // A request that FAILED left the order the store's own: only a standing one stops us.\n if (held.cancellationStatus === \"PENDING\" || held.cancellationStatus === \"REQUESTED\") {\n return `a cancellation request is ${held.cancellationStatus}`;\n }\n return null;\n}\n\nfunction deliveredByOf(held: HeldAcceptance): MarketplaceDeliveredBy | null {\n return held.deliveredBy === \"MERCHANT\" || held.deliveredBy === \"MARKETPLACE\" ? held.deliveredBy : null;\n}\n\n/** What `followLifecycle` needs once it is known the connection follows this event. */\ninterface Following {\n lifecycle: MarketplaceLifecycle;\n externalOrderId: string;\n hook: NonNullable<EngineContext[\"ports\"][\"order\"][\"onLifecycle\"]>;\n}\n\n/** Whether this ingestion follows this event at all: a lifecycle, the switch ON, a host hook. */\nfunction following(ctx: EngineContext, event: NormalizedEvent, settings: IngestSettings): Following | null {\n const hook = ctx.ports.order.onLifecycle;\n if (!event.lifecycle || !event.externalOrderId || !settings.followStatus || !hook) return null;\n return { lifecycle: event.lifecycle, externalOrderId: event.externalOrderId, hook };\n}\n\n/**\n * Apply one lifecycle event, or null when this ingestion does not follow it\n * (no lifecycle, switch OFF, no hook, no status model): the caller then does\n * what it did before FUT-4653.\n */\nexport async function followLifecycle(\n ctx: EngineContext,\n inboxId: string,\n clientId: string,\n event: NormalizedEvent,\n settings: IngestSettings,\n): Promise<DeliveryOutcome | null> {\n const follow = following(ctx, event, settings);\n if (!follow) return null;\n const { lifecycle, hook } = follow;\n const db = await ctx.ports.db();\n const table = statusTable(db);\n if (!table) return null;\n\n const held = (await db.marketplaceAcceptance.findFirst({\n where: { clientId, provider: event.provider, externalOrderId: follow.externalOrderId },\n select: { orderId: true, status: true, deliveredBy: true, cancellationStatus: true },\n })) as HeldAcceptance | null;\n if (!held) {\n const reason = \"lifecycle before its order\";\n await deferInboxEvent(ctx, inboxId, reason);\n return { kind: \"ignored\", reason };\n }\n const stopped = refusal(held);\n if (stopped) return ignored(ctx, inboxId, stopped);\n\n const echo = ECHO_OF[lifecycle];\n const ours = (await readStatusRows(table, held.orderId, [echo])).some((row) => row.source === \"STORE\");\n if (ours) return ignored(ctx, inboxId, `echo of our ${echo}`);\n\n // Two statements, not one: the echo was read above and the marketplace's word is noted below. A\n // genuine event judged \"no echo\" can lose the unique on its note to our own job claiming in\n // between, and that job then sends a step the marketplace already has. Harmless (at worst a 4xx,\n // FAILED and logged): the marketplace's state and ours already agree, and a stricter ordering\n // would put a write before the host's answer on every event.\n const answer = await hook.call(ctx.ports.order, clientId, held.orderId, event, { deliveredBy: deliveredByOf(held) });\n await noteMarketplaceStep(ctx, { clientId, orderId: held.orderId, provider: event.provider, step: lifecycle });\n if (answer === \"moved\") {\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n ctx.ports.publishChanged(clientId);\n return { kind: \"moved\", orderId: held.orderId, lifecycle };\n }\n const reason = answer === \"unchanged\" ? `already at or past ${lifecycle}` : answer.reason;\n if (answer !== \"unchanged\") ctx.ports.logger.warn(`marketplace.lifecycle: ${event.provider} order ${held.orderId}: ${reason}`);\n return ignored(ctx, inboxId, reason);\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 { CANCELLED_BEFORE_INGEST_REASON, cancelledBeforeIngest, markCancelledBeforeIngest } from \"./order-fetch-marks\";\nimport type { EngineContext } from \"./ports\";\nimport type { MarketplaceLifecycle, MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from \"./types\";\nimport { followLifecycle } from \"./lifecycle\";\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 /** A lifecycle event moved the order forward, through the host's `onLifecycle` (FUT-4653). */\n | { kind: \"moved\"; orderId: string; lifecycle: MarketplaceLifecycle }\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 // A lifecycle event (dispatched, concluded) of an order we hold: with the\n // connection's switch ON and a host that binds the hook, the order follows.\n // Anything else falls through to \"understood, nothing to do\", as before.\n const followed = await followLifecycle(ctx, inboxId, clientId, event, settings);\n if (followed) return followed;\n return ingestOrIgnore(ctx, inboxId, clientId, event, settings, now);\n}\n\n/** An event with no order body is understood and ignored; one that carries an order is ingested. */\nasync function ingestOrIgnore(\n ctx: EngineContext,\n inboxId: string,\n clientId: string,\n event: NormalizedEvent,\n settings: IngestSettings,\n now: Date | undefined,\n): Promise<DeliveryOutcome> {\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 // A CANCELLED that found nothing to cancel left its marker (an earlier\n // NEW_ORDER FAILED, so no acceptance existed). The retry sweep re-runs that\n // row: ingesting it now would send a cancelled order to the kitchen.\n if (await cancelledBeforeIngest(ctx, { clientId, provider: order.provider, externalOrderId: order.externalOrderId })) {\n await settleInboxEvent(ctx, inboxId, \"IGNORED\", CANCELLED_BEFORE_INGEST_REASON);\n return { kind: \"ignored\", reason: CANCELLED_BEFORE_INGEST_REASON };\n }\n const result = await ingestMarketplaceOrder(ctx, { clientId, order, settings, now });\n // A CANCELLED that read the acceptances while this ingest's transaction was\n // still open found none and left its marker: honour it now, through the\n // ordinary cancel path (the order is cancelled; no confirm is owed).\n const ref = { clientId, provider: order.provider, externalOrderId: order.externalOrderId };\n if (await cancelledBeforeIngest(ctx, ref)) await cancelAcceptance(ctx, ref);\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, followStatus: target.followStatus },\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, UNREACHABLE 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 { readMarketplaceCatalogue } from \"./catalogue-read\";\nimport type { CatalogueReadResult } from \"./catalogue-read-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 { informStatus, type InformStatusInput } from \"./status-inform\";\nimport {\n availabilityState,\n pauseStore,\n resumeStore,\n type PauseStoreInput,\n type PauseStoreResult,\n type ResumeOutcome,\n type StoreAvailabilityView,\n} from \"./pause\";\nimport { runAvailability, type AvailabilityOutcome } from \"./pause-job\";\nimport type { AvailabilityJobPayload } from \"./pause-store\";\nimport { sweepAvailability, type AvailabilitySweepResult } from \"./pause-sweep\";\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 /**\n * Tell the marketplace the order reached a step (FUT-4653): ONE enqueue of\n * the `marketplace.outbound` job, action `status`. Never throws, runs no\n * statement and calls nobody: the job decides everything else. True when the\n * queue took it.\n */\n informStatus(input: InformStatusInput): Promise<boolean>;\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 /**\n * Read the menu the store keeps on a marketplace, through its own\n * connection (FUT-951): the snapshot, a final refusal, or a `retry` (429,\n * 5xx, a timeout). Calls the marketplace at once; nothing is queued.\n */\n readCatalogue(input: { clientId: string; provider: MarketplaceProvider; now?: Date }): Promise<CatalogueReadResult>;\n /** Run one queued publish or withdraw (the `marketplace.catalogue` job's body). */\n runCatalogue(payload: CatalogueJobPayload, attempt: OutboundAttempt): Promise<CatalogueOutcome>;\n\n /**\n * The kitchen paused (or renewed its pause): close the store until `until`\n * on every live connection whose marketplace can be paused (FUT-4851).\n * Idempotent: the `until` already standing does nothing; any other, an\n * earlier one included, renews the closure.\n */\n pauseStore(input: PauseStoreInput): Promise<PauseStoreResult>;\n /** The kitchen's pause is over: delete every closure the engine created, and nothing else. */\n resumeStore(input: {\n clientId: string;\n now?: Date;\n }): Promise<{ marketplaces: { provider: MarketplaceProvider; outcome: ResumeOutcome }[] }>;\n /** Where the store's pause stands on each marketplace, for the screen. */\n availabilityState(clientId: string): Promise<StoreAvailabilityView[]>;\n /** Bring one marketplace in line with the last ask (the `marketplace.availability` job's body). */\n runAvailability(payload: AvailabilityJobPayload, attempt: OutboundAttempt): Promise<AvailabilityOutcome>;\n /** Expire, re-queue and give up on store pauses (the `marketplace.availability-sweep` job's body). */\n sweepAvailability(now?: Date): Promise<AvailabilitySweepResult>;\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 informStatus: (input) => informStatus(ctx, input),\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 readCatalogue: (input) => readMarketplaceCatalogue(ctx, input),\n\n pauseStore: (input) => pauseStore(ctx, input),\n resumeStore: (input) => resumeStore(ctx, input),\n availabilityState: (clientId) => availabilityState(ctx, clientId),\n runAvailability: (payload, attempt) => runAvailability(ctx, payload, attempt),\n sweepAvailability: (now) => sweepAvailability(ctx, now ?? ports.clock.now()),\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,gBAAgB,iBAAiB,aAAa;AAElI,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,M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