@12-apps/marketplace 1.0.0 → 1.2.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 +44 -9
- package/README.md +149 -4
- package/dist/99food/en-US.d.ts +19 -0
- package/dist/99food/en-US.js +23 -0
- package/dist/99food/en-US.js.map +1 -0
- package/dist/99food/index.d.ts +116 -0
- package/dist/99food/index.js +361 -0
- package/dist/99food/index.js.map +1 -0
- package/dist/99food/pt-BR.d.ts +23 -0
- package/dist/99food/pt-BR.js +23 -0
- package/dist/99food/pt-BR.js.map +1 -0
- package/dist/{adapter-CgCAYBSJ.d.ts → adapter-_iuSxvVD.d.ts} +41 -1
- package/dist/{chunk-OEKTWUQH.js → chunk-24RQZPSV.js} +1 -1
- package/dist/chunk-24RQZPSV.js.map +1 -0
- package/dist/chunk-BD7DS3XM.js +78 -0
- package/dist/chunk-BD7DS3XM.js.map +1 -0
- package/dist/{chunk-BEMTRJYM.js → chunk-CRYFYDQ2.js} +28 -4
- package/dist/{chunk-BEMTRJYM.js.map → chunk-CRYFYDQ2.js.map} +1 -1
- package/dist/chunk-D2X7TOR6.js +1240 -0
- package/dist/chunk-D2X7TOR6.js.map +1 -0
- package/dist/{engine-DDE0mnTu.d.ts → engine-D-a4mttc.d.ts} +117 -17
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +10 -12
- package/dist/ifood/index.js +19 -61
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +113 -497
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +3 -2
- package/dist/manifest/server.js +2 -2
- package/dist/rappi/en-US.d.ts +14 -0
- package/dist/rappi/en-US.js +18 -0
- package/dist/rappi/en-US.js.map +1 -0
- package/dist/rappi/index.d.ts +190 -0
- package/dist/rappi/index.js +353 -0
- package/dist/rappi/index.js.map +1 -0
- package/dist/rappi/pt-BR.d.ts +18 -0
- package/dist/rappi/pt-BR.js +18 -0
- package/dist/rappi/pt-BR.js.map +1 -0
- package/dist/server/index.d.ts +12 -5
- package/dist/server/index.js +4 -2
- package/package.json +26 -2
- package/prisma/marketplace.prisma +12 -1
- package/prisma/migrations/20261112120000_marketplace_cancellation_failure/migration.sql +21 -0
- package/src/99food/copy.ts +36 -0
- package/src/99food/en-US.ts +19 -0
- package/src/99food/index.ts +121 -0
- package/src/99food/normalize.ts +263 -0
- package/src/99food/outbound.ts +220 -0
- package/src/99food/pt-BR.ts +23 -0
- package/src/core/acceptance.ts +30 -14
- package/src/core/adapter.ts +23 -1
- package/src/core/cancellation-outcome.ts +92 -0
- package/src/core/cancellation.ts +46 -15
- package/src/core/decisions.ts +94 -19
- package/src/core/engine.ts +8 -0
- package/src/core/fetch-order.ts +253 -0
- package/src/core/inbox.ts +8 -2
- package/src/core/ingest.ts +10 -2
- package/src/core/integration.ts +30 -1
- package/src/core/order-fetch-marks.ts +63 -0
- package/src/core/outbound-sweep.ts +87 -8
- package/src/core/outbound.ts +103 -7
- package/src/core/payload-read.ts +101 -0
- package/src/core/pipeline.ts +64 -15
- package/src/core/ports.ts +32 -0
- package/src/core/state.ts +6 -1
- package/src/core/types.ts +14 -0
- package/src/ifood/index.ts +9 -0
- package/src/ifood/normalize.ts +15 -88
- package/src/index.ts +10 -1
- package/src/rappi/copy.ts +39 -0
- package/src/rappi/en-US.ts +14 -0
- package/src/rappi/index.ts +155 -0
- package/src/rappi/normalize.ts +314 -0
- package/src/rappi/outbound.ts +182 -0
- package/src/rappi/pt-BR.ts +18 -0
- package/src/server/index.ts +1 -0
- package/src/server/jobs.ts +38 -4
- package/dist/chunk-6OODIO3E.js +0 -395
- package/dist/chunk-6OODIO3E.js.map +0 -1
- package/dist/chunk-OEKTWUQH.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/acceptance.ts","../src/core/menu-links.ts","../src/core/bulk.ts","../src/core/cancellation.ts","../src/core/outbound-queue.ts","../src/core/decisions.ts","../src/core/outbound-sweep.ts","../src/core/inbox.ts","../src/core/ingest.ts","../src/core/pipeline.ts","../src/core/state.ts","../src/core/engine.ts"],"sourcesContent":["import type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * The acceptance clock — the store saying yes (or no) to an order.\n *\n * A first-class state rather than a notification, because a marketplace\n * CANCELS an order nobody acknowledged. This module is the only thing that\n * moves an order between the states it can be in:\n *\n * AWAITING ──accept──▶ ACCEPTED ──store cancel──▶ REJECTED\n * │ └──reject───▶ REJECTED\n * └──sweep───────▶ EXPIRED\n *\n * Every transition is guarded on the CURRENT state in the WHERE clause rather\n * than read-then-written, so the sweep and a person deciding in the same\n * second cannot both win. The decisions themselves are `./decisions.ts`;\n * this module holds the queue, the sweep and the marketplace's own cancel.\n *\n * Beside the clock sits the store's own CANCELLATION REQUEST, on the same row:\n *\n * null ──refuse/cancel──▶ PENDING ──job 2xx──▶ REQUESTED ──event──▶ CONFIRMED\n * │ └──job 4xx / last retry──▶ FAILED ──event──▶ CONFIRMED\n * └──event (the marketplace cancelled)──▶ CONFIRMED\n *\n * CONFIRMED is terminal; every write to the column is predicated on the\n * statuses it may come from, so an out-of-order event cannot undo it.\n */\n\n/** The states an acceptance can be in. The host renders them; they are not copy. */\nexport type AcceptanceStatus = \"AWAITING\" | \"ACCEPTED\" | \"REJECTED\" | \"EXPIRED\";\n\n/** Where the store's own cancellation request stands. */\nexport type CancellationStatus = \"PENDING\" | \"REQUESTED\" | \"CONFIRMED\" | \"FAILED\";\n\n/** An order waiting on the store, as the acceptance queue shows it. */\nexport interface PendingAcceptance {\n id: string;\n /** The HOST's order id — what every host-side surface keys off. */\n orderId: string;\n provider: MarketplaceProvider;\n externalOrderId: string;\n externalDisplayId: string | null;\n /** The deadline itself, so a client counts down against a real instant. */\n acknowledgeBy: Date | null;\n externalDueAt: Date | null;\n commissionCents: number | null;\n buyerName: string | null;\n totalCents: number;\n unmappedLines: number;\n createdAt: string | null;\n}\n\ninterface PendingRow {\n id: string;\n orderId: string;\n provider: string;\n externalOrderId: string;\n externalDisplayId: string | null;\n acknowledgeBy: Date | null;\n externalDueAt: Date | null;\n commissionCents: number | null;\n}\n\n/**\n * Orders still on the clock, soonest DEADLINE first — the one about to lapse\n * is the one that has to be at the top of the screen. The host's half of each\n * row arrives in ONE `summarize` call.\n */\nexport async function listPendingAcceptances(\n ctx: EngineContext,\n clientId: string,\n orderIds?: readonly string[],\n): Promise<PendingAcceptance[]> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceAcceptance.findMany({\n where: { clientId, status: \"AWAITING\", ...(orderIds ? { orderId: { in: [...orderIds] } } : {}) },\n orderBy: { acknowledgeBy: \"asc\" },\n select: {\n id: true,\n orderId: true,\n provider: true,\n externalOrderId: true,\n externalDisplayId: true,\n acknowledgeBy: true,\n externalDueAt: true,\n commissionCents: true,\n },\n })) as PendingRow[];\n if (rows.length === 0) return [];\n\n const summaries = await ctx.ports.order.summarize(\n clientId,\n rows.map((row) => row.orderId),\n );\n return rows.map((row) => {\n const summary = summaries.get(row.orderId);\n return {\n ...row,\n buyerName: summary?.buyerName ?? null,\n totalCents: summary?.totalCents ?? 0,\n unmappedLines: summary?.unmappedLines ?? 0,\n createdAt: summary?.createdAt ?? null,\n };\n });\n}\n\n/** What one sweep pass did. */\nexport interface ExpirySweepResult {\n expired: number;\n tenants: number;\n}\n\n/**\n * Expire every order whose deadline has passed.\n *\n * The marketplace has already cancelled these on its own side — that is what\n * the deadline MEANS — so this records what the engine now knows happened.\n * Idempotent by durable marker: `status` is in the predicate, and an ACCEPTED\n * row is never touched, so an order a person accepted is never expired.\n */\nexport async function expireLapsedAcceptances(\n ctx: EngineContext,\n now: Date,\n): Promise<ExpirySweepResult> {\n const db = await ctx.ports.db();\n const lapsed = (await db.marketplaceAcceptance.findMany({\n where: { status: \"AWAITING\", acknowledgeBy: { lt: now } },\n select: { id: true, clientId: true, orderId: true },\n })) as { id: string; clientId: string; orderId: string }[];\n if (lapsed.length === 0) return { expired: 0, tenants: 0 };\n\n const result = await db.marketplaceAcceptance.updateMany({\n where: { id: { in: lapsed.map((row) => row.id) }, status: \"AWAITING\" },\n data: { status: \"EXPIRED\", acknowledgedAt: now },\n });\n\n // The host's half must not be able to fail the sweep: one tenant's broken\n // cancellation cannot leave every other tenant's lapsed orders on the clock.\n for (const row of lapsed) {\n try {\n await ctx.ports.order.onRefused(row.clientId, row.orderId, \"EXPIRED\");\n } catch (error) {\n ctx.ports.logger.error(\n `marketplace.expire-acceptances: order ${row.orderId} expired but the host's refusal failed: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n }\n\n const tenants = new Set(lapsed.map((row) => row.clientId));\n for (const clientId of tenants) ctx.ports.publishChanged(clientId);\n return { expired: result.count, tenants: tenants.size };\n}\n\n/**\n * The marketplace cancelled an order it had already given us.\n *\n * Terminal on the acceptance side whatever state it was in. A cancellation\n * request the store made is answered: CONFIRMED, from PENDING, REQUESTED or\n * FAILED (a refusal followed by a cancellation is still a cancellation).\n * Returns false when no acceptance stands for this external order — a\n * cancellation can outrun the placement it refers to.\n */\nexport async function cancelAcceptance(\n ctx: EngineContext,\n input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string; now?: Date },\n): Promise<boolean> {\n const db = await ctx.ports.db();\n const row = (await db.marketplaceAcceptance.findFirst({\n where: {\n clientId: input.clientId,\n provider: input.provider,\n externalOrderId: input.externalOrderId,\n },\n select: { orderId: true },\n })) as { orderId: string } | null;\n if (!row) return false;\n\n // The two stamps commit together: a cancelled order never shows a request\n // still PENDING. The host's cancel runs after; if it throws, the inbox row\n // is FAILED and the retry sweep re-runs this, whose stamps are idempotent.\n await ctx.ports.transaction(async (tx) => {\n await tx.marketplaceAcceptance.updateMany({\n where: { orderId: row.orderId, status: { not: \"REJECTED\" } },\n data: { status: \"REJECTED\", acknowledgedAt: input.now ?? ctx.ports.clock.now() },\n });\n await tx.marketplaceAcceptance.updateMany({\n where: { orderId: row.orderId, cancellationStatus: { in: [\"PENDING\", \"REQUESTED\", \"FAILED\"] } },\n data: { cancellationStatus: \"CONFIRMED\" },\n });\n });\n await ctx.ports.order.onRefused(input.clientId, row.orderId, \"CANCELLED\");\n ctx.ports.publishChanged(input.clientId);\n return true;\n}\n\n","import type { EngineContext, MarketplaceDb } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * External SKU ↔ catalog mapping .\n *\n * The rule the whole module is built around: an unmapped SKU is a ROW, not an\n * absence. Every SKU an order has ever carried has a link row, mapped or not,\n * so the attention list is a query rather than a reconciliation, and mapping\n * one is an update on something the store can already see. Manual mapping\n * upkeep has to be visibly cheap or it does not happen — and a store that stops\n * doing it is a store quietly selling food it cannot make.\n *\n * The package never dereferences `menuItemId`. It asks the host whether the id\n * is theirs (`order.catalogHas`, in `./bulk.ts`) and stores it; what the id\n * MEANS is the host's.\n */\n\n/** A link as every read surface sees it. */\nexport interface MarketplaceMenuLinkView {\n id: string;\n provider: MarketplaceProvider;\n externalSku: string;\n externalName: string;\n /** The host catalog id, or null while the SKU is unmapped. */\n menuItemId: string | null;\n lastSeenAt: Date;\n}\n\nconst LINK_SELECT = {\n id: true,\n provider: true,\n externalSku: true,\n externalName: true,\n menuItemId: true,\n lastSeenAt: true,\n} as const;\n\ninterface LinkRow {\n id: string;\n provider: string;\n externalSku: string;\n externalName: string | null;\n menuItemId: string | null;\n lastSeenAt: Date;\n}\n\nfunction toView(row: LinkRow): MarketplaceMenuLinkView {\n return {\n id: row.id,\n provider: row.provider as MarketplaceProvider,\n externalSku: row.externalSku,\n externalName: row.externalName ?? row.externalSku,\n menuItemId: row.menuItemId,\n lastSeenAt: row.lastSeenAt,\n };\n}\n\n/**\n * A store's SKU map. `unmappedOnly` is the attention list.\n *\n * Ordered by `lastSeenAt` descending, which is the ordering that matters for\n * the unmapped half: a store fixing five mappings should fix the five that are\n * costing them money right now, not the five that happen to be oldest.\n */\nexport async function listMarketplaceMenuLinks(\n ctx: EngineContext,\n input: { clientId: string; provider?: MarketplaceProvider; unmappedOnly?: boolean; ids?: readonly string[] },\n): Promise<MarketplaceMenuLinkView[]> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceMenuLink.findMany({\n where: {\n clientId: input.clientId,\n ...(input.ids ? { id: { in: [...input.ids] } } : {}),\n ...(input.provider ? { provider: input.provider } : {}),\n ...(input.unmappedOnly ? { menuItemId: null } : {}),\n },\n select: LINK_SELECT,\n orderBy: { lastSeenAt: \"desc\" },\n })) as LinkRow[];\n return rows.map(toView);\n}\n\n/**\n * Point an external SKU at a catalog id, or unmap it, inside the caller's\n * transaction. The caller has already checked the id is this tenant's\n * (`order.catalogHas`). Creates the link if the SKU has never been seen: an\n * operator mapping ahead of the first order is doing the right thing.\n */\nexport async function upsertLink(\n db: MarketplaceDb,\n input: {\n clientId: string;\n provider: MarketplaceProvider;\n externalSku: string;\n externalName?: string;\n menuItemId: string | null;\n },\n): Promise<MarketplaceMenuLinkView> {\n const row = (await db.marketplaceMenuLink.upsert({\n where: {\n clientId_provider_externalSku: {\n clientId: input.clientId,\n provider: input.provider,\n externalSku: input.externalSku,\n },\n },\n create: {\n clientId: input.clientId,\n provider: input.provider,\n externalSku: input.externalSku,\n externalName: input.externalName ?? input.externalSku,\n menuItemId: input.menuItemId,\n },\n // `externalName` is NOT rewritten here. It is the marketplace's snapshot of\n // what it called the item, and an operator's typing is not a better record\n // of that than the marketplace's own text.\n update: { menuItemId: input.menuItemId },\n select: LINK_SELECT,\n })) as LinkRow;\n return toView(row);\n}\n\n/**\n * Resolve an order's SKUs to catalog ids, recording every one of them.\n *\n * Called on the ingestion path, so it does two jobs at once and both are\n * required: it answers what each SKU maps to, and it makes sure a row exists\n * for each — including the ones that map to nothing, which is how an unmapped\n * SKU reaches the attention list at all. Upserting on the ingest path is what\n * makes the list self-maintaining; a store never has to discover the gap by\n * reading a ticket.\n */\nexport async function resolveSkus(\n db: MarketplaceDb,\n input: {\n clientId: string;\n provider: MarketplaceProvider;\n skus: { externalSku: string; name: string }[];\n seenAt: Date;\n },\n): Promise<Map<string, string | null>> {\n const resolved = new Map<string, string | null>();\n for (const sku of input.skus) {\n const row = (await db.marketplaceMenuLink.upsert({\n where: {\n clientId_provider_externalSku: {\n clientId: input.clientId,\n provider: input.provider,\n externalSku: sku.externalSku,\n },\n },\n create: {\n clientId: input.clientId,\n provider: input.provider,\n externalSku: sku.externalSku,\n externalName: sku.name,\n lastSeenAt: input.seenAt,\n },\n update: { lastSeenAt: input.seenAt },\n select: { menuItemId: true },\n })) as { menuItemId: string | null };\n resolved.set(sku.externalSku, row.menuItemId);\n }\n return resolved;\n}\n","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 type { CancellationReason, MarketplaceAdapter } from \"./adapter\";\nimport type { EngineContext } from \"./ports\";\nimport { resolveReason } from \"./registry\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * The store's own CANCELLATION REQUEST — the half of a refusal that must reach\n * the marketplace. Lives on the acceptance row:\n *\n * null ──refuse/cancel──▶ PENDING ──job 2xx──▶ REQUESTED ──event──▶ CONFIRMED\n * │ └──job 4xx / last attempt──▶ FAILED ──event──▶ CONFIRMED\n * └──event (the marketplace cancelled)──▶ CONFIRMED\n *\n * CONFIRMED is terminal; every write is predicated on the statuses it may come\n * from, so an out-of-order event cannot undo it.\n */\n\n/** Why a decision (or a store cancellation) was refused. Vocabulary, not copy. */\nexport type DecisionProblemCode =\n | \"DUPLICATE\"\n | \"NOT_FOUND\"\n | \"ALREADY_DECIDED\"\n | \"EXPIRED\"\n | \"CONFLICT\"\n | \"INVALID_REASON\"\n | \"ITEMS_REQUIRED\"\n | \"UNKNOWN_ITEM\"\n | \"HOST_REFUSED\";\n\n/** One refusal, with the path of the input it is about. Nothing was written. */\nexport interface DecisionProblem {\n path: (string | number)[];\n code: DecisionProblemCode;\n /** The row's current status, for NOT-pending refusals (ALREADY_DECIDED, EXPIRED). */\n status?: AcceptanceStatus;\n /** The marketplace's codes, for INVALID_REASON. */\n validCodes?: string[];\n /** The host's own refusal, for HOST_REFUSED. */\n host?: { code: string; message: string; details?: unknown };\n}\n\n/** The acceptance row a claim reads first. */\nexport interface ClaimRow {\n orderId: string;\n provider: string;\n status: string;\n cancellationStatus: string | null;\n lineSkus: unknown;\n}\n\nexport const CLAIM_SELECT = {\n orderId: true,\n provider: true,\n status: true,\n cancellationStatus: true,\n lineSkus: true,\n} as const;\n\n/** The refusal a row that is no longer on the clock earns, or null. */\nexport function notPendingProblem(\n row: ClaimRow | undefined | null,\n path: (string | number)[],\n allowed: readonly string[] = [\"AWAITING\"],\n): DecisionProblem | null {\n if (!row) return { path: [...path, \"orderId\"], code: \"NOT_FOUND\" };\n if (allowed.includes(row.status) && row.cancellationStatus === null) return null;\n const status = row.status as AcceptanceStatus;\n return { path: [...path, \"orderId\"], code: status === \"EXPIRED\" ? \"EXPIRED\" : \"ALREADY_DECIDED\", status };\n}\n\n/** What a refusal stamps, and with which reason and SKUs. */\nexport interface CancellationPlan {\n status: CancellationStatus | null;\n reason: CancellationReason | null;\n skus: string[];\n}\n\nfunction lineSkusOf(row: ClaimRow): Set<string> | null {\n return Array.isArray(row.lineSkus) ? new Set(row.lineSkus.map(String)) : null;\n}\n\n/** Every refusal the named SKUs earn: none when the reason needs some, an unknown one. */\nfunction skuProblems(\n reason: CancellationReason | null,\n skus: string[],\n row: ClaimRow,\n path: (string | number)[],\n): DecisionProblem[] {\n if (reason?.needsItems && skus.length === 0) return [{ path: [...path, \"offendingSkus\"], code: \"ITEMS_REQUIRED\" }];\n const known = lineSkusOf(row);\n // A row from before `line_skus` existed cannot be checked; its SKUs pass.\n if (!known) return [];\n return skus.flatMap((sku, index) =>\n known.has(sku) ? [] : [{ path: [...path, \"offendingSkus\", index], code: \"UNKNOWN_ITEM\" as const }],\n );\n}\n\n/** The refusal of a named code that is not the marketplace's, or null. */\nfunction invalidReasonProblem(\n adapter: MarketplaceAdapter,\n reason: CancellationReason | null,\n code: string | null | undefined,\n path: (string | number)[],\n): DecisionProblem | null {\n if (code === null || code === undefined || reason) return null;\n const validCodes = adapter.cancellationReasons().map((candidate) => candidate.code);\n return { path: [...path, \"reasonCode\"], code: \"INVALID_REASON\", validCodes };\n}\n\n/**\n * Plan the cancellation half of a refusal, or say what is wrong with it.\n *\n * - No adapter (a provider nobody registers any more): nothing goes out.\n * - The code must be the marketplace's; with none, its first reason is taken.\n * - A reason that `needsItems` needs offending SKUs, each one of the order's.\n * - An API that cannot cancel — at all, or after an accept — stamps FAILED at\n * once: the request cannot be made from here, and FAILED is what puts the\n * adapter's app link in front of a person.\n * - Otherwise PENDING, for the outbound job.\n */\nexport function planCancellation(\n adapter: MarketplaceAdapter | null,\n input: { reasonCode?: string | null; offendingSkus?: readonly string[] },\n row: ClaimRow,\n path: (string | number)[],\n): CancellationPlan | DecisionProblem[] {\n if (!adapter) return { status: null, reason: null, skus: [] };\n const reason = resolveReason(adapter, input.reasonCode);\n const invalid = invalidReasonProblem(adapter, reason, input.reasonCode, path);\n if (invalid) return [invalid];\n const skus = [...new Set(input.offendingSkus ?? [])];\n const problems = skuProblems(reason, skus, row, path);\n if (problems.length > 0) return problems;\n const { apiCancel, cancelAfterAccept } = adapter.capabilities;\n const canAsk = apiCancel && reason !== null && (row.status === \"AWAITING\" || cancelAfterAccept);\n return { status: canAsk ? \"PENDING\" : \"FAILED\", reason, skus };\n}\n\n/** The columns one refusal writes, from the status it leaves. */\nexport function refusalData(plan: CancellationPlan, fromStatus: string, now: Date): Record<string, unknown> {\n return {\n status: \"REJECTED\",\n // An accepted row keeps the instant it was accepted; a row leaving the\n // clock is acknowledged now (the table's CHECK pairs the two).\n ...(fromStatus === \"AWAITING\" ? { acknowledgedAt: now } : {}),\n cancellationStatus: plan.status,\n cancellationReasonCode: plan.reason?.code ?? null,\n cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,\n cancellationRequestedAt: plan.status === \"PENDING\" ? now : null,\n };\n}\n\n/**\n * The marketplace refused the store's cancellation request. FAILED, from\n * PENDING or REQUESTED only: CONFIRMED is terminal, so a refusal arriving\n * after the cancellation changes nothing. Returns whether a row moved.\n */\nexport async function failCancellationRequest(\n ctx: EngineContext,\n input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string },\n): Promise<boolean> {\n const db = await ctx.ports.db();\n const moved = await db.marketplaceAcceptance.updateMany({\n where: {\n clientId: input.clientId,\n provider: input.provider,\n externalOrderId: input.externalOrderId,\n cancellationStatus: { in: [\"PENDING\", \"REQUESTED\"] },\n },\n data: { cancellationStatus: \"FAILED\" },\n });\n if (moved.count > 0) ctx.ports.publishChanged(input.clientId);\n return moved.count > 0;\n}\n","import type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * The outbound job's name and payload — what a decision QUEUES.\n *\n * No path that answers a request ever calls a marketplace: an aceite, a\n * refusal, a webhook and an ingest only enqueue this, and the job does the\n * call. The payload carries identifiers only; the reason code and every\n * outcome live on the acceptance row, so a replayed or duplicated job reads\n * the truth rather than a stale copy of it.\n */\n\n/** The wire name, `<namespace>.<blueprint>` as the jobs contribution binds it. */\nexport const MARKETPLACE_OUTBOUND_JOB = \"marketplace.outbound\";\n\n/** What goes out: the store's aceite, or the store's cancellation request. */\nexport type OutboundAction = \"confirm\" | \"requestCancellation\";\n\n/** The outbound job's payload. Identifiers only. */\nexport interface OutboundJobPayload {\n clientId: string;\n orderId: string;\n action: OutboundAction;\n}\n\n/** The dedupe key: at most one queued call per (order, action). */\nexport function outboundDedupeKey(payload: OutboundJobPayload): string {\n return `${MARKETPLACE_OUTBOUND_JOB}:${payload.action}:${payload.orderId}`;\n}\n\n/**\n * Queue one outbound call, when the marketplace's API can take it at all.\n *\n * A marketplace whose adapter states no API for the action gets nothing\n * queued: there is nobody to call, and the host shows the app link instead.\n * The queue port never throws. A refusal to enqueue is logged AND recovered:\n * the row still owes the call (PENDING, or ACCEPTED with no confirm stamp),\n * and the outbound sweep re-queues every such row (`./outbound-sweep.ts`).\n *\n * `dedupeKey` defaults to the job's own key; the sweep passes its own, since a\n * queue keeps a finished job's id and would swallow a re-queue under it.\n */\nexport async function enqueueOutbound(\n ctx: EngineContext,\n payload: OutboundJobPayload,\n provider: MarketplaceProvider,\n dedupeKey: string = outboundDedupeKey(payload),\n): Promise<boolean> {\n const adapter = ctx.registry.get(provider);\n if (!adapter) return false;\n const able =\n payload.action === \"confirm\" ? adapter.capabilities.apiConfirm : adapter.capabilities.apiCancel;\n if (!able) return false;\n const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });\n if (!outcome.enqueued) {\n ctx.ports.logger.warn(\n `${MARKETPLACE_OUTBOUND_JOB}: ${payload.action} for order ${payload.orderId} was not queued; the outbound sweep will re-queue it` +\n (outcome.reason ? ` (${outcome.reason})` : \"\"),\n );\n }\n return outcome.enqueued;\n}\n","import type { AcceptanceStatus, CancellationStatus } from \"./acceptance\";\nimport {\n CLAIM_SELECT,\n notPendingProblem,\n planCancellation,\n refusalData,\n type CancellationPlan,\n type ClaimRow,\n type DecisionProblem,\n type DecisionProblemCode,\n} from \"./cancellation\";\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/** One decided row. */\nexport interface DecidedRow {\n orderId: string;\n status: Extract<AcceptanceStatus, \"ACCEPTED\" | \"REJECTED\">;\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}\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): DecidedRow {\n return {\n orderId: input.orderId,\n status: input.decision === \"ACCEPT\" ? \"ACCEPTED\" : \"REJECTED\",\n cancellation: plan?.status ?? null,\n reasonCode: plan?.reason?.code ?? null,\n offendingSkus: plan?.skus ?? [],\n };\n}\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 const data = { status: \"ACCEPTED\", acknowledgedAt: now, preparationMinutes: input.preparationMinutes ?? null };\n return { input, index, row, data, decided: decidedOf(input, null) };\n }\n const plan = planCancellation(ctx.registry.get(row.provider), input, row, path);\n if (Array.isArray(plan)) return plan;\n return { input, index, row, data: refusalData(plan, row.status, now), decided: decidedOf(input, plan) };\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\" },\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.decided.status === \"ACCEPTED\") {\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\") await ctx.ports.order.onAccepted(clientId, orderId);\n else await ctx.ports.order.onRefused(clientId, orderId, \"REJECTED\");\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 cancelled an order through the host's own cancel — before or\n * after accepting it. Stamps the request the marketplace must hear and queues\n * it. The host's own cancel already ran, so the engine neither admits nor\n * calls `onRefused`: it records and queues, and nothing else.\n *\n * `stale` (ALREADY_DECIDED) when the marketplace already cancelled it, the\n * clock lapsed (EXPIRED), or a request was already made.\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 const now = input.now ?? ctx.ports.clock.now();\n const db = await ctx.ports.db();\n const claimed = await db.marketplaceAcceptance.updateMany({\n where: { orderId: input.orderId, clientId: input.clientId, status: row.status, cancellationStatus: null },\n data: 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 return { kind: \"decided\", ...decidedOf({ orderId: input.orderId, decision: \"REJECT\" }, plan) };\n}\n","import { MARKETPLACE_OUTBOUND_JOB, enqueueOutbound, type OutboundAction } from \"./outbound-queue\";\nimport type { EngineContext } from \"./ports\";\n\n/**\n * The outbound sweep: nothing owed to a marketplace is lost.\n *\n * A decision queues its call right after the commit, but a queue can refuse\n * the job, a process can die between the commit and the enqueue, and a job can\n * die without stamping. The ROW still says what is owed — a PENDING request,\n * or an ACCEPTED order with neither confirm stamp — so this pass re-queues\n * every such row once it is older than the outbound job's own retry span.\n *\n * Bounded both ways:\n * - younger than {@link OUTBOUND_STALE_MS}: the original job may still be\n * retrying, so it is left alone;\n * - older than {@link OUTBOUND_GIVE_UP_MS}: a marketplace has long since\n * settled the order on its own clock. A PENDING request that old is stamped\n * FAILED (a person finishes it on the marketplace, through the app link),\n * and an accept that old is never confirmed — which is also what keeps a\n * host's ACCEPTED history from before this engine from being confirmed on\n * the first pass.\n *\n * Re-queued under a key of its own per pass: a queue keeps a finished job's id\n * and would swallow a re-queue under the job's plain key. The job itself is\n * idempotent by the row, so a duplicate run calls nobody twice.\n */\n\n/** Longer than the outbound job's three attempts with their backoff. */\nexport const OUTBOUND_STALE_MS = 10 * 60_000;\n\n/** Past this, a marketplace has settled the order without us. */\nexport const OUTBOUND_GIVE_UP_MS = 24 * 60 * 60_000;\n\n/** What one sweep pass did. */\nexport interface OutboundSweepResult {\n requeued: number;\n givenUp: number;\n}\n\ninterface OwedRow {\n clientId: string;\n orderId: string;\n provider: string;\n}\n\nconst OWED_SELECT = { clientId: true, orderId: true, provider: true } as const;\n\n/** The sweep's own dedupe key: distinct from the job's, and per pass. */\nfunction sweepDedupeKey(action: OutboundAction, orderId: string, now: Date): string {\n return `${MARKETPLACE_OUTBOUND_JOB}:${action}:${orderId}:sweep:${now.getTime()}`;\n}\n\nasync function requeue(ctx: EngineContext, rows: readonly OwedRow[], action: OutboundAction, now: Date): Promise<number> {\n let queued = 0;\n for (const row of rows) {\n const payload = { clientId: row.clientId, orderId: row.orderId, action };\n if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now))) queued += 1;\n }\n return queued;\n}\n\n/** Re-queue every owed call older than the job's retry span; give up on the ancient ones. */\nexport async function sweepOutbound(ctx: EngineContext, now: Date): Promise<OutboundSweepResult> {\n const db = await ctx.ports.db();\n const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);\n const giveUp = new Date(now.getTime() - OUTBOUND_GIVE_UP_MS);\n\n const abandoned = await db.marketplaceAcceptance.updateMany({\n where: { cancellationStatus: \"PENDING\", cancellationRequestedAt: { lt: giveUp } },\n data: { cancellationStatus: \"FAILED\" },\n });\n const cancellations = (await db.marketplaceAcceptance.findMany({\n where: { cancellationStatus: \"PENDING\", cancellationRequestedAt: { lt: stale, gte: giveUp } },\n select: OWED_SELECT,\n })) as OwedRow[];\n const confirms = (await db.marketplaceAcceptance.findMany({\n where: {\n status: \"ACCEPTED\",\n confirmedAt: null,\n confirmFailedAt: null,\n acknowledgedAt: { lt: stale, gte: giveUp },\n },\n select: OWED_SELECT,\n })) as OwedRow[];\n\n const requeued =\n (await requeue(ctx, cancellations, \"requestCancellation\", now)) + (await requeue(ctx, confirms, \"confirm\", now));\n if (abandoned.count > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${abandoned.count} cancellation request(s).`);\n return { requeued, givenUp: abandoned.count };\n}\n","import type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider, NormalizedEvent } from \"./types\";\n\n/**\n * The durable inbox , needed here for two reasons rather than one.\n *\n * A marketplace's delivery is not reliably exactly-once, so the SAME event\n * arrives more than once and the pipeline must be able to say \"already seen\".\n * It is not reliably at-least-once either, so reconciliation polling has to be\n * able to inject an event the webhook never brought. Both paths write here, and\n * `(provider, eventId)` is what collapses them onto one row — a duplicate is a\n * DB-level no-op rather than a second order.\n *\n * The RAW payload is stored because normalization is the part most likely to be\n * wrong. When a mapping bug drops a line, the only way to reconstruct what the\n * marketplace actually said is to have kept it.\n */\n\n/** What {@link recordInboxEvent} tells the caller about a delivery. */\ninterface InboxRecord {\n id: string;\n /** False when this exact delivery had already been recorded. */\n fresh: boolean;\n}\n\n/**\n * Record one delivery, deduped on `(provider, eventId)`.\n *\n * Returns `fresh: false` for a redelivery, which is the pipeline's whole\n * idempotency story at the door: the caller stops there and answers the\n * marketplace 200. Answering 200 to a duplicate matters as much as processing\n * the original — a marketplace that gets an error redelivers, and a pipeline\n * that errors on its own duplicates never stops receiving them.\n */\nexport async function recordInboxEvent(\n ctx: EngineContext,\n input: { clientId: string | null; event: NormalizedEvent; payload: unknown },\n): Promise<InboxRecord> {\n const db = await ctx.ports.db();\n const key = { provider_eventId: { provider: input.event.provider, eventId: input.event.eventId } };\n const existing = (await db.marketplaceInboxEvent.findUnique({\n where: key,\n select: { id: true },\n })) as { id: string } | null;\n if (existing) return { id: existing.id, fresh: false };\n\n try {\n const row = (await db.marketplaceInboxEvent.create({\n data: {\n clientId: input.clientId,\n provider: input.event.provider,\n eventId: input.event.eventId,\n eventType: input.event.eventType,\n externalOrderId: input.event.externalOrderId,\n payload: input.payload,\n },\n select: { id: true },\n })) as { id: string };\n return { id: row.id, fresh: true };\n } catch (error) {\n // The check-then-insert above is not atomic, and two simultaneous\n // redeliveries are exactly the shape that loses that race. The unique index\n // is the real guard; this turns losing the race into the same answer the\n // check would have given, rather than a 500 that provokes another retry.\n if ((error as { code?: string }).code !== \"P2002\") throw error;\n const raced = (await db.marketplaceInboxEvent.findUnique({\n where: key,\n select: { id: true },\n })) as { id: string } | null;\n return { id: raced?.id ?? \"\", fresh: false };\n }\n}\n\n/** How an inbox row ended up. */\ntype InboxOutcome = \"PROCESSED\" | \"FAILED\" | \"IGNORED\";\n\n/**\n * Close out an inbox row.\n *\n * `attempts` increments on every close, including the successful one, so the\n * count reads as \"how many times did we touch this\" rather than \"how many times\n * did we fail\" — a row PROCESSED on its third attempt is a different story from\n * one processed on its first, and only the incrementing version can tell them\n * apart.\n */\nexport async function settleInboxEvent(\n ctx: EngineContext,\n id: string,\n outcome: InboxOutcome,\n error?: string,\n): Promise<void> {\n if (!id) return;\n const db = await ctx.ports.db();\n await db.marketplaceInboxEvent.update({\n where: { id },\n data: {\n status: outcome,\n // Truncated: a provider's error body can be a page of HTML, and the\n // column exists to be read by a human in a list.\n error: error ? error.slice(0, 500) : null,\n processedAt: ctx.ports.clock.now(),\n attempts: { increment: 1 },\n },\n });\n}\n\n/**\n * Leave a row PENDING with its reason recorded, and count the attempt.\n *\n * The state between \"done\" and \"broken\": the delivery is fine and the STORE is\n * not ready for it — the channel is switched off, or was mid-onboarding when\n * the order came in. Settling it either way would be a lie (IGNORED discards an\n * order that could still be ingested; FAILED blames the payload), so it stays\n * PENDING and the sweep picks it up again.\n *\n * The attempt still counts, which is what stops the churn: the sweep's own\n * attempt bound retires a row after a few passes over a store that never turned\n * the channel on, instead of re-reading it forever.\n */\nexport async function deferInboxEvent(\n ctx: EngineContext,\n id: string,\n reason: string,\n): Promise<void> {\n if (!id) return;\n const db = await ctx.ports.db();\n await db.marketplaceInboxEvent.update({\n where: { id },\n data: { error: reason.slice(0, 500), attempts: { increment: 1 } },\n });\n}\n\n/** One stored delivery, as the retry sweep re-reads it. */\nexport interface PendingInboxEvent {\n id: string;\n clientId: string;\n provider: MarketplaceProvider;\n payload: unknown;\n}\n\n/**\n * Deliveries recorded but never processed, oldest first.\n *\n * PENDING and FAILED both qualify: a row left PENDING is one whose process died\n * between recording and processing — the exact crash the durable inbox exists\n * to survive — and dropping it would make the inbox a log rather than a queue.\n *\n * Unattributed events (`clientId` null) are deliberately NOT returned. There is\n * no tenant to ingest them into, so retrying achieves nothing; they stay in the\n * table as the evidence of a half-finished onboarding.\n */\nexport async function listRetryableInboxEvents(\n ctx: EngineContext,\n): Promise<PendingInboxEvent[]> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceInboxEvent.findMany({\n where: {\n status: { in: [\"PENDING\", \"FAILED\"] },\n clientId: { not: null },\n attempts: { lt: ctx.ports.maxInboxAttempts },\n },\n orderBy: { receivedAt: \"asc\" },\n take: ctx.ports.reconcileBatchSize,\n select: { id: true, clientId: true, provider: true, payload: true },\n })) as { id: string; clientId: string; provider: string; payload: unknown }[];\n return rows.map((row) => ({\n id: row.id,\n clientId: row.clientId,\n provider: row.provider as MarketplaceProvider,\n payload: row.payload,\n }));\n}\n","import { markMarketplaceEventSeen } from \"./integration\";\nimport { resolveSkus } from \"./menu-links\";\nimport { enqueueOutbound } from \"./outbound-queue\";\nimport type { EngineContext, MarketplaceDb, ResolvedOrderLine } from \"./ports\";\nimport type { NormalizedMarketplaceOrder } from \"./types\";\n\n/**\n * Normalized marketplace order → the host's own order.\n *\n * The rule this module is written around, stated once so every decision below\n * reads against it: **losing a paid marketplace order is the one unforgivable\n * failure.** An unmapped SKU, a buyer with no name, a total that does not equal\n * the line sum — none of them reject the order. They land, flagged, on a screen\n * a human can act on. The only thing that stops an ingestion is a condition\n * under which persisting would be WRONG rather than incomplete.\n *\n * Idempotent on `(provider, externalOrderId)`, which the acceptance table's\n * unique enforces. That is what makes a redelivered webhook, a reconciliation\n * poll racing it, and a retry after a crash all safe: each either creates the\n * one order or finds it already there. The pre-read below is a fast path, not\n * the guarantee — two concurrent deliveries both miss it and only one of them\n * reaches a row.\n */\n\n/** What one ingestion did. */\nexport interface IngestResult {\n /** The HOST's order id. */\n orderId: string;\n /** False when the order already existed — a redelivery, not a second sale. */\n created: boolean;\n /** SKUs that arrived with nothing behind them, in this order. */\n unmappedSkus: string[];\n /** Whether the connection's policy made this order born accepted. */\n autoAccepted: boolean;\n}\n\n/** The store's operating decisions, read from the connection at ingest time. */\nexport interface IngestSettings {\n autoAccept: boolean;\n ackSlaSeconds: number;\n}\n\n/**\n * Resolve the order's SKUs and compose its lines.\n *\n * `resolveSkus` does double duty on this path: it answers what each SKU maps to\n * AND records every one of them, which is how an unmapped SKU reaches the\n * store's attention list without anyone having to notice it first.\n */\nasync function composeLines(\n db: MarketplaceDb,\n clientId: string,\n order: NormalizedMarketplaceOrder,\n seenAt: Date,\n): Promise<ResolvedOrderLine[]> {\n const mapping = await resolveSkus(db, {\n clientId,\n provider: order.provider,\n skus: order.lines.map((line) => ({ externalSku: line.externalSku, name: line.name })),\n seenAt,\n });\n return order.lines.map((line) => ({\n externalSku: line.externalSku,\n // The MARKETPLACE's text, never the catalog's, even for a mapped line.\n // Every other order snapshots what the buyer was shown, and what this buyer\n // was shown is the marketplace's menu — a mapped line renamed to the host's\n // own product name would quietly disagree with the receipt in the bag.\n name: line.name,\n quantity: line.quantity,\n unitPriceCents: line.unitPriceCents,\n note: line.note,\n subjectRef: mapping.get(line.externalSku) ?? null,\n }));\n}\n\n/** The acceptance row an ingest writes: born ACCEPTED or on the clock. */\nfunction acceptanceData(\n clientId: string,\n orderId: string,\n order: NormalizedMarketplaceOrder,\n settings: IngestSettings,\n now: Date,\n): Record<string, unknown> {\n const accepted = settings.autoAccept;\n return {\n clientId,\n orderId,\n provider: order.provider,\n externalOrderId: order.externalOrderId,\n externalDisplayId: order.externalDisplayId,\n // Who carries a delivery: the merchant's courier or the marketplace's fleet.\n deliveredBy: order.deliveredBy ?? null,\n status: accepted ? \"ACCEPTED\" : \"AWAITING\",\n acknowledgeBy: new Date(now.getTime() + settings.ackSlaSeconds * 1000),\n acknowledgedAt: accepted ? now : null,\n externalDueAt: order.deliveryDueAt,\n commissionCents: order.commissionCents,\n // The order's SKUs: what a cancellation's offending SKUs are checked against.\n lineSkus: [...new Set(order.lines.map((line) => line.externalSku))],\n };\n}\n\n/**\n * Ingest one order.\n *\n * The deadline is stamped HERE, from the connection's SLA, and never recomputed\n * afterwards: a store that later lengthens its SLA must not move the deadline of\n * an order already on the clock, and one that shortens it must not retroactively\n * expire orders that were fine when they arrived.\n *\n * The acceptance row and the host's order are written in that dependency order\n * — the host creates its own row first and hands back an id, because only the\n * host knows what creating one costs. Auto-accept is decided at arrival so the\n * order is BORN accepted rather than created and immediately updated: the\n * two-step version has a window in which a crash leaves an order the store\n * believes was auto-accepted sitting on a clock nobody is watching.\n */\nexport async function ingestMarketplaceOrder(\n ctx: EngineContext,\n input: {\n clientId: string;\n order: NormalizedMarketplaceOrder;\n settings: IngestSettings;\n now?: Date;\n },\n): Promise<IngestResult> {\n const { clientId, order, settings } = input;\n const now = input.now ?? ctx.ports.clock.now();\n\n const db = await ctx.ports.db();\n // Answered from this package's OWN table rather than through a port: the\n // idempotency key is `(provider, externalOrderId)` on `marketplace_acceptances`,\n // so the package holds it and no host has to be trusted to re-implement it.\n const existing = (await db.marketplaceAcceptance.findFirst({\n where: { provider: order.provider, externalOrderId: order.externalOrderId },\n select: { orderId: true },\n })) as { orderId: string } | null;\n if (existing) {\n return { orderId: existing.orderId, created: false, unmappedSkus: [], autoAccepted: false };\n }\n\n const accepted = settings.autoAccept;\n // ONE transaction for the host's order, the SKU rows, the acceptance row and\n // the liveness stamp: the host's `create` is handed the transaction's client,\n // so an acceptance that cannot be written (a concurrent ingest won the\n // unique) rolls the host's order back with it, and a redelivery never meets\n // an orphan host order to duplicate.\n const { orderId, unmappedSkus } = await ctx.ports.transaction(async (tx) => {\n const lines = await composeLines(tx, clientId, order, now);\n const created = await ctx.ports.order.create(clientId, order, lines, tx);\n await tx.marketplaceAcceptance.create({ data: acceptanceData(clientId, created, order, settings, now) });\n await markMarketplaceEventSeen(tx, clientId, order.provider, now);\n return { orderId: created, unmappedSkus: lines.filter((l) => l.subjectRef === null).map((l) => l.externalSku) };\n });\n\n if (accepted) {\n // Born accepted is still an acceptance the marketplace must hear about.\n // Queued FIRST, never called (no ingest waits on a marketplace's API), so\n // a host half that throws cannot lose it; the sweep re-queues it if the\n // queue refused it.\n await enqueueOutbound(ctx, { clientId, orderId, action: \"confirm\" }, order.provider);\n await ctx.ports.order.onAccepted(clientId, orderId);\n }\n\n ctx.ports.publishChanged(clientId);\n\n return { orderId, created: true, unmappedSkus, autoAccepted: accepted };\n}\n","import { cancelAcceptance } from \"./acceptance\";\nimport { failCancellationRequest } from \"./cancellation\";\nimport { deferInboxEvent, recordInboxEvent, settleInboxEvent } from \"./inbox\";\nimport { ingestMarketplaceOrder, type IngestSettings } from \"./ingest\";\nimport { resolveIngestionTarget } from \"./integration\";\nimport type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider, NormalizedEvent } 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 | { 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/**\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 await cancelAcceptance(ctx, {\n clientId,\n provider: event.provider,\n externalOrderId: event.externalOrderId,\n now,\n });\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n return { kind: \"cancelled\" };\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 const result = await ingestMarketplaceOrder(ctx, {\n clientId,\n order: event.order,\n settings,\n now,\n });\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 },\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 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 { 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 /** 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}\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 },\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 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 { sweepOutbound, type OutboundSweepResult } from \"./outbound-sweep\";\nimport type {\n AdapterTokenCache,\n CancellationReason,\n MarketplaceAdapter,\n OutboundOrderRef,\n} from \"./adapter\";\nimport { listRetryableInboxEvents, type PendingInboxEvent } from \"./inbox\";\nimport { ingestMarketplaceOrder, type IngestResult, type IngestSettings } from \"./ingest\";\nimport {\n listMarketplaceIntegrations,\n resolveIngestionTarget,\n resolveTenantByMerchant,\n saveMarketplaceIntegration,\n type IngestionTarget,\n type MarketplaceIntegrationView,\n type SaveMarketplaceIntegrationInput,\n} from \"./integration\";\nimport { listMarketplaceMenuLinks, type MarketplaceMenuLinkView } from \"./menu-links\";\nimport { runOutbound, type OutboundAttempt, type OutboundOutcome } from \"./outbound\";\nimport type { OutboundJobPayload } from \"./outbound-queue\";\nimport {\n normalizeEvent,\n processDelivery,\n reprocessStoredDelivery,\n type DeliveryOutcome,\n} from \"./pipeline\";\nimport type { EngineContext, MarketplaceEngineConfig } from \"./ports\";\nimport { createAdapterRegistry, suggestReason } from \"./registry\";\nimport { readOrderStates, type MarketplaceOrderState } from \"./state\";\nimport type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from \"./types\";\n\n/** Everything the mounted engine can do, with the ports and adapters bound in. */\nexport interface MarketplaceEngine {\n /** Every registered marketplace, in registration order. */\n providers(): readonly MarketplaceProvider[];\n /** Whether a provider id (a URL segment, a body field) names a registered adapter. */\n knows(provider: string): provider is MarketplaceProvider;\n /** The adapter itself: its capabilities, reasons and app link. Null when unknown. */\n adapter(provider: string): MarketplaceAdapter | null;\n /** The marketplace's reasons, static and offline. Empty when unknown. */\n reasons(provider: string): readonly CancellationReason[];\n /** The reason a host preselects, given whether the order is short of an item. */\n suggestReason(provider: string, input: { itemUnavailable: boolean }): CancellationReason | null;\n /** Where a person goes to act on the marketplace's side. Null when unknown. */\n appLink(provider: string, order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string | null;\n\n /** Turn a raw payload into the canonical shape, or null if nothing does. */\n normalize(provider: string, payload: unknown): NormalizedEvent | null;\n /** Read the provider's signature header off a request. */\n readSignature(provider: string, header: (name: string) => string | null): string | null;\n /** Verify a delivery. An unknown provider is never verified, so never accepted. */\n verifySignature(provider: string, rawBody: string, signature: string | null, secret: string | null): boolean;\n /** Which tenant a delivery belongs to, from the merchant id it names. */\n tenantFor(provider: MarketplaceProvider, externalMerchantId: string): Promise<string | null>;\n /** The connection behind one (tenant, marketplace), for the ingestion path. */\n target(clientId: string, provider: MarketplaceProvider): Promise<IngestionTarget | null>;\n /** Ingest ONE already-normalized order, bypassing the inbox. Idempotent. */\n ingest(input: {\n clientId: string;\n order: NormalizedMarketplaceOrder;\n settings: IngestSettings;\n now?: Date;\n }): Promise<IngestResult>;\n /** Record and act on one delivery. Never throws. */\n deliver(input: {\n clientId: string | null;\n event: NormalizedEvent;\n payload: unknown;\n settings: IngestSettings | null;\n now?: Date;\n }): Promise<DeliveryOutcome>;\n\n /** This store's connections, secrets withheld; archived ones only when asked. */\n integrations(\n clientId: string,\n options?: { providers?: readonly string[]; includeArchived?: boolean },\n ): Promise<MarketplaceIntegrationView[]>;\n /** Create or patch ONE connection (the bulk call's single-row form, with no audit). */\n saveIntegration(input: SaveMarketplaceIntegrationInput): Promise<MarketplaceIntegrationView>;\n /** Create, patch, archive or unarchive many connections, all-or-nothing. */\n upsertIntegrations(input: {\n clientId: string;\n actorId: string | null;\n rows: readonly IntegrationRowInput[];\n validateOnly?: boolean;\n }): Promise<BulkResult<MarketplaceIntegrationView>>;\n\n /** The SKU map. `unmappedOnly` is the store's attention list; `ids` narrows. */\n menuLinks(input: {\n clientId: string;\n provider?: MarketplaceProvider;\n unmappedOnly?: boolean;\n ids?: readonly string[];\n }): Promise<MarketplaceMenuLinkView[]>;\n /** Map or unmap many SKUs, all-or-nothing. */\n upsertMenuLinks(input: {\n clientId: string;\n rows: readonly MenuLinkRowInput[];\n validateOnly?: boolean;\n }): Promise<BulkResult<MarketplaceMenuLinkView>>;\n /** Map or unmap ONE SKU. `null` = the catalog id is not this tenant's. */\n setMenuLink(input: { clientId: string } & MenuLinkRowInput): Promise<MarketplaceMenuLinkView | null>;\n\n /** Orders still on the clock, soonest deadline first; `orderIds` narrows. */\n pending(clientId: string, orderIds?: readonly string[]): Promise<PendingAcceptance[]>;\n /** Decide many orders, all-or-nothing, the host admitting each inside the claim's transaction. */\n decideMany(input: {\n clientId: string;\n decisions: readonly DecisionInput[];\n validateOnly?: boolean;\n now?: Date;\n }): Promise<DecideManyResult>;\n /** Decide ONE order (`decideMany` with one decision). */\n decide(input: { clientId: string; now?: Date } & DecisionInput): Promise<DecisionResult>;\n /** The store cancelled through the host's own cancel: stamp and queue the request. */\n recordStoreCancellation(input: {\n clientId: string;\n orderId: string;\n reasonCode?: string | null;\n offendingSkus?: readonly string[];\n now?: Date;\n }): Promise<DecisionResult>;\n /** The marketplace cancelled an order we already have. */\n cancel(input: {\n clientId: string;\n provider: MarketplaceProvider;\n externalOrderId: string;\n now?: Date;\n }): Promise<boolean>;\n /** Where each of these orders' acceptance and cancellation stand. */\n orderStates(clientId: string, orderIds: readonly string[]): Promise<Map<string, MarketplaceOrderState>>;\n\n /** Expire every order whose deadline has passed, across all tenants. */\n expireLapsed(now?: Date): Promise<ExpirySweepResult>;\n /** Deliveries recorded but never processed, oldest first. */\n retryable(): Promise<PendingInboxEvent[]>;\n /** Re-run one stored delivery against the store's CURRENT settings. */\n reprocess(event: PendingInboxEvent): Promise<DeliveryOutcome>;\n /** Re-queue every outbound call still owed (the `marketplace.outbound-sweep` job's body). */\n sweepOutbound(now?: Date): Promise<OutboundSweepResult>;\n /** Run one queued outbound call (the `marketplace.outbound` job's body). */\n runOutbound(payload: OutboundJobPayload, attempt: OutboundAttempt): Promise<OutboundOutcome>;\n}\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 };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqEA,eAAsB,uBACpB,KACA,UACA,UAC8B;AAC9B,QAAM,KAAK,MAAM,IAAI,MAAM,GAAG;AAC9B,QAAM,OAAQ,MAAM,GAAG,sBAAsB,SAAS;AAAA,IACpD,OAAO,EAAE,UAAU,QAAQ,YAAY,GAAI,WA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ates"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/bulk.ts","../src/core/decisions.ts","../src/core/pipeline.ts","../src/core/state.ts","../src/core/engine.ts"],"sourcesContent":["import {\n listMarketplaceIntegrations,\n saveMarketplaceIntegration,\n type MarketplaceIntegrationView,\n type SaveMarketplaceIntegrationInput,\n} from \"./integration\";\nimport { upsertLink, type MarketplaceMenuLinkView } from \"./menu-links\";\nimport type { EngineContext, MarketplaceAuditEntry, MarketplaceDb } from \"./ports\";\n\n/**\n * The bulk writes: one call, many rows, all-or-nothing.\n *\n * Every row is validated first (cross-row duplicates, unknown providers, a\n * catalog id that is not the store's, an archive of nothing) and every problem\n * is returned with its path; any problem writes nothing. Then ONE transaction\n * writes every row, or none. `validateOnly` validates and writes nothing.\n * Idempotent on the natural key: a connection is `(store, provider)`, a SKU\n * link `(store, provider, externalSku)`.\n */\n\n/** Why a bulk row was refused. Vocabulary, not copy. */\nexport type BulkProblemCode =\n | \"DUPLICATE\"\n | \"UNKNOWN_PROVIDER\"\n | \"NOTHING_TO_UPDATE\"\n | \"NOT_FOUND\"\n | \"CATALOG_ITEM_NOT_FOUND\";\n\nexport interface BulkProblem {\n path: (string | number)[];\n code: BulkProblemCode;\n}\n\nexport type BulkResult<T> =\n | { kind: \"saved\"; validateOnly: boolean; rows: T[] }\n | { kind: \"refused\"; problems: BulkProblem[] };\n\n/** One connection row: an upsert of its settings, an archive, or an unarchive. */\nexport type IntegrationRowInput =\n | ({ operation?: \"upsert\" } & Omit<SaveMarketplaceIntegrationInput, \"clientId\">)\n | { operation: \"archive\" | \"unarchive\"; provider: string; reason?: string | null };\n\n/** One SKU link: map it to a catalog id, or unmap it with `menuItemId: null`. */\nexport interface MenuLinkRowInput {\n provider: string;\n externalSku: string;\n externalName?: string;\n menuItemId: string | null;\n}\n\n/** The key of each row seen twice, as problems. */\nfunction duplicates<T>(rows: readonly T[], keyOf: (row: T) => string, list: string, field: string): BulkProblem[] {\n const seen = new Set<string>();\n return rows.flatMap((row, index) => {\n const key = keyOf(row);\n if (!seen.has(key)) {\n seen.add(key);\n return [];\n }\n return [{ path: [list, index, field], code: \"DUPLICATE\" as const }];\n });\n}\n\nfunction unknownProviders(ctx: EngineContext, rows: readonly { provider: string }[], list: string): BulkProblem[] {\n return rows.flatMap((row, index) =>\n ctx.registry.has(row.provider) ? [] : [{ path: [list, index, \"provider\"], code: \"UNKNOWN_PROVIDER\" as const }],\n );\n}\n\nconst SETTING_KEYS = [\"enabled\", \"environment\", \"externalMerchantId\", \"autoAccept\", \"ackSlaSeconds\", \"credentials\"] as const;\n\nfunction integrationRowProblems(\n row: IntegrationRowInput,\n index: number,\n existing: ReadonlySet<string>,\n): BulkProblem[] {\n if (row.operation === \"archive\" || row.operation === \"unarchive\") {\n return existing.has(row.provider) ? [] : [{ path: [\"integrations\", index, \"provider\"], code: \"NOT_FOUND\" }];\n }\n const settings = row as Partial<Record<(typeof SETTING_KEYS)[number], unknown>>;\n const changes = SETTING_KEYS.some((key) => settings[key] !== undefined);\n return changes ? [] : [{ path: [\"integrations\", index], code: \"NOTHING_TO_UPDATE\" }];\n}\n\n/** Thrown inside the transaction to roll a `validateOnly` call back. */\nclass ValidateOnly extends Error {\n constructor() {\n super(\"validate only\");\n }\n}\n\n/** Run `write` in one transaction; a `validateOnly` call is rolled back. */\nasync function inTransaction<T>(ctx: EngineContext, validateOnly: boolean, write: (db: MarketplaceDb) => Promise<T>): Promise<T | null> {\n let written: T | null = null;\n try {\n await ctx.ports.transaction(async (db) => {\n written = await write(db);\n if (validateOnly) throw new ValidateOnly();\n });\n } catch (error) {\n if (!(error instanceof ValidateOnly)) throw error;\n }\n return written;\n}\n\nasync function writeIntegration(\n ctx: EngineContext,\n db: MarketplaceDb,\n clientId: string,\n row: IntegrationRowInput,\n now: Date,\n): Promise<MarketplaceIntegrationView | null> {\n if (row.operation === \"archive\" || row.operation === \"unarchive\") {\n await db.marketplaceIntegration.updateMany({\n where: { clientId, provider: row.provider },\n data: { archivedAt: row.operation === \"archive\" ? now : null },\n });\n return null;\n }\n const settings: Omit<IntegrationRowInput, \"operation\"> & { operation?: unknown } = { ...row };\n delete settings.operation;\n return saveMarketplaceIntegration(ctx, { clientId, ...(settings as Omit<SaveMarketplaceIntegrationInput, \"clientId\">) }, db);\n}\n\n/**\n * Create, patch, archive or unarchive many connections at once. A connection\n * is never deleted: archiving is reversible, and each archive and unarchive is\n * an audit line through the host's `audit` port, in the same transaction.\n */\nexport async function upsertIntegrations(\n ctx: EngineContext,\n input: { clientId: string; actorId: string | null; rows: readonly IntegrationRowInput[]; validateOnly?: boolean },\n): Promise<BulkResult<MarketplaceIntegrationView>> {\n const existing = new Set(\n (await listMarketplaceIntegrations(ctx, input.clientId, { includeArchived: true })).map((row) => row.provider),\n );\n const problems = [\n ...duplicates(input.rows, (row) => row.provider, \"integrations\", \"provider\"),\n ...unknownProviders(ctx, input.rows, \"integrations\"),\n ...input.rows.flatMap((row, index) => integrationRowProblems(row, index, existing)),\n ];\n if (problems.length > 0) return { kind: \"refused\", problems };\n\n const validateOnly = input.validateOnly === true;\n const now = ctx.ports.clock.now();\n // The audit lines are written INSIDE the archive's transaction, through its\n // client: an archive never lands without its line, and an audit that fails\n // rolls the archive back. A `validateOnly` call rolls both back.\n await inTransaction(ctx, validateOnly, async (db) => {\n for (const row of input.rows) await writeIntegration(ctx, db, input.clientId, row, now);\n await auditArchives(ctx, db, input, now);\n });\n const providers = input.rows.map((row) => row.provider);\n const rows = validateOnly\n ? []\n : await listMarketplaceIntegrations(ctx, input.clientId, { providers, includeArchived: true });\n return { kind: \"saved\", validateOnly, rows };\n}\n\nasync function auditArchives(\n ctx: EngineContext,\n db: MarketplaceDb,\n input: { clientId: string; actorId: string | null; rows: readonly IntegrationRowInput[] },\n now: Date,\n): Promise<void> {\n for (const row of input.rows) {\n if (row.operation !== \"archive\" && row.operation !== \"unarchive\") continue;\n const entry: MarketplaceAuditEntry = {\n clientId: input.clientId,\n actorId: input.actorId,\n action: row.operation === \"archive\" ? \"marketplace.integration.archive\" : \"marketplace.integration.unarchive\",\n provider: row.provider,\n reason: row.reason ?? null,\n at: now,\n };\n await ctx.ports.audit.record(entry, db);\n }\n}\n\n/** Map or unmap many SKUs at once; every catalog id must be the store's. */\nexport async function upsertMenuLinks(\n ctx: EngineContext,\n input: { clientId: string; rows: readonly MenuLinkRowInput[]; validateOnly?: boolean },\n): Promise<BulkResult<MarketplaceMenuLinkView>> {\n const problems = [\n ...duplicates(input.rows, (row) => `${row.provider}\\u0000${row.externalSku}`, \"links\", \"externalSku\"),\n ...unknownProviders(ctx, input.rows, \"links\"),\n ];\n for (const [index, row] of input.rows.entries()) {\n if (row.menuItemId !== null && !(await ctx.ports.order.catalogHas(input.clientId, row.menuItemId))) {\n problems.push({ path: [\"links\", index, \"menuItemId\"], code: \"CATALOG_ITEM_NOT_FOUND\" });\n }\n }\n if (problems.length > 0) return { kind: \"refused\", problems };\n\n const validateOnly = input.validateOnly === true;\n const written = await inTransaction(ctx, validateOnly, async (db) => {\n const rows: MarketplaceMenuLinkView[] = [];\n for (const row of input.rows) rows.push(await upsertLink(db, { clientId: input.clientId, ...row }));\n return rows;\n });\n return { kind: \"saved\", validateOnly, rows: written ?? [] };\n}\n","import type { AcceptanceStatus, CancellationStatus } from \"./acceptance\";\nimport {\n CLAIM_SELECT,\n NO_STANDING_REQUEST,\n notPendingProblem,\n planCancellation,\n refusalData,\n requestData,\n type CancellationPlan,\n type ClaimRow,\n type DecisionProblem,\n type DecisionProblemCode,\n} from \"./cancellation\";\nimport { requestsFirst, tellCancellationFailed } from \"./cancellation-outcome\";\nimport { enqueueOutbound } from \"./outbound-queue\";\nimport type { EngineContext, MarketplaceAdmission, MarketplaceDb } from \"./ports\";\n\n/**\n * The store's decisions on orders on the clock — ONE path for every surface\n * (the host's board, the admin route, the MCP tool), and all-or-nothing:\n *\n * 1. every decision is validated against its row (still AWAITING, the reason\n * the marketplace's, the offending SKUs the order's) before anything runs;\n * 2. inside ONE transaction the host ADMITS each decision (`order.admit`: the\n * stock ask, the draw) and the engine claims each row on `AWAITING`. A\n * host refusal or a lost claim rolls the whole call back;\n * 3. after the commit, each outbound call is QUEUED FIRST, then the host's\n * half runs (`onAccepted` / `onRefused`). A host half that throws cannot\n * lose the call; it is logged, and the decision stands.\n *\n * A queue that refuses the job loses nothing either: the outbound sweep\n * (`./outbound-sweep.ts`) re-queues every request still owed.\n */\n\n/** The two things a person can do to an order on the clock. */\nexport type AcceptanceDecision = \"ACCEPT\" | \"REJECT\";\n\n/** One decision, as a caller states it. */\nexport type DecisionInput =\n | {\n orderId: string;\n decision: \"ACCEPT\";\n /** What the person confirmed, for the host's admission. */\n admission?: MarketplaceAdmission;\n /** Minutes to prepare, for a marketplace whose confirm states one. */\n preparationMinutes?: number | null;\n }\n | {\n orderId: string;\n decision: \"REJECT\";\n /** One of the marketplace's codes; its first reason when absent. */\n reasonCode?: string | null;\n /** The order's SKUs a reason that `needsItems` names. */\n offendingSkus?: readonly string[];\n };\n\n/**\n * One decided row. `status` is the row's status after the call: ACCEPTED or\n * REJECTED, or — for a refusal of a host that requests first (FUT-4758) —\n * the status it keeps (AWAITING, ACCEPTED) while `cancellation` waits.\n */\nexport interface DecidedRow {\n orderId: string;\n status: AcceptanceStatus;\n cancellation: CancellationStatus | null;\n reasonCode: string | null;\n offendingSkus: string[];\n}\n\n/** What a call did: every row decided, or nothing written and every problem named. */\nexport type DecideManyResult =\n | { kind: \"decided\"; validateOnly: boolean; rows: DecidedRow[] }\n | { kind: \"refused\"; problems: DecisionProblem[] };\n\n/** One decision's result, for a caller deciding one order. */\nexport type DecisionResult =\n | ({ kind: \"decided\" } & DecidedRow)\n | {\n kind: \"stale\";\n /** Why: gone, decided already (I4: answer it as done), expired, or lost to a race. */\n reason: Extract<DecisionProblemCode, \"NOT_FOUND\" | \"ALREADY_DECIDED\" | \"EXPIRED\" | \"CONFLICT\">;\n status: AcceptanceStatus | null;\n }\n | {\n kind: \"invalidReason\";\n problem: Extract<DecisionProblemCode, \"INVALID_REASON\" | \"ITEMS_REQUIRED\" | \"UNKNOWN_ITEM\">;\n validCodes: string[];\n }\n | { kind: \"refusedByHost\"; code: string; message: string; details?: unknown };\n\n/** A planned decision: the row, the claim's data, and what it becomes. */\ninterface PlannedDecision {\n input: DecisionInput;\n index: number;\n row: ClaimRow;\n data: Record<string, unknown>;\n decided: DecidedRow;\n /** A refusal that only REQUESTS the cancellation: the host cancels on the marketplace's confirmation. */\n requestOnly: boolean;\n}\n\n/** Thrown inside the transaction to roll it back, carrying the reason. */\nclass Rollback extends Error {\n constructor(readonly problems: DecisionProblem[] | null) {\n super(\"rollback\");\n }\n}\n\nfunction duplicateProblems(decisions: readonly DecisionInput[]): DecisionProblem[] {\n const seen = new Set<string>();\n return decisions.flatMap((decision, index) => {\n if (!seen.has(decision.orderId)) {\n seen.add(decision.orderId);\n return [];\n }\n return [{ path: [\"decisions\", index, \"orderId\"], code: \"DUPLICATE\" as const }];\n });\n}\n\nfunction decidedOf(input: DecisionInput, plan: CancellationPlan | null, keptStatus?: string): DecidedRow {\n const decided: AcceptanceStatus = input.decision === \"ACCEPT\" ? \"ACCEPTED\" : \"REJECTED\";\n return {\n orderId: input.orderId,\n status: (keptStatus as AcceptanceStatus | undefined) ?? decided,\n cancellation: plan?.status ?? null,\n reasonCode: plan?.reason?.code ?? null,\n offendingSkus: plan?.skus ?? [],\n };\n}\n\n/**\n * The columns of a request that no longer stands, cleared, but for its\n * TOMBSTONE: `cancellation_requested_at` stays, naming the request that was\n * made (FUT-4765, R3-N2).\n *\n * A synchronous marketplace answers a cancellation in the call's response,\n * never by event. When the sweep times a request out while that call is still\n * in flight and the store then accepts the order, the late answer must still\n * find the request it answers: \"cancelled\" means the marketplace cancelled the\n * order, and dropping it would leave the order ACCEPTED here and cancelled\n * there. The outbound job matches a status-less row by this instant\n * (`stampConfirmedCancellation`); nothing else reads it without a status.\n */\nconst CLEARED_REQUEST = {\n cancellationStatus: null,\n cancellationReasonCode: null,\n cancellationOffendingSkus: null,\n cancellationFailureReason: null,\n} as const;\n\n/** Plan one decision against its row, or name what is wrong with it. */\nfunction planOne(\n ctx: EngineContext,\n input: DecisionInput,\n index: number,\n row: ClaimRow | undefined,\n now: Date,\n): PlannedDecision | DecisionProblem[] {\n const path = [\"decisions\", index];\n const stale = notPendingProblem(row, path);\n if (stale || !row) return stale ? [stale] : [];\n if (input.decision === \"ACCEPT\") {\n // An accept after a FAILED request (FUT-4758) leaves no request behind it,\n // only its tombstone (see CLEARED_REQUEST).\n const data = {\n status: \"ACCEPTED\",\n acknowledgedAt: now,\n preparationMinutes: input.preparationMinutes ?? null,\n ...(row.cancellationStatus === null ? {} : CLEARED_REQUEST),\n };\n return { input, index, row, data, decided: decidedOf(input, null), requestOnly: false };\n }\n const plan = planCancellation(ctx.registry.get(row.provider), input, row, path);\n if (Array.isArray(plan)) return plan;\n if (requestOnly(ctx, plan)) {\n return { input, index, row, data: requestData(plan, now), decided: decidedOf(input, plan, row.status), requestOnly: true };\n }\n return { input, index, row, data: refusalData(plan, row.status, now), decided: decidedOf(input, plan), requestOnly: false };\n}\n\n/**\n * Whether a refusal only REQUESTS the cancellation (FUT-4758): the host\n * requests first (it binds `onCancellationConfirmed`), and there is a request\n * to make — PENDING, or FAILED at once for a marketplace that cannot take it\n * through its API (a person cancels in its app, and its event confirms). A\n * provider with no adapter has nothing to ask: refused at once, as ever.\n */\nfunction requestOnly(ctx: EngineContext, plan: CancellationPlan): boolean {\n return requestsFirst(ctx) && plan.status !== null;\n}\n\n/** Admit every decision through the host, then claim every row, in one transaction. */\nasync function admitAndClaim(\n ctx: EngineContext,\n clientId: string,\n planned: readonly PlannedDecision[],\n validateOnly: boolean,\n): Promise<void> {\n await ctx.ports.transaction(async (tx: MarketplaceDb) => {\n const refused: DecisionProblem[] = [];\n for (const one of planned) {\n const admission = one.input.decision === \"ACCEPT\" ? (one.input.admission ?? {}) : {};\n const answer = await ctx.ports.order.admit({\n clientId,\n orderId: one.input.orderId,\n decision: one.input.decision,\n admission,\n db: tx,\n });\n if (!answer.admitted) {\n const host = { code: answer.code, message: answer.message, details: answer.details };\n refused.push({ path: [\"decisions\", one.index], code: \"HOST_REFUSED\", host });\n }\n }\n if (refused.length > 0) throw new Rollback(refused);\n for (const one of planned) {\n const claimed = await tx.marketplaceAcceptance.updateMany({\n where: { orderId: one.input.orderId, clientId, status: \"AWAITING\", ...NO_STANDING_REQUEST },\n data: one.data,\n });\n if (claimed.count === 0) refused.push({ path: [\"decisions\", one.index, \"orderId\"], code: \"CONFLICT\" });\n }\n if (refused.length > 0) throw new Rollback(refused);\n if (validateOnly) throw new Rollback(null);\n });\n}\n\n/** After the commit: queue each owed call FIRST, then the host's half, which may not lose it. */\nasync function afterCommit(ctx: EngineContext, clientId: string, planned: readonly PlannedDecision[]): Promise<void> {\n for (const one of planned) {\n const { orderId } = one.input;\n if (one.input.decision === \"ACCEPT\") {\n await enqueueOutbound(ctx, { clientId, orderId, action: \"confirm\" }, one.row.provider);\n } else if (one.decided.cancellation === \"PENDING\") {\n await enqueueOutbound(ctx, { clientId, orderId, action: \"requestCancellation\" }, one.row.provider);\n }\n try {\n if (one.decided.status === \"ACCEPTED\" && one.input.decision === \"ACCEPT\") await ctx.ports.order.onAccepted(clientId, orderId);\n else if (!one.requestOnly) await ctx.ports.order.onRefused(clientId, orderId, \"REJECTED\");\n // A request the marketplace cannot take through its API failed at once:\n // the order stays, and a person cancels it in the marketplace's app.\n else if (one.decided.cancellation === \"FAILED\") await tellCancellationFailed(ctx, clientId, orderId, \"REFUSED\");\n } catch (error) {\n ctx.ports.logger.error(\n `marketplace.decide: order ${orderId} is ${one.decided.status} but the host's half failed: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n }\n ctx.ports.publishChanged(clientId);\n}\n\n/** Read every row a call names, in one statement. */\nasync function readRows(ctx: EngineContext, clientId: string, orderIds: string[]): Promise<Map<string, ClaimRow>> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceAcceptance.findMany({\n where: { clientId, orderId: { in: orderIds } },\n select: CLAIM_SELECT,\n })) as ClaimRow[];\n return new Map(rows.map((row) => [row.orderId, row]));\n}\n\n/**\n * Decide many orders at once, all-or-nothing. `validateOnly` runs everything —\n * the host's admission included — and rolls it back.\n */\nexport async function decideMany(\n ctx: EngineContext,\n input: { clientId: string; decisions: readonly DecisionInput[]; validateOnly?: boolean; now?: Date },\n): Promise<DecideManyResult> {\n const duplicates = duplicateProblems(input.decisions);\n if (duplicates.length > 0) return { kind: \"refused\", problems: duplicates };\n const now = input.now ?? ctx.ports.clock.now();\n const rows = await readRows(ctx, input.clientId, input.decisions.map((decision) => decision.orderId));\n\n const planned: PlannedDecision[] = [];\n const problems: DecisionProblem[] = [];\n input.decisions.forEach((decision, index) => {\n const plan = planOne(ctx, decision, index, rows.get(decision.orderId), now);\n if (Array.isArray(plan)) problems.push(...plan);\n else planned.push(plan);\n });\n if (problems.length > 0) return { kind: \"refused\", problems };\n\n const validateOnly = input.validateOnly === true;\n try {\n await admitAndClaim(ctx, input.clientId, planned, validateOnly);\n } catch (error) {\n if (!(error instanceof Rollback)) throw error;\n if (error.problems) return { kind: \"refused\", problems: error.problems };\n }\n if (!validateOnly) await afterCommit(ctx, input.clientId, planned);\n return { kind: \"decided\", validateOnly, rows: planned.map((one) => one.decided) };\n}\n\nconst STALE_CODES = new Set<DecisionProblemCode>([\"NOT_FOUND\", \"ALREADY_DECIDED\", \"EXPIRED\", \"CONFLICT\"]);\n\n/** One decision's problem, as the single-order result names it. */\nfunction resultOfProblem(problem: DecisionProblem): DecisionResult {\n if (problem.code === \"HOST_REFUSED\") {\n const host = problem.host ?? { code: \"\", message: \"\" };\n return { kind: \"refusedByHost\", code: host.code, message: host.message, details: host.details };\n }\n if (STALE_CODES.has(problem.code)) {\n const reason = problem.code as Extract<DecisionResult, { kind: \"stale\" }>[\"reason\"];\n return { kind: \"stale\", reason, status: problem.status ?? null };\n }\n const invalid = problem.code as Extract<DecisionResult, { kind: \"invalidReason\" }>[\"problem\"];\n return { kind: \"invalidReason\", problem: invalid, validCodes: problem.validCodes ?? [] };\n}\n\n/** Decide ONE order: `decideMany` with one decision. */\nexport async function decideOne(\n ctx: EngineContext,\n input: { clientId: string; now?: Date } & DecisionInput,\n): Promise<DecisionResult> {\n const { clientId, now, ...decision } = input;\n const result = await decideMany(ctx, { clientId, decisions: [decision as DecisionInput], now });\n if (result.kind === \"decided\") {\n const [row] = result.rows;\n if (row) return { kind: \"decided\", ...row };\n }\n const [problem] = result.kind === \"refused\" ? result.problems : [];\n return problem ? resultOfProblem(problem) : { kind: \"stale\", reason: \"CONFLICT\", status: null };\n}\n\n/**\n * The STORE asks to cancel an order — before or after accepting it. Stamps\n * the request the marketplace must hear and queues it; the engine neither\n * admits nor calls `onRefused`: it records and queues, and nothing else.\n *\n * REQUEST FIRST (FUT-4758), for a host that binds `onCancellationConfirmed`:\n * only the request moves. The decision status stays AWAITING or ACCEPTED while\n * the marketplace answers, so the host keeps the order as it was until then,\n * and a refused or timed-out request (`onCancellationFailed`) leaves it\n * acceptable. The marketplace's confirmation moves it to REJECTED. A FAILED\n * request may be asked again. A host that binds no `onCancellationConfirmed`\n * cancelled first and gets 1.0.0's stamps exactly: REJECTED at once.\n *\n * The returned row's `status` is the row's after the call.\n *\n * `stale` (ALREADY_DECIDED) when the marketplace already cancelled it, the\n * clock lapsed (EXPIRED), or a request is already waiting.\n */\nexport async function recordStoreCancellation(\n ctx: EngineContext,\n input: { clientId: string; orderId: string; reasonCode?: string | null; offendingSkus?: readonly string[]; now?: Date },\n): Promise<DecisionResult> {\n const row = (await readRows(ctx, input.clientId, [input.orderId])).get(input.orderId);\n const stale = notPendingProblem(row, [], [\"AWAITING\", \"ACCEPTED\"]);\n if (stale || !row) return stale ? resultOfProblem(stale) : { kind: \"stale\", reason: \"NOT_FOUND\", status: null };\n const plan = planCancellation(ctx.registry.get(row.provider), input, row, []);\n if (Array.isArray(plan)) return resultOfProblem(plan[0]!);\n\n return claimStoreCancellation(ctx, input, row, plan);\n}\n\n/** Stamp the store's cancellation (the request alone, or 1.0.0's REJECTED), queue it, and tell the host. */\nasync function claimStoreCancellation(\n ctx: EngineContext,\n input: { clientId: string; orderId: string; now?: Date },\n row: ClaimRow,\n plan: CancellationPlan,\n): Promise<DecisionResult> {\n const now = input.now ?? ctx.ports.clock.now();\n const db = await ctx.ports.db();\n const only = requestOnly(ctx, plan);\n const claimed = await db.marketplaceAcceptance.updateMany({\n where: { orderId: input.orderId, clientId: input.clientId, status: row.status, ...NO_STANDING_REQUEST },\n data: only ? requestData(plan, now) : refusalData(plan, row.status, now),\n });\n if (claimed.count === 0) return { kind: \"stale\", reason: \"CONFLICT\", status: null };\n if (plan.status === \"PENDING\") {\n await enqueueOutbound(ctx, { clientId: input.clientId, orderId: input.orderId, action: \"requestCancellation\" }, row.provider);\n }\n ctx.ports.publishChanged(input.clientId);\n if (only && plan.status === \"FAILED\") await tellCancellationFailed(ctx, input.clientId, input.orderId, \"REFUSED\");\n return { kind: \"decided\", ...decidedOf({ orderId: input.orderId, decision: \"REJECT\" }, plan, only ? row.status : undefined) };\n}\n","import { cancelAcceptance } from \"./acceptance\";\nimport { failCancellationRequest } from \"./cancellation\";\nimport { awaitOrderBody, merchantMismatch, requeueOwedFetch } from \"./fetch-order\";\nimport { deferInboxEvent, recordInboxEvent, settleInboxEvent } from \"./inbox\";\nimport { ingestMarketplaceOrder, type IngestSettings } from \"./ingest\";\nimport { connectionMerchantId, resolveIngestionTarget } from \"./integration\";\nimport { markCancelledBeforeIngest } from \"./order-fetch-marks\";\nimport type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from \"./types\";\n\n/**\n * One delivery, start to finish: normalize → inbox → ingest.\n *\n * The ONE path both producers use. The webhook calls it, and so does the\n * reconciliation retry sweep — which is the whole reason it is a module rather\n * than the body of a route handler. Two producers with two copies of this\n * sequence is how a webhook and a poll come to disagree about what an order is,\n * and the disagreement only shows up on the orders that took the unlucky path.\n */\n\n/**\n * Normalize a raw payload through the provider's adapter, or null when no\n * adapter is registered for it or the adapter refuses the payload. The\n * registry is the only dispatch: there is no provider branch here.\n */\nexport function normalizeEvent(\n ctx: EngineContext,\n provider: MarketplaceProvider,\n payload: unknown,\n): NormalizedEvent | null {\n return ctx.registry.get(provider)?.normalize(payload) ?? null;\n}\n\n/** How a delivery ended. `duplicate` and `ignored` are both ordinary outcomes. */\nexport type DeliveryOutcome =\n | { kind: \"ingested\"; orderId: string; unmappedSkus: string[] }\n | { kind: \"cancelled\" }\n | { kind: \"cancellationFailed\" }\n /** Recorded; the order body is fetched by the `marketplace.fetch-order` job. */\n | { kind: \"awaitingOrder\" }\n | { kind: \"duplicate\" }\n | { kind: \"ignored\"; reason: string }\n | { kind: \"failed\"; reason: string };\n\n/**\n * Process one delivery for one tenant.\n *\n * NEVER throws. Every failure is caught, recorded on the inbox row, and\n * returned — because the caller is a webhook handler whose answer decides\n * whether the marketplace redelivers, and a 500 out of here would make an\n * ingestion bug indistinguishable from a network one while multiplying the\n * traffic that hits it.\n *\n * The delivery is recorded BEFORE it is processed. That ordering is the durable\n * part of the durable inbox: a process that dies mid-ingest leaves a PENDING\n * row the sweep will retry, whereas processing first and recording after loses\n * the event entirely on exactly the crashes worth surviving.\n */\nexport async function processDelivery(\n ctx: EngineContext,\n input: {\n clientId: string | null;\n event: NormalizedEvent;\n payload: unknown;\n settings: IngestSettings | null;\n now?: Date;\n },\n): Promise<DeliveryOutcome> {\n const { clientId, event, settings } = input;\n const record = await recordInboxEvent(ctx, { clientId, event, payload: input.payload });\n if (!record.fresh) return { kind: \"duplicate\" };\n\n if (!clientId || !settings) {\n // Stored, not dropped, and the two reasons are kept apart because only one\n // of them is a problem. An order naming a merchant no tenant claims is the\n // loudest possible symptom of a half-finished onboarding, and it is only\n // findable later because the row survived. An order for a store that has\n // simply switched the channel off is not a fault at all — it stays PENDING\n // for the retry sweep to pick up if the store switches it back on.\n const reason = clientId ? \"integration is not enabled\" : \"no tenant claims this merchant\";\n if (clientId) await deferInboxEvent(ctx, record.id, reason);\n else await settleInboxEvent(ctx, record.id, \"IGNORED\", reason);\n return { kind: \"ignored\", reason };\n }\n\n try {\n return await applyEvent(ctx, record.id, clientId, event, settings, input.now);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n await settleInboxEvent(ctx, record.id, \"FAILED\", reason);\n return { kind: \"failed\", reason };\n }\n}\n\n/** The event names an order whose body the marketplace serves apart (`orderToFetch`). */\nfunction announcesOrderToFetch(event: NormalizedEvent): boolean {\n return event.order === null && event.orderToFetch === true && event.externalOrderId !== null;\n}\n\n/**\n * Why an order the event CARRIES must not be ingested for this store: it names\n * another merchant than the connection's (a wrong webhook URL, a replay), the\n * rule a fetched order is held to. Read only for an order that names its\n * merchant (an adapter that sets `externalMerchantId` on the order); an order\n * that names none costs no read.\n */\nasync function carriedOrderMismatch(\n ctx: EngineContext,\n clientId: string,\n order: NormalizedMarketplaceOrder,\n): Promise<string | null> {\n if (!order.externalMerchantId) return null;\n // The one column, never the whole target: no credentials opened per order.\n return merchantMismatch(order, await connectionMerchantId(ctx, clientId, order.provider));\n}\n\n/**\n * Act on one recorded delivery: cancel, ingest, or deliberately nothing.\n *\n * Extracted so both producers share the ACTION as well as the recording — the\n * webhook and the retry sweep differ only in how they arrived here and in what\n * they do with a throw, never in what an event MEANS.\n */\nasync function applyEvent(\n ctx: EngineContext,\n inboxId: string,\n clientId: string,\n event: NormalizedEvent,\n settings: IngestSettings,\n now: Date | undefined,\n): Promise<DeliveryOutcome> {\n const outcome = event.cancellationOutcome ?? (event.cancelled ? \"CONFIRMED\" : null);\n if (outcome === \"FAILED\" && event.externalOrderId) {\n // The marketplace refused the store's own cancellation request. Understood\n // and recorded, never IGNORED: it is what tells a person to finish the\n // cancellation on the marketplace's side.\n await failCancellationRequest(ctx, {\n clientId,\n provider: event.provider,\n externalOrderId: event.externalOrderId,\n });\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n return { kind: \"cancellationFailed\" };\n }\n\n if (event.cancelled && event.externalOrderId) {\n const order = { clientId, provider: event.provider, externalOrderId: event.externalOrderId };\n // A cancellation that outran a fetched order's body leaves its marker, so\n // the fetch that follows ingests nothing.\n if (!(await cancelAcceptance(ctx, { ...order, now }))) await markCancelledBeforeIngest(ctx, order);\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n return { kind: \"cancelled\" };\n }\n\n if (announcesOrderToFetch(event)) {\n // The event announces an order whose body the marketplace serves apart.\n // Fetching is a call to the marketplace, so it is a job's, never this\n // request's: the row waits PENDING and the fetch is queued.\n await awaitOrderBody(ctx, clientId, inboxId);\n return { kind: \"awaitingOrder\" };\n }\n\n if (!event.order) {\n // An event type this ingestion does not act on. Marketplaces emit a wide\n // stream (dispatched, concluded, driver assigned…) and most of it is not an\n // order; IGNORED says \"understood, nothing to do\" and keeps it out of the\n // retry sweep, which FAILED would not.\n const reason = `no order body on ${event.eventType}`;\n await settleInboxEvent(ctx, inboxId, \"IGNORED\", reason);\n return { kind: \"ignored\", reason };\n }\n\n return ingestCarried(ctx, inboxId, clientId, event.order, settings, now);\n}\n\n/** Ingest the order an event carries, unless it names another merchant than the connection's. */\nasync function ingestCarried(\n ctx: EngineContext,\n inboxId: string,\n clientId: string,\n order: NormalizedMarketplaceOrder,\n settings: IngestSettings,\n now: Date | undefined,\n): Promise<DeliveryOutcome> {\n const mismatch = await carriedOrderMismatch(ctx, clientId, order);\n if (mismatch) {\n // FAILED, so the reconciliation sweep retries it once the connection's\n // merchant id is corrected, within the inbox's attempt bound.\n await settleInboxEvent(ctx, inboxId, \"FAILED\", mismatch);\n ctx.ports.logger.error(`marketplace.ingest: inbox row ${inboxId} refused: ${mismatch}`);\n return { kind: \"failed\", reason: mismatch };\n }\n const result = await ingestMarketplaceOrder(ctx, { clientId, order, settings, now });\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n return { kind: \"ingested\", orderId: result.orderId, unmappedSkus: result.unmappedSkus };\n}\n\n/**\n * Re-run a delivery already sitting in the inbox.\n *\n * Used by the retry sweep. It re-reads the store's CURRENT settings rather than\n * whatever they were when the event first arrived — a store that connected the\n * channel properly an hour after the first order came in should have that order\n * ingested on the retry, which is the case this exists for.\n */\nexport async function reprocessStoredDelivery(\n ctx: EngineContext,\n input: { id: string; clientId: string; provider: MarketplaceProvider; payload: unknown; receivedAt?: Date | null },\n): Promise<DeliveryOutcome> {\n const event = normalizeEvent(ctx, input.provider, input.payload);\n if (!event) {\n const reason = \"payload no longer normalizes\";\n await settleInboxEvent(ctx, input.id, \"IGNORED\", reason);\n return { kind: \"ignored\", reason };\n }\n const target = await resolveIngestionTarget(ctx, input.clientId, input.provider);\n if (!target?.enabled) {\n // Still not ready. Deferred rather than settled, for the same reason as on\n // arrival — and the attempt counter is what eventually retires it, so a\n // store that never switches the channel on does not have its inbox re-read\n // forever.\n const reason = \"integration is not enabled\";\n await deferInboxEvent(ctx, input.id, reason);\n return { kind: \"ignored\", reason };\n }\n // A row waiting for its order body is the fetch job's: re-queued, never fetched here.\n if (announcesOrderToFetch(event)) return requeueOwedFetch(ctx, input);\n try {\n return await applyEvent(\n ctx,\n input.id,\n input.clientId,\n event,\n { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds },\n undefined,\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n await settleInboxEvent(ctx, input.id, \"FAILED\", reason);\n return { kind: \"failed\", reason };\n }\n}\n","import type { AcceptanceStatus, CancellationStatus } from \"./acceptance\";\nimport type { CancellationFailureReason, EngineContext } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * What the host's order reads need to draw a marketplace order: where its\n * aceite and its cancellation request stand, and where a person goes when the\n * API could not do it. One read for a batch, so a list stays one statement.\n */\nexport interface MarketplaceOrderState {\n orderId: string;\n provider: MarketplaceProvider;\n externalOrderId: string;\n externalDisplayId: string | null;\n status: AcceptanceStatus;\n confirmedAt: Date | null;\n confirmFailedAt: Date | null;\n cancellation: CancellationStatus | null;\n cancellationReasonCode: string | null;\n /** Why the request FAILED (REFUSED or TIMEOUT); null unless `cancellation` is FAILED, and on rows from before it. */\n cancellationFailure: CancellationFailureReason | null;\n /** The adapter's app link, or null when no adapter is registered for it. */\n appUrl: string | null;\n}\n\ninterface StateRow {\n orderId: string;\n provider: string;\n externalOrderId: string;\n externalDisplayId: string | null;\n status: string;\n confirmedAt: Date | null;\n confirmFailedAt: Date | null;\n cancellationStatus: string | null;\n cancellationReasonCode: string | null;\n cancellationFailureReason: string | null;\n}\n\n/** The state of each of these orders that is a marketplace order, keyed by id. */\nexport async function readOrderStates(\n ctx: EngineContext,\n clientId: string,\n orderIds: readonly string[],\n): Promise<Map<string, MarketplaceOrderState>> {\n if (orderIds.length === 0) return new Map();\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceAcceptance.findMany({\n where: { clientId, orderId: { in: [...orderIds] } },\n select: {\n orderId: true,\n provider: true,\n externalOrderId: true,\n externalDisplayId: true,\n status: true,\n confirmedAt: true,\n confirmFailedAt: true,\n cancellationStatus: true,\n cancellationReasonCode: true,\n cancellationFailureReason: true,\n },\n })) as StateRow[];\n return new Map(\n rows.map((row) => {\n const adapter = ctx.registry.get(row.provider);\n const state: MarketplaceOrderState = {\n orderId: row.orderId,\n provider: row.provider,\n externalOrderId: row.externalOrderId,\n externalDisplayId: row.externalDisplayId,\n status: row.status as AcceptanceStatus,\n confirmedAt: row.confirmedAt,\n confirmFailedAt: row.confirmFailedAt,\n cancellation: row.cancellationStatus as CancellationStatus | null,\n cancellationReasonCode: row.cancellationReasonCode,\n cancellationFailure: row.cancellationFailureReason as CancellationFailureReason | null,\n appUrl: adapter ? adapter.appLink(row) : null,\n };\n return [row.orderId, state];\n }),\n );\n}\n","import {\n cancelAcceptance,\n expireLapsedAcceptances,\n listPendingAcceptances,\n type ExpirySweepResult,\n type PendingAcceptance,\n} from \"./acceptance\";\nimport {\n upsertIntegrations,\n upsertMenuLinks,\n type BulkResult,\n type IntegrationRowInput,\n type MenuLinkRowInput,\n} from \"./bulk\";\nimport {\n decideMany,\n decideOne,\n recordStoreCancellation,\n type DecideManyResult,\n type DecisionInput,\n type DecisionResult,\n} from \"./decisions\";\nimport {\n runFetchOrder,\n type FetchOrderJobPayload,\n type FetchOrderOutcome,\n} from \"./fetch-order\";\nimport { sweepOutbound, type OutboundSweepResult } from \"./outbound-sweep\";\nimport type {\n AdapterTokenCache,\n CancellationReason,\n MarketplaceAdapter,\n OutboundOrderRef,\n} from \"./adapter\";\nimport { listRetryableInboxEvents, type PendingInboxEvent } from \"./inbox\";\nimport { ingestMarketplaceOrder, type IngestResult, type IngestSettings } from \"./ingest\";\nimport {\n listMarketplaceIntegrations,\n resolveIngestionTarget,\n resolveTenantByMerchant,\n saveMarketplaceIntegration,\n type IngestionTarget,\n type MarketplaceIntegrationView,\n type SaveMarketplaceIntegrationInput,\n} from \"./integration\";\nimport { listMarketplaceMenuLinks, type MarketplaceMenuLinkView } from \"./menu-links\";\nimport { runOutbound, type OutboundAttempt, type OutboundOutcome } from \"./outbound\";\nimport type { OutboundJobPayload } from \"./outbound-queue\";\nimport {\n normalizeEvent,\n processDelivery,\n reprocessStoredDelivery,\n type DeliveryOutcome,\n} from \"./pipeline\";\nimport type { EngineContext, MarketplaceEngineConfig } from \"./ports\";\nimport { createAdapterRegistry, suggestReason } from \"./registry\";\nimport { readOrderStates, type MarketplaceOrderState } from \"./state\";\nimport type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from \"./types\";\n\n/** Everything the mounted engine can do, with the ports and adapters bound in. */\nexport interface MarketplaceEngine {\n /** Every registered marketplace, in registration order. */\n providers(): readonly MarketplaceProvider[];\n /** Whether a provider id (a URL segment, a body field) names a registered adapter. */\n knows(provider: string): provider is MarketplaceProvider;\n /** The adapter itself: its capabilities, reasons and app link. Null when unknown. */\n adapter(provider: string): MarketplaceAdapter | null;\n /** The marketplace's reasons, static and offline. Empty when unknown. */\n reasons(provider: string): readonly CancellationReason[];\n /** The reason a host preselects, given whether the order is short of an item. */\n suggestReason(provider: string, input: { itemUnavailable: boolean }): CancellationReason | null;\n /** Where a person goes to act on the marketplace's side. Null when unknown. */\n appLink(provider: string, order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string | null;\n\n /** Turn a raw payload into the canonical shape, or null if nothing does. */\n normalize(provider: string, payload: unknown): NormalizedEvent | null;\n /** Read the provider's signature header off a request. */\n readSignature(provider: string, header: (name: string) => string | null): string | null;\n /** Verify a delivery. An unknown provider is never verified, so never accepted. */\n verifySignature(provider: string, rawBody: string, signature: string | null, secret: string | null): boolean;\n /** Which tenant a delivery belongs to, from the merchant id it names. */\n tenantFor(provider: MarketplaceProvider, externalMerchantId: string): Promise<string | null>;\n /** The connection behind one (tenant, marketplace), for the ingestion path. */\n target(clientId: string, provider: MarketplaceProvider): Promise<IngestionTarget | null>;\n /** Ingest ONE already-normalized order, bypassing the inbox. Idempotent. */\n ingest(input: {\n clientId: string;\n order: NormalizedMarketplaceOrder;\n settings: IngestSettings;\n now?: Date;\n }): Promise<IngestResult>;\n /** Record and act on one delivery. Never throws. */\n deliver(input: {\n clientId: string | null;\n event: NormalizedEvent;\n payload: unknown;\n settings: IngestSettings | null;\n now?: Date;\n }): Promise<DeliveryOutcome>;\n\n /** This store's connections, secrets withheld; archived ones only when asked. */\n integrations(\n clientId: string,\n options?: { providers?: readonly string[]; includeArchived?: boolean },\n ): Promise<MarketplaceIntegrationView[]>;\n /** Create or patch ONE connection (the bulk call's single-row form, with no audit). */\n saveIntegration(input: SaveMarketplaceIntegrationInput): Promise<MarketplaceIntegrationView>;\n /** Create, patch, archive or unarchive many connections, all-or-nothing. */\n upsertIntegrations(input: {\n clientId: string;\n actorId: string | null;\n rows: readonly IntegrationRowInput[];\n validateOnly?: boolean;\n }): Promise<BulkResult<MarketplaceIntegrationView>>;\n\n /** The SKU map. `unmappedOnly` is the store's attention list; `ids` narrows. */\n menuLinks(input: {\n clientId: string;\n provider?: MarketplaceProvider;\n unmappedOnly?: boolean;\n ids?: readonly string[];\n }): Promise<MarketplaceMenuLinkView[]>;\n /** Map or unmap many SKUs, all-or-nothing. */\n upsertMenuLinks(input: {\n clientId: string;\n rows: readonly MenuLinkRowInput[];\n validateOnly?: boolean;\n }): Promise<BulkResult<MarketplaceMenuLinkView>>;\n /** Map or unmap ONE SKU. `null` = the catalog id is not this tenant's. */\n setMenuLink(input: { clientId: string } & MenuLinkRowInput): Promise<MarketplaceMenuLinkView | null>;\n\n /** Orders still on the clock, soonest deadline first; `orderIds` narrows. */\n pending(clientId: string, orderIds?: readonly string[]): Promise<PendingAcceptance[]>;\n /** Decide many orders, all-or-nothing, the host admitting each inside the claim's transaction. */\n decideMany(input: {\n clientId: string;\n decisions: readonly DecisionInput[];\n validateOnly?: boolean;\n now?: Date;\n }): Promise<DecideManyResult>;\n /** Decide ONE order (`decideMany` with one decision). */\n decide(input: { clientId: string; now?: Date } & DecisionInput): Promise<DecisionResult>;\n /** The store cancelled through the host's own cancel: stamp and queue the request. */\n recordStoreCancellation(input: {\n clientId: string;\n orderId: string;\n reasonCode?: string | null;\n offendingSkus?: readonly string[];\n now?: Date;\n }): Promise<DecisionResult>;\n /** The marketplace cancelled an order we already have. */\n cancel(input: {\n clientId: string;\n provider: MarketplaceProvider;\n externalOrderId: string;\n now?: Date;\n }): Promise<boolean>;\n /** Where each of these orders' acceptance and cancellation stand. */\n orderStates(clientId: string, orderIds: readonly string[]): Promise<Map<string, MarketplaceOrderState>>;\n\n /** Expire every order whose deadline has passed, across all tenants. */\n expireLapsed(now?: Date): Promise<ExpirySweepResult>;\n /** Deliveries recorded but never processed, oldest first. */\n retryable(): Promise<PendingInboxEvent[]>;\n /** Re-run one stored delivery against the store's CURRENT settings. */\n reprocess(event: PendingInboxEvent): Promise<DeliveryOutcome>;\n /** Re-queue every outbound call still owed (the `marketplace.outbound-sweep` job's body). */\n sweepOutbound(now?: Date): Promise<OutboundSweepResult>;\n /** Run one queued outbound call (the `marketplace.outbound` job's body). */\n runOutbound(payload: OutboundJobPayload, attempt: OutboundAttempt): Promise<OutboundOutcome>;\n /** Fetch and ingest one announced order (the `marketplace.fetch-order` job's body). */\n runFetchOrder(payload: FetchOrderJobPayload, attempt: OutboundAttempt): Promise<FetchOrderOutcome>;\n}\n\n/**\n * Mount the engine onto a host.\n *\n * Every port is REQUIRED and there are no defaults: a default would let a\n * second host silently inherit the first one's answers. The adapter list is\n * validated here (`createAdapterRegistry`), so a malformed adapter fails at\n * boot rather than on the first order it would have mangled.\n */\nexport function createMarketplaceEngine(config: MarketplaceEngineConfig): MarketplaceEngine {\n const { adapters, ...ports } = config;\n const registry = createAdapterRegistry(adapters);\n const tokens: AdapterTokenCache = new Map();\n const ctx: EngineContext = { ports, registry, tokens };\n\n return {\n providers: () => registry.providers(),\n knows: (provider): provider is MarketplaceProvider => registry.has(provider),\n adapter: (provider) => registry.get(provider),\n reasons: (provider) => registry.get(provider)?.cancellationReasons() ?? [],\n suggestReason: (provider, input) => {\n const adapter = registry.get(provider);\n return adapter ? suggestReason(adapter, input) : null;\n },\n appLink: (provider, order) => registry.get(provider)?.appLink(order) ?? null,\n\n normalize: (provider, payload) => normalizeEvent(ctx, provider, payload),\n readSignature: (provider, header) => registry.get(provider)?.readSignature(header) ?? null,\n // An unknown provider cannot be verified, so it is not accepted: trusting\n // what cannot be checked is how an unsigned endpoint ships by omission.\n verifySignature: (provider, rawBody, signature, secret) =>\n registry.get(provider)?.verifySignature(rawBody, signature, secret) ?? false,\n tenantFor: (provider, externalMerchantId) =>\n resolveTenantByMerchant(ctx, provider, externalMerchantId),\n target: (clientId, provider) => resolveIngestionTarget(ctx, clientId, provider),\n ingest: (input) => ingestMarketplaceOrder(ctx, input),\n deliver: (input) => processDelivery(ctx, input),\n\n integrations: (clientId, options) => listMarketplaceIntegrations(ctx, clientId, options),\n saveIntegration: async (input) => saveMarketplaceIntegration(ctx, input, await ports.db()),\n upsertIntegrations: (input) => upsertIntegrations(ctx, input),\n\n menuLinks: (input) => listMarketplaceMenuLinks(ctx, input),\n upsertMenuLinks: (input) => upsertMenuLinks(ctx, input),\n setMenuLink: async ({ clientId, ...row }) => {\n const result = await upsertMenuLinks(ctx, { clientId, rows: [row] });\n return result.kind === \"saved\" ? (result.rows[0] ?? null) : null;\n },\n\n pending: (clientId, orderIds) => listPendingAcceptances(ctx, clientId, orderIds),\n decideMany: (input) => decideMany(ctx, input),\n decide: (input) => decideOne(ctx, input),\n recordStoreCancellation: (input) => recordStoreCancellation(ctx, input),\n cancel: (input) => cancelAcceptance(ctx, input),\n orderStates: (clientId, orderIds) => readOrderStates(ctx, clientId, orderIds),\n\n expireLapsed: (now) => expireLapsedAcceptances(ctx, now ?? ports.clock.now()),\n retryable: () => listRetryableInboxEvents(ctx),\n reprocess: (event) => reprocessStoredDelivery(ctx, event),\n sweepOutbound: (now) => sweepOutbound(ctx, now ?? ports.clock.now()),\n runOutbound: (payload, attempt) => runOutbound(ctx, payload, attempt),\n runFetchOrder: (payload, attempt) => runFetchOrder(ctx, payload, attempt),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAS,WAAc,MAAoB,OAA2B,MAAc,OAA8B;AAChH,QAAM,OAAO,oBAAI,IAAY;AAC7B,SAAO,KAAK,QAAQ,CAAC,KAAK,UAAU;AAClC,UAAM,MAAM,MAAM,GAAG;AACrB,QAAI,CAAC,KAAK,IAAI,GAAG,GAAG;AAClB,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,E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UAAU,MAAM,CAAC,GAAG,EAAE,CAAC;AACnE,aAAO,OAAO,SAAS,UAAW,OAAO,KAAK,CAAC,KAAK,OAAQ;AAAA,IAC9D,GAHa;AAAA,IAKb,SAAS,wBAAC,UAAU,aAAa,uBAAuB,KAAK,UAAU,QAAQ,GAAtE;AAAA,IACT,YAAY,wBAAC,UAAU,WAAW,KAAK,KAAK,GAAhC;AAAA,IACZ,QAAQ,wBAAC,UAAU,UAAU,KAAK,KAAK,GAA/B;AAAA,IACR,yBAAyB,wBAAC,UAAU,wBAAwB,KAAK,KAAK,GAA7C;AAAA,IACzB,QAAQ,wBAAC,UAAU,iBAAiB,KAAK,KAAK,GAAtC;AAAA,IACR,aAAa,wBAAC,UAAU,aAAa,gBAAgB,KAAK,UAAU,QAAQ,GAA/D;AAAA,IAEb,cAAc,wBAAC,QAAQ,wBAAwB,KAAK,OAAO,MAAM,MAAM,IAAI,CAAC,GAA9D;AAAA,IACd,WAAW,6BAAM,yBAAyB,GAAG,GAAlC;AAAA,IACX,WAAW,wBAAC,UAAU,wBAAwB,KAAK,KAAK,GAA7C;AAAA,IACX,eAAe,wBAAC,QAAQ,cAAc,KAAK,OAAO,MAAM,MAAM,IAAI,CAAC,GAApD;AAAA,IACf,aAAa,wBAAC,SAAS,YAAY,YAAY,KAAK,SAAS,OAAO,GAAvD;AAAA,IACb,eAAe,wBAAC,SAAS,YAAY,cAAc,KAAK,SAAS,OAAO,GAAzD;AAAA,EACjB;AACF;AAtDgB;","names":["duplicates"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { W as OutboundJobPayload, F as FetchOrderJobPayload } from '../engine-D-a4mttc.js';
|
|
2
2
|
import * as _12_apps_wiring from '@12-apps/wiring';
|
|
3
3
|
import { createApiMarketplace, MarketplaceJobDeps } from '../server/index.js';
|
|
4
|
-
import '../adapter-
|
|
4
|
+
import '../adapter-_iuSxvVD.js';
|
|
5
5
|
import 'zod';
|
|
6
6
|
|
|
7
7
|
declare const marketplaceServerManifest: {
|
|
@@ -15,6 +15,7 @@ declare const marketplaceServerManifest: {
|
|
|
15
15
|
readonly "expire-acceptances": _12_apps_wiring.WireJobBlueprint<void, MarketplaceJobDeps>;
|
|
16
16
|
readonly "reconcile-inbox": _12_apps_wiring.WireJobBlueprint<void, MarketplaceJobDeps>;
|
|
17
17
|
readonly outbound: _12_apps_wiring.WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps>;
|
|
18
|
+
readonly "fetch-order": _12_apps_wiring.WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps>;
|
|
18
19
|
readonly "outbound-sweep": _12_apps_wiring.WireJobBlueprint<void, MarketplaceJobDeps>;
|
|
19
20
|
};
|
|
20
21
|
};
|
package/dist/manifest/server.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
MARKETPLACE_JOBS,
|
|
3
3
|
createApiMarketplace
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-CRYFYDQ2.js";
|
|
5
5
|
import "../chunk-UYFYGGCS.js";
|
|
6
|
-
import "../chunk-
|
|
6
|
+
import "../chunk-D2X7TOR6.js";
|
|
7
7
|
import "../chunk-7QVYU63E.js";
|
|
8
8
|
|
|
9
9
|
// src/manifest/server.ts
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** The Rappi adapter's en-US pack: the same reasons, in English. */
|
|
2
|
+
declare const RAPPI_ADAPTER_COPY_EN_US: {
|
|
3
|
+
readonly reasonLabels: {
|
|
4
|
+
readonly ITEM_OUT_OF_STOCK: "Item unavailable";
|
|
5
|
+
readonly ITEM_NOT_FOUND: "Item not found";
|
|
6
|
+
readonly ITEM_WRONG_PRICE: "Wrong item price";
|
|
7
|
+
readonly ORDER_MISSING_INFORMATION: "Order information missing";
|
|
8
|
+
readonly ORDER_MISSING_ADDRESS_INFORMATION: "Address information missing";
|
|
9
|
+
readonly ORDER_TOTAL_INCORRECT: "Order total incorrect";
|
|
10
|
+
};
|
|
11
|
+
readonly missingStreetNumber: "no number";
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export { RAPPI_ADAPTER_COPY_EN_US };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import "../chunk-7QVYU63E.js";
|
|
2
|
+
|
|
3
|
+
// src/rappi/en-US.ts
|
|
4
|
+
var RAPPI_ADAPTER_COPY_EN_US = {
|
|
5
|
+
reasonLabels: {
|
|
6
|
+
ITEM_OUT_OF_STOCK: "Item unavailable",
|
|
7
|
+
ITEM_NOT_FOUND: "Item not found",
|
|
8
|
+
ITEM_WRONG_PRICE: "Wrong item price",
|
|
9
|
+
ORDER_MISSING_INFORMATION: "Order information missing",
|
|
10
|
+
ORDER_MISSING_ADDRESS_INFORMATION: "Address information missing",
|
|
11
|
+
ORDER_TOTAL_INCORRECT: "Order total incorrect"
|
|
12
|
+
},
|
|
13
|
+
missingStreetNumber: "no number"
|
|
14
|
+
};
|
|
15
|
+
export {
|
|
16
|
+
RAPPI_ADAPTER_COPY_EN_US
|
|
17
|
+
};
|
|
18
|
+
//# sourceMappingURL=en-US.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/rappi/en-US.ts"],"sourcesContent":["import type { RappiAdapterCopy } from \"./copy\";\n\n/** The Rappi adapter's en-US pack: the same reasons, in English. */\nexport const RAPPI_ADAPTER_COPY_EN_US = {\n reasonLabels: {\n ITEM_OUT_OF_STOCK: \"Item unavailable\",\n ITEM_NOT_FOUND: \"Item not found\",\n ITEM_WRONG_PRICE: \"Wrong item price\",\n ORDER_MISSING_INFORMATION: \"Order information missing\",\n ORDER_MISSING_ADDRESS_INFORMATION: \"Address information missing\",\n ORDER_TOTAL_INCORRECT: \"Order total incorrect\",\n },\n missingStreetNumber: \"no number\",\n} as const satisfies RappiAdapterCopy;\n"],"mappings":";;;AAGO,IAAM,2BAA2B;AAAA,EACtC,cAAc;AAAA,IACZ,mBAAmB;AAAA,IACnB,gBAAgB;AAAA,IAChB,kBAAkB;AAAA,IAClB,2BAA2B;AAAA,IAC3B,mCAAmC;AAAA,IACnC,uBAAuB;AAAA,EACzB;AAAA,EACA,qBAAqB;AACvB;","names":[]}
|