@12-apps/marketplace 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/ADOPTING.md +35 -5
  2. package/README.md +2 -2
  3. package/dist/{adapter-CgCAYBSJ.d.ts → adapter-BggtVFf9.d.ts} +6 -0
  4. package/dist/{chunk-OEKTWUQH.js → chunk-7BYVGNU5.js} +1 -1
  5. package/dist/chunk-7BYVGNU5.js.map +1 -0
  6. package/dist/{chunk-6OODIO3E.js → chunk-DVIRN42O.js} +325 -13
  7. package/dist/chunk-DVIRN42O.js.map +1 -0
  8. package/dist/{chunk-BEMTRJYM.js → chunk-NGNEL4HS.js} +4 -4
  9. package/dist/{chunk-BEMTRJYM.js.map → chunk-NGNEL4HS.js.map} +1 -1
  10. package/dist/{engine-DDE0mnTu.d.ts → engine-KrgZ4pA4.d.ts} +61 -17
  11. package/dist/hono/index.d.ts +2 -2
  12. package/dist/hono/index.js +2 -2
  13. package/dist/ifood/index.d.ts +4 -2
  14. package/dist/ifood/index.js +10 -2
  15. package/dist/ifood/index.js.map +1 -1
  16. package/dist/index.d.ts +3 -3
  17. package/dist/index.js +81 -169
  18. package/dist/index.js.map +1 -1
  19. package/dist/manifest/server.d.ts +2 -2
  20. package/dist/manifest/server.js +2 -2
  21. package/dist/server/index.d.ts +2 -2
  22. package/dist/server/index.js +2 -2
  23. package/package.json +1 -1
  24. package/prisma/marketplace.prisma +7 -0
  25. package/prisma/migrations/20261112120000_marketplace_cancellation_failure/migration.sql +21 -0
  26. package/src/core/acceptance.ts +30 -14
  27. package/src/core/adapter.ts +6 -0
  28. package/src/core/cancellation-outcome.ts +92 -0
  29. package/src/core/cancellation.ts +46 -15
  30. package/src/core/decisions.ts +82 -19
  31. package/src/core/outbound-sweep.ts +87 -8
  32. package/src/core/outbound.ts +83 -7
  33. package/src/core/ports.ts +32 -0
  34. package/src/core/state.ts +6 -1
  35. package/src/ifood/index.ts +9 -0
  36. package/src/index.ts +1 -0
  37. package/src/server/jobs.ts +3 -2
  38. package/dist/chunk-6OODIO3E.js.map +0 -1
  39. package/dist/chunk-OEKTWUQH.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  answered,
3
3
  outboundResultOf
4
- } from "../chunk-OEKTWUQH.js";
4
+ } from "../chunk-7BYVGNU5.js";
5
5
  import {
6
6
  __name
7
7
  } from "../chunk-7QVYU63E.js";
@@ -265,6 +265,7 @@ __name(ifoodRequestCancellation, "ifoodRequestCancellation");
265
265
  // src/ifood/index.ts
266
266
  var IFOOD_PROVIDER = "IFOOD";
267
267
  var ITEM_UNAVAILABLE = "503";
268
+ var IFOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 6e4;
268
269
  function createIfoodAdapter(config) {
269
270
  const reasons = IFOOD_REASON_CODES.map((code) => ({
270
271
  code,
@@ -281,7 +282,13 @@ function createIfoodAdapter(config) {
281
282
  cancelAfterAccept: true,
282
283
  asyncCancellationOutcome: true,
283
284
  perOrderAppLink: false,
284
- confirmTakesPreparationTime: false
285
+ confirmTakesPreparationTime: false,
286
+ // How long iFood takes, at most, to answer a cancellation request: its
287
+ // CANCELLED or CANCELLATION_REQUEST_FAILED event. ESTIMATED, not read off
288
+ // iFood's documentation, which names no answer deadline: iFood answers a
289
+ // request in seconds when it answers at all, so 5 minutes is generous.
290
+ // A host overrides it with the engine's `cancellationWindowMs`.
291
+ cancellationAnswerWindowMs: IFOOD_CANCELLATION_ANSWER_WINDOW_MS
285
292
  },
286
293
  normalize: /* @__PURE__ */ __name((payload) => normalizeIfoodEvent(payload, normalizeOptions), "normalize"),
287
294
  readSignature: /* @__PURE__ */ __name((header) => header("x-ifood-signature") ?? header("x-signature"), "readSignature"),
@@ -296,6 +303,7 @@ function createIfoodAdapter(config) {
296
303
  }
297
304
  __name(createIfoodAdapter, "createIfoodAdapter");
298
305
  export {
306
+ IFOOD_CANCELLATION_ANSWER_WINDOW_MS,
299
307
  IFOOD_PROVIDER,
300
308
  IFOOD_REASON_CODES,
301
309
  createIfoodAdapter,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ifood/copy.ts","../../src/ifood/normalize.ts","../../src/ifood/outbound.ts","../../src/ifood/index.ts"],"sourcesContent":["/**\n * The words the iFood adapter needs from its host, and nothing else.\n *\n * Required and defaultless, like every copy port in this repo: the adapter\n * ships no language of its own. Two packs sit beside it (`./pt-BR`,\n * `./en-US`); a host passes one by hand, or its own.\n */\n\n/**\n * iFood's documented cancellation reason codes. UNVERIFIED: read from the\n * merchant portal's search snippets (2026-11-11), not from a page we could\n * read whole; the homologation run against iFood's sandbox corrects them here.\n */\nexport const IFOOD_REASON_CODES = [\n \"501\",\n \"502\",\n \"503\",\n \"504\",\n \"505\",\n \"506\",\n \"507\",\n \"508\",\n \"509\",\n \"511\",\n \"512\",\n \"513\",\n] as const;\n\nexport type IfoodReasonCode = (typeof IFOOD_REASON_CODES)[number];\n\nexport interface IfoodAdapterCopy {\n /** One label per reason code. Sent to iFood as the reason text when the store wrote none. */\n reasonLabels: Readonly<Record<IfoodReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\n\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceOrderType,\n NormalizedAddress,\n NormalizedBuyer,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n NormalizedOrderLine,\n} from \"../core/types\";\n\n/**\n * The iFood adapter's INBOUND half: one delivery → a {@link NormalizedEvent}.\n *\n * Everything iFood-shaped about a delivery is in this file, and the engine\n * never learns the name: it reaches this through the adapter registry.\n *\n * The payload is treated as UNTRUSTED and read defensively throughout: iFood's\n * documented shape and iFood's actual shape have drifted before, and a\n * `TypeError` reading a missing field would reject a paid order at the door.\n * Every reader below either produces a value or produces null; the one thing\n * that can refuse an order outright is a missing order ID, because without it\n * there is no idempotency key and ingesting would risk a duplicate.\n */\n\n/** iFood event codes this ingestion acts on. */\nconst ORDER_PLACED = new Set([\"PLC\", \"PLACED\", \"ORDER_PLACED\"]);\nconst ORDER_CANCELLED = new Set([\"CAN\", \"CANCELLED\", \"ORDER_CANCELLED\"]);\n/** iFood refused the store's own cancellation request. */\nconst CANCELLATION_REQUEST_FAILED = new Set([\"CARF\", \"CANCELLATION_REQUEST_FAILED\"]);\n\n/** Read a nested value without asserting the shape of anything on the way. */\nfunction pick(source: unknown, ...path: string[]): unknown {\n let cursor: unknown = source;\n for (const key of path) {\n if (typeof cursor !== \"object\" || cursor === null) return undefined;\n cursor = (cursor as Record<string, unknown>)[key];\n }\n return cursor;\n}\n\nfunction asString(value: unknown): string | null {\n if (typeof value === \"string\" && value.trim() !== \"\") return value.trim();\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n return null;\n}\n\n/**\n * The first of several candidate paths that yields a string.\n *\n * iFood states the same fact under different keys depending on which API\n * version delivered the order, so nearly every read here is a fallback chain.\n * Expressed as data rather than as `??` so a chain can grow by one entry\n * instead of by one branch.\n */\nfunction firstString(source: unknown, paths: string[][]): string | null {\n for (const path of paths) {\n const found = asString(pick(source, ...path));\n if (found !== null) return found;\n }\n return null;\n}\n\n/** {@link firstString} for money. Same reason, same shape. */\nfunction firstCents(source: unknown, paths: string[][]): number | null {\n for (const path of paths) {\n const found = toCents(pick(source, ...path));\n if (found !== null) return found;\n }\n return null;\n}\n\n/**\n * iFood states money in DECIMAL reais (`12.9`), this app in integer cents.\n *\n * Rounded rather than truncated: `Math.trunc(12.9 * 100)` is 1289 on IEEE-754,\n * so truncation loses a cent on ordinary prices — per line, on every order,\n * always in the store's disfavour.\n */\nfunction toCents(value: unknown): number | null {\n const numeric = typeof value === \"string\" ? Number(value) : value;\n if (typeof numeric !== \"number\" || !Number.isFinite(numeric)) return null;\n return Math.round(numeric * 100);\n}\n\nfunction toDate(value: unknown): Date | null {\n const raw = asString(value);\n if (!raw) return null;\n const parsed = new Date(raw);\n return Number.isNaN(parsed.getTime()) ? null : parsed;\n}\n\n/** {@link firstString} for timestamps. */\nfunction firstDate(source: unknown, paths: string[][]): Date | null {\n for (const path of paths) {\n const found = toDate(pick(source, ...path));\n if (found !== null) return found;\n }\n return null;\n}\n\n/**\n * Verify a delivery against the merchant's webhook secret.\n *\n * Unsigned deliveries are refused whenever a secret is CONFIGURED. A store that\n * has not set one yet is accepted — iFood's own onboarding issues the secret\n * after the merchant is certified, so refusing before then would make the\n * connection untestable — and that state is visible on the integration screen\n * rather than silent.\n *\n * Compared in constant time over bytes: an early-exit `===` on a hex digest\n * leaks the prefix a forger already got right, one request at a time.\n */\nexport function verifyIfoodSignature(\n rawBody: string,\n signature: string | null,\n webhookSecret: string | null,\n): boolean {\n if (!webhookSecret) return true;\n if (!signature) return false;\n const expected = createHmac(\"sha256\", webhookSecret).update(rawBody, \"utf8\").digest(\"hex\");\n const given = Buffer.from(signature.trim().toLowerCase().replace(/^sha256=/u, \"\"), \"utf8\");\n const mine = Buffer.from(expected, \"utf8\");\n return given.length === mine.length && timingSafeEqual(given, mine);\n}\n\n/** The buyer, as much of them as iFood discloses on the order. */\nfunction readBuyer(order: unknown): NormalizedBuyer {\n return {\n externalId: asString(pick(order, \"customer\", \"id\")),\n name: asString(pick(order, \"customer\", \"name\")),\n phone: firstString(order, [\n [\"customer\", \"phone\", \"number\"],\n [\"customer\", \"phone\"],\n ]),\n };\n}\n\n/**\n * One iFood item → one normalized line.\n *\n * A line with no resolvable SKU still becomes a line: `externalSku` falls back\n * to the item's own id, and failing that to its name. That fallback is doing\n * real work — an unmapped line is recoverable (the store maps it and it is\n * fixed forever), a DROPPED line is not, because nothing downstream can tell\n * that food is missing from the ticket.\n */\nfunction readLine(item: unknown): NormalizedOrderLine | null {\n const name = firstString(item, [[\"name\"], [\"description\"]]);\n const sku = firstString(item, [[\"externalCode\"], [\"sku\"], [\"id\"]]) ?? name;\n if (!sku) return null;\n const quantity = Number(pick(item, \"quantity\") ?? 1);\n return {\n externalSku: sku,\n name: name ?? sku,\n quantity: Number.isFinite(quantity) && quantity > 0 ? Math.round(quantity) : 1,\n unitPriceCents: firstCents(item, [[\"unitPrice\"], [\"price\"]]) ?? 0,\n note: firstString(item, [[\"observations\"], [\"note\"]]),\n };\n}\n\n/**\n * The commission iFood states on the order, in cents.\n *\n * Absent on plenty of real payloads (it depends on the merchant's contract and\n * on which API version delivered the order), and absent is stored as NULL\n * rather than as 0 — \"iFood took nothing\" and \"iFood did not say\" are different\n * claims, and only one of them is safe to put in a margin report.\n */\nfunction readCommission(order: unknown): number | null {\n return firstCents(order, [[\"total\", \"commission\"], [\"commission\"], [\"payments\", \"commission\"]]);\n}\n\n/** iFood's `orderType` as the two ways an order reaches the buyer, or null when it says neither. */\nfunction readOrderType(order: unknown): MarketplaceOrderType | null {\n const stated = firstString(order, [[\"orderType\"]])?.toUpperCase();\n return stated === \"DELIVERY\" || stated === \"TAKEOUT\" ? stated : null;\n}\n\n/** `delivery.deliveredBy`: iFood's own fleet, or the merchant's. Anything else is unstated. */\nfunction readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {\n const stated = firstString(order, [[\"delivery\", \"deliveredBy\"]])?.toUpperCase();\n if (stated === \"IFOOD\") return \"MARKETPLACE\";\n return stated === \"MERCHANT\" ? \"MERCHANT\" : null;\n}\n\n/**\n * Where a delivery goes. The street is what a courier cannot find a door\n * without, so an address with none is none; a missing number reads as the\n * host's own words for \"no number\" (`copy.missingStreetNumber`), which keeps\n * the street, the neighbourhood and the reference rather than dropping the\n * whole door.\n */\nfunction readAddress(order: unknown, missingStreetNumber: string): NormalizedAddress | null {\n const raw = pick(order, \"delivery\", \"deliveryAddress\");\n const street = firstString(raw, [[\"streetName\"], [\"street\"]]);\n if (street === null) return null;\n return {\n street,\n number: firstString(raw, [[\"streetNumber\"], [\"number\"]]) ?? missingStreetNumber,\n neighborhood: firstString(raw, [[\"neighborhood\"]]) ?? \"\",\n complement: firstString(raw, [[\"complement\"]]),\n reference: firstString(raw, [[\"reference\"]]),\n postalCode: firstString(raw, [[\"postalCode\"]])?.replace(/\\D/g, \"\") || null,\n city: firstString(raw, [[\"city\"]]),\n state: firstString(raw, [[\"state\"]]),\n };\n}\n\n/** The order body of a placed-order event, or null when it carries none. */\nfunction readOrder(\n payload: unknown,\n externalOrderId: string,\n missingStreetNumber: string,\n): NormalizedMarketplaceOrder | null {\n const order = pick(payload, \"order\") ?? payload;\n const rawItems = pick(order, \"items\");\n const lines = (Array.isArray(rawItems) ? rawItems : [])\n .map(readLine)\n .filter((line): line is NormalizedOrderLine => line !== null);\n if (lines.length === 0) return null;\n\n const stated = firstCents(order, [[\"total\", \"orderAmount\"], [\"totalPrice\"], [\"total\"]]);\n\n return {\n provider: \"IFOOD\",\n externalOrderId,\n externalDisplayId: firstString(order, [[\"displayId\"]]) ?? firstString(payload, [[\"displayId\"]]),\n buyer: readBuyer(order),\n lines,\n // The line sum is the FALLBACK, never the preference: iFood's stated total\n // carries delivery fees, its promotions and its rounding, and it is the\n // number on the buyer's receipt. Summing lines when iFood did say is how a\n // store's revenue quietly stops matching its iFood statement.\n totalCents: stated ?? lines.reduce((sum, l) => sum + l.unitPriceCents * l.quantity, 0),\n commissionCents: readCommission(order),\n deliveryDueAt: firstDate(order, [[\"delivery\", \"deliveryDateTime\"], [\"preparationStartDateTime\"]]),\n placedAt:\n firstDate(order, [[\"createdAt\"]]) ?? firstDate(payload, [[\"createdAt\"]]) ?? new Date(),\n orderType: readOrderType(order),\n deliveredBy: readDeliveredBy(order),\n deliveryAddress: readAddress(order, missingStreetNumber),\n };\n}\n\n/**\n * Normalize one iFood delivery.\n *\n * Returns null only when the payload carries no order id at all — the one thing\n * this pipeline cannot proceed without, because it IS the idempotency key and\n * ingesting without it risks the duplicate that \"never lose an order\" is\n * balanced against.\n */\nexport function normalizeIfoodEvent(\n payload: unknown,\n options: { missingStreetNumber: string },\n): NormalizedEvent | null {\n const externalOrderId = firstString(payload, [[\"orderId\"], [\"order\", \"id\"], [\"id\"]]);\n if (!externalOrderId) return null;\n\n const eventType = firstString(payload, [[\"fullCode\"], [\"code\"]]) ?? \"UNKNOWN\";\n const cancelled = ORDER_CANCELLED.has(eventType.toUpperCase());\n const placed = ORDER_PLACED.has(eventType.toUpperCase());\n const refusedRequest = CANCELLATION_REQUEST_FAILED.has(eventType.toUpperCase());\n\n return {\n provider: \"IFOOD\",\n // iFood's own event id when it sends one. The fallback is deterministic on\n // purpose — (order, type) is stable across a redelivery, so a duplicate\n // still collides on the inbox's unique index instead of creating a second\n // row that would be processed a second time.\n eventId: firstString(payload, [[\"id\"]]) ?? `${externalOrderId}:${eventType}`,\n eventType,\n externalMerchantId: firstString(payload, [[\"merchantId\"], [\"merchant\", \"id\"]]),\n externalOrderId,\n order: placed ? readOrder(payload, externalOrderId, options.missingStreetNumber) : null,\n cancelled,\n cancellationOutcome: cancelled ? \"CONFIRMED\" : refusedRequest ? \"FAILED\" : null,\n };\n}\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type OutboundOrderRef,\n type OutboundResult,\n} from \"../core/adapter\";\n\n/**\n * The iFood adapter's OUTBOUND half: auth, URLs and payload shapes. Everything\n * here is iFood's wire format and nothing else — the job that calls it, its\n * retries and what a failure shows are the engine's (`../core/outbound.ts`).\n *\n * UNVERIFIED. iFood's developer portal refused our reader, so every URL, body\n * field below (and the reason codes in `./copy.ts`) comes from the portal's search snippets\n * (2026-11-11), not from a page we could read whole. They are in THIS file and\n * nowhere else so that the homologation run against iFood's sandbox, once\n * homologation credentials exist, corrects one file. Tests never reach\n * iFood: the HTTP client is the host's port, answered by a fake.\n */\n\n/** iFood's merchant API. Sandbox and production share the host; the credentials differ. */\nconst API = \"https://merchant-api.ifood.com.br\";\nconst TOKEN_URL = `${API}/authentication/v1.0/oauth/token`;\nconst orderUrl = (externalOrderId: string, action: string): string =>\n `${API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}/${action}`;\n\n/**\n * iFood's order-manager portal. No per-order deep link was found in the\n * snippets, so the app link opens the portal, where the order is on the\n * first screen while it is live.\n */\nexport const IFOOD_PORTAL_URL = \"https://portal.ifood.com.br/\";\n\n/** A token is renewed this long before iFood says it expires. */\nconst TOKEN_MARGIN_MS = 60_000;\n\n/** iFood's OAuth answer, read defensively: a missing field is \"no token\". */\nfunction tokenOf(body: string): { token: string; expiresInSeconds: number } | null {\n try {\n const parsed = JSON.parse(body) as { accessToken?: unknown; expiresIn?: unknown };\n if (typeof parsed.accessToken !== \"string\" || parsed.accessToken === \"\") return null;\n const expires = typeof parsed.expiresIn === \"number\" && parsed.expiresIn > 0 ? parsed.expiresIn : 3600;\n return { token: parsed.accessToken, expiresInSeconds: expires };\n } catch {\n return null;\n }\n}\n\n/**\n * A bearer token for this merchant app, from the per-process cache or a fresh\n * client-credentials grant. Keyed by the app's client id, so two stores with\n * two apps never share one. The token lives in memory only.\n */\nasync function bearer(ctx: AdapterCallContext): Promise<{ token: string } | OutboundResult> {\n const key = `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`;\n const cached = ctx.tokens.get(key);\n if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };\n const response = await ctx.http({\n method: \"POST\",\n url: TOKEN_URL,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grantType: \"client_credentials\",\n clientId: ctx.credentials.clientId,\n clientSecret: ctx.credentials.clientSecret,\n }).toString(),\n });\n if (response.status < 200 || response.status >= 300) return outboundResultOf(response);\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: \"iFood answered the token grant without a token\" };\n ctx.tokens.set(key, { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });\n return { token: token.token };\n}\n\n/** One authenticated POST to an order's resource. */\nfunction postOrder(ctx: AdapterCallContext, externalOrderId: string, action: string, body?: unknown): Promise<OutboundResult> {\n return answered(async () => {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"POST\",\n url: orderUrl(externalOrderId, action),\n headers: {\n Authorization: `Bearer ${auth.token}`,\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n // A 401 is a token that went stale under us: forget it, and the retry fetches another.\n if (response.status === 401) ctx.tokens.delete(`IFOOD:${ctx.environment}:${ctx.credentials.clientId}`);\n return response.status === 401 ? { kind: \"retry\", reason: \"iFood refused the token\" } : outboundResultOf(response);\n });\n}\n\n/** Tell iFood the store accepted the order. No body: the URL names the order. */\nexport function ifoodConfirm(ctx: AdapterCallContext, order: OutboundOrderRef): Promise<OutboundResult> {\n return postOrder(ctx, order.externalOrderId, \"confirm\");\n}\n\n/** Ask iFood to cancel the order with one of its reason codes. */\nexport function ifoodRequestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n): Promise<OutboundResult> {\n return postOrder(ctx, order.externalOrderId, \"requestCancellation\", {\n reason: input.text === \"\" ? input.reason.label : input.text,\n cancellationCode: input.reason.code,\n });\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from \"./copy\";\nimport { normalizeIfoodEvent, verifyIfoodSignature } from \"./normalize\";\nimport { IFOOD_PORTAL_URL, ifoodConfirm, ifoodRequestCancellation } from \"./outbound\";\n\n/**\n * `@12-apps/marketplace/ifood` — iFood, as one adapter on the engine.\n *\n * The owner's rule: adapters live inside the lib, one per subpath, and no\n * provider-specific branch exists anywhere outside an adapter and its\n * registration. Everything iFood is under this folder; the engine reaches it\n * only through the {@link MarketplaceAdapter} port.\n *\n * ```ts\n * import { createIfoodAdapter } from \"@12-apps/marketplace/ifood\";\n * import { IFOOD_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/ifood/pt-BR\";\n *\n * createMarketplaceEngine({ …ports, adapters: [createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR })] });\n * ```\n */\n\n/** The provider id iFood is registered under. */\nexport const IFOOD_PROVIDER = \"IFOOD\";\n\n/** The one reason that means \"an item is unavailable\". */\nconst ITEM_UNAVAILABLE: IfoodReasonCode = \"503\";\n\nexport interface IfoodAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: IfoodAdapterCopy;\n}\n\n/** Build the iFood adapter. Its reasons are static: a dialog never waits on iFood. */\nexport function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapter {\n const reasons: readonly CancellationReason[] = IFOOD_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === ITEM_UNAVAILABLE,\n needsItems: false,\n }));\n const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };\n return {\n provider: IFOOD_PROVIDER,\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n cancelAfterAccept: true,\n asyncCancellationOutcome: true,\n perOrderAppLink: false,\n confirmTakesPreparationTime: false,\n },\n normalize: (payload) => normalizeIfoodEvent(payload, normalizeOptions),\n readSignature: (header) => header(\"x-ifood-signature\") ?? header(\"x-signature\"),\n verifySignature: verifyIfoodSignature,\n cancellationReasons: () => reasons,\n confirm: (ctx, order) => ifoodConfirm(ctx, order),\n requestCancellation: ifoodRequestCancellation,\n // No per-order deep link is known, so the portal, where a live order is\n // on the first screen.\n appLink: () => IFOOD_PORTAL_URL,\n };\n}\n\nexport { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from \"./copy\";\nexport { normalizeIfoodEvent, verifyIfoodSignature } from \"./normalize\";\n"],"mappings":";;;;;;;;;AAaO,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;AC1BA,SAAS,YAAY,uBAAuB;AA2B5C,IAAM,eAAe,oBAAI,IAAI,CAAC,OAA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S,gBAAgB,GAA1D;AAAA,IACX,eAAe,wBAAC,WAAW,OAAO,mBAAmB,KAAK,OAAO,aAAa,GAA/D;AAAA,IACf,iBAAiB;AAAA,IACjB,qBAAqB,6BAAM,SAAN;AAAA,IACrB,SAAS,wBAAC,KAAK,UAAU,aAAa,KAAK,KAAK,GAAvC;AAAA,IACT,qBAAqB;AAAA;AAAA;AAAA,IAGrB,SAAS,6BAAM,kBAAN;AAAA,EACX;AACF;AA5BgB;","names":[]}
1
+ {"version":3,"sources":["../../src/ifood/copy.ts","../../src/ifood/normalize.ts","../../src/ifood/outbound.ts","../../src/ifood/index.ts"],"sourcesContent":["/**\n * The words the iFood adapter needs from its host, and nothing else.\n *\n * Required and defaultless, like every copy port in this repo: the adapter\n * ships no language of its own. Two packs sit beside it (`./pt-BR`,\n * `./en-US`); a host passes one by hand, or its own.\n */\n\n/**\n * iFood's documented cancellation reason codes. UNVERIFIED: read from the\n * merchant portal's search snippets (2026-11-11), not from a page we could\n * read whole; the homologation run against iFood's sandbox corrects them here.\n */\nexport const IFOOD_REASON_CODES = [\n \"501\",\n \"502\",\n \"503\",\n \"504\",\n \"505\",\n \"506\",\n \"507\",\n \"508\",\n \"509\",\n \"511\",\n \"512\",\n \"513\",\n] as const;\n\nexport type IfoodReasonCode = (typeof IFOOD_REASON_CODES)[number];\n\nexport interface IfoodAdapterCopy {\n /** One label per reason code. Sent to iFood as the reason text when the store wrote none. */\n reasonLabels: Readonly<Record<IfoodReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\n\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceOrderType,\n NormalizedAddress,\n NormalizedBuyer,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n NormalizedOrderLine,\n} from \"../core/types\";\n\n/**\n * The iFood adapter's INBOUND half: one delivery → a {@link NormalizedEvent}.\n *\n * Everything iFood-shaped about a delivery is in this file, and the engine\n * never learns the name: it reaches this through the adapter registry.\n *\n * The payload is treated as UNTRUSTED and read defensively throughout: iFood's\n * documented shape and iFood's actual shape have drifted before, and a\n * `TypeError` reading a missing field would reject a paid order at the door.\n * Every reader below either produces a value or produces null; the one thing\n * that can refuse an order outright is a missing order ID, because without it\n * there is no idempotency key and ingesting would risk a duplicate.\n */\n\n/** iFood event codes this ingestion acts on. */\nconst ORDER_PLACED = new Set([\"PLC\", \"PLACED\", \"ORDER_PLACED\"]);\nconst ORDER_CANCELLED = new Set([\"CAN\", \"CANCELLED\", \"ORDER_CANCELLED\"]);\n/** iFood refused the store's own cancellation request. */\nconst CANCELLATION_REQUEST_FAILED = new Set([\"CARF\", \"CANCELLATION_REQUEST_FAILED\"]);\n\n/** Read a nested value without asserting the shape of anything on the way. */\nfunction pick(source: unknown, ...path: string[]): unknown {\n let cursor: unknown = source;\n for (const key of path) {\n if (typeof cursor !== \"object\" || cursor === null) return undefined;\n cursor = (cursor as Record<string, unknown>)[key];\n }\n return cursor;\n}\n\nfunction asString(value: unknown): string | null {\n if (typeof value === \"string\" && value.trim() !== \"\") return value.trim();\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n return null;\n}\n\n/**\n * The first of several candidate paths that yields a string.\n *\n * iFood states the same fact under different keys depending on which API\n * version delivered the order, so nearly every read here is a fallback chain.\n * Expressed as data rather than as `??` so a chain can grow by one entry\n * instead of by one branch.\n */\nfunction firstString(source: unknown, paths: string[][]): string | null {\n for (const path of paths) {\n const found = asString(pick(source, ...path));\n if (found !== null) return found;\n }\n return null;\n}\n\n/** {@link firstString} for money. Same reason, same shape. */\nfunction firstCents(source: unknown, paths: string[][]): number | null {\n for (const path of paths) {\n const found = toCents(pick(source, ...path));\n if (found !== null) return found;\n }\n return null;\n}\n\n/**\n * iFood states money in DECIMAL reais (`12.9`), this app in integer cents.\n *\n * Rounded rather than truncated: `Math.trunc(12.9 * 100)` is 1289 on IEEE-754,\n * so truncation loses a cent on ordinary prices — per line, on every order,\n * always in the store's disfavour.\n */\nfunction toCents(value: unknown): number | null {\n const numeric = typeof value === \"string\" ? Number(value) : value;\n if (typeof numeric !== \"number\" || !Number.isFinite(numeric)) return null;\n return Math.round(numeric * 100);\n}\n\nfunction toDate(value: unknown): Date | null {\n const raw = asString(value);\n if (!raw) return null;\n const parsed = new Date(raw);\n return Number.isNaN(parsed.getTime()) ? null : parsed;\n}\n\n/** {@link firstString} for timestamps. */\nfunction firstDate(source: unknown, paths: string[][]): Date | null {\n for (const path of paths) {\n const found = toDate(pick(source, ...path));\n if (found !== null) return found;\n }\n return null;\n}\n\n/**\n * Verify a delivery against the merchant's webhook secret.\n *\n * Unsigned deliveries are refused whenever a secret is CONFIGURED. A store that\n * has not set one yet is accepted — iFood's own onboarding issues the secret\n * after the merchant is certified, so refusing before then would make the\n * connection untestable — and that state is visible on the integration screen\n * rather than silent.\n *\n * Compared in constant time over bytes: an early-exit `===` on a hex digest\n * leaks the prefix a forger already got right, one request at a time.\n */\nexport function verifyIfoodSignature(\n rawBody: string,\n signature: string | null,\n webhookSecret: string | null,\n): boolean {\n if (!webhookSecret) return true;\n if (!signature) return false;\n const expected = createHmac(\"sha256\", webhookSecret).update(rawBody, \"utf8\").digest(\"hex\");\n const given = Buffer.from(signature.trim().toLowerCase().replace(/^sha256=/u, \"\"), \"utf8\");\n const mine = Buffer.from(expected, \"utf8\");\n return given.length === mine.length && timingSafeEqual(given, mine);\n}\n\n/** The buyer, as much of them as iFood discloses on the order. */\nfunction readBuyer(order: unknown): NormalizedBuyer {\n return {\n externalId: asString(pick(order, \"customer\", \"id\")),\n name: asString(pick(order, \"customer\", \"name\")),\n phone: firstString(order, [\n [\"customer\", \"phone\", \"number\"],\n [\"customer\", \"phone\"],\n ]),\n };\n}\n\n/**\n * One iFood item → one normalized line.\n *\n * A line with no resolvable SKU still becomes a line: `externalSku` falls back\n * to the item's own id, and failing that to its name. That fallback is doing\n * real work — an unmapped line is recoverable (the store maps it and it is\n * fixed forever), a DROPPED line is not, because nothing downstream can tell\n * that food is missing from the ticket.\n */\nfunction readLine(item: unknown): NormalizedOrderLine | null {\n const name = firstString(item, [[\"name\"], [\"description\"]]);\n const sku = firstString(item, [[\"externalCode\"], [\"sku\"], [\"id\"]]) ?? name;\n if (!sku) return null;\n const quantity = Number(pick(item, \"quantity\") ?? 1);\n return {\n externalSku: sku,\n name: name ?? sku,\n quantity: Number.isFinite(quantity) && quantity > 0 ? Math.round(quantity) : 1,\n unitPriceCents: firstCents(item, [[\"unitPrice\"], [\"price\"]]) ?? 0,\n note: firstString(item, [[\"observations\"], [\"note\"]]),\n };\n}\n\n/**\n * The commission iFood states on the order, in cents.\n *\n * Absent on plenty of real payloads (it depends on the merchant's contract and\n * on which API version delivered the order), and absent is stored as NULL\n * rather than as 0 — \"iFood took nothing\" and \"iFood did not say\" are different\n * claims, and only one of them is safe to put in a margin report.\n */\nfunction readCommission(order: unknown): number | null {\n return firstCents(order, [[\"total\", \"commission\"], [\"commission\"], [\"payments\", \"commission\"]]);\n}\n\n/** iFood's `orderType` as the two ways an order reaches the buyer, or null when it says neither. */\nfunction readOrderType(order: unknown): MarketplaceOrderType | null {\n const stated = firstString(order, [[\"orderType\"]])?.toUpperCase();\n return stated === \"DELIVERY\" || stated === \"TAKEOUT\" ? stated : null;\n}\n\n/** `delivery.deliveredBy`: iFood's own fleet, or the merchant's. Anything else is unstated. */\nfunction readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {\n const stated = firstString(order, [[\"delivery\", \"deliveredBy\"]])?.toUpperCase();\n if (stated === \"IFOOD\") return \"MARKETPLACE\";\n return stated === \"MERCHANT\" ? \"MERCHANT\" : null;\n}\n\n/**\n * Where a delivery goes. The street is what a courier cannot find a door\n * without, so an address with none is none; a missing number reads as the\n * host's own words for \"no number\" (`copy.missingStreetNumber`), which keeps\n * the street, the neighbourhood and the reference rather than dropping the\n * whole door.\n */\nfunction readAddress(order: unknown, missingStreetNumber: string): NormalizedAddress | null {\n const raw = pick(order, \"delivery\", \"deliveryAddress\");\n const street = firstString(raw, [[\"streetName\"], [\"street\"]]);\n if (street === null) return null;\n return {\n street,\n number: firstString(raw, [[\"streetNumber\"], [\"number\"]]) ?? missingStreetNumber,\n neighborhood: firstString(raw, [[\"neighborhood\"]]) ?? \"\",\n complement: firstString(raw, [[\"complement\"]]),\n reference: firstString(raw, [[\"reference\"]]),\n postalCode: firstString(raw, [[\"postalCode\"]])?.replace(/\\D/g, \"\") || null,\n city: firstString(raw, [[\"city\"]]),\n state: firstString(raw, [[\"state\"]]),\n };\n}\n\n/** The order body of a placed-order event, or null when it carries none. */\nfunction readOrder(\n payload: unknown,\n externalOrderId: string,\n missingStreetNumber: string,\n): NormalizedMarketplaceOrder | null {\n const order = pick(payload, \"order\") ?? payload;\n const rawItems = pick(order, \"items\");\n const lines = (Array.isArray(rawItems) ? rawItems : [])\n .map(readLine)\n .filter((line): line is NormalizedOrderLine => line !== null);\n if (lines.length === 0) return null;\n\n const stated = firstCents(order, [[\"total\", \"orderAmount\"], [\"totalPrice\"], [\"total\"]]);\n\n return {\n provider: \"IFOOD\",\n externalOrderId,\n externalDisplayId: firstString(order, [[\"displayId\"]]) ?? firstString(payload, [[\"displayId\"]]),\n buyer: readBuyer(order),\n lines,\n // The line sum is the FALLBACK, never the preference: iFood's stated total\n // carries delivery fees, its promotions and its rounding, and it is the\n // number on the buyer's receipt. Summing lines when iFood did say is how a\n // store's revenue quietly stops matching its iFood statement.\n totalCents: stated ?? lines.reduce((sum, l) => sum + l.unitPriceCents * l.quantity, 0),\n commissionCents: readCommission(order),\n deliveryDueAt: firstDate(order, [[\"delivery\", \"deliveryDateTime\"], [\"preparationStartDateTime\"]]),\n placedAt:\n firstDate(order, [[\"createdAt\"]]) ?? firstDate(payload, [[\"createdAt\"]]) ?? new Date(),\n orderType: readOrderType(order),\n deliveredBy: readDeliveredBy(order),\n deliveryAddress: readAddress(order, missingStreetNumber),\n };\n}\n\n/**\n * Normalize one iFood delivery.\n *\n * Returns null only when the payload carries no order id at all — the one thing\n * this pipeline cannot proceed without, because it IS the idempotency key and\n * ingesting without it risks the duplicate that \"never lose an order\" is\n * balanced against.\n */\nexport function normalizeIfoodEvent(\n payload: unknown,\n options: { missingStreetNumber: string },\n): NormalizedEvent | null {\n const externalOrderId = firstString(payload, [[\"orderId\"], [\"order\", \"id\"], [\"id\"]]);\n if (!externalOrderId) return null;\n\n const eventType = firstString(payload, [[\"fullCode\"], [\"code\"]]) ?? \"UNKNOWN\";\n const cancelled = ORDER_CANCELLED.has(eventType.toUpperCase());\n const placed = ORDER_PLACED.has(eventType.toUpperCase());\n const refusedRequest = CANCELLATION_REQUEST_FAILED.has(eventType.toUpperCase());\n\n return {\n provider: \"IFOOD\",\n // iFood's own event id when it sends one. The fallback is deterministic on\n // purpose — (order, type) is stable across a redelivery, so a duplicate\n // still collides on the inbox's unique index instead of creating a second\n // row that would be processed a second time.\n eventId: firstString(payload, [[\"id\"]]) ?? `${externalOrderId}:${eventType}`,\n eventType,\n externalMerchantId: firstString(payload, [[\"merchantId\"], [\"merchant\", \"id\"]]),\n externalOrderId,\n order: placed ? readOrder(payload, externalOrderId, options.missingStreetNumber) : null,\n cancelled,\n cancellationOutcome: cancelled ? \"CONFIRMED\" : refusedRequest ? \"FAILED\" : null,\n };\n}\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type OutboundOrderRef,\n type OutboundResult,\n} from \"../core/adapter\";\n\n/**\n * The iFood adapter's OUTBOUND half: auth, URLs and payload shapes. Everything\n * here is iFood's wire format and nothing else — the job that calls it, its\n * retries and what a failure shows are the engine's (`../core/outbound.ts`).\n *\n * UNVERIFIED. iFood's developer portal refused our reader, so every URL, body\n * field below (and the reason codes in `./copy.ts`) comes from the portal's search snippets\n * (2026-11-11), not from a page we could read whole. They are in THIS file and\n * nowhere else so that the homologation run against iFood's sandbox, once\n * homologation credentials exist, corrects one file. Tests never reach\n * iFood: the HTTP client is the host's port, answered by a fake.\n */\n\n/** iFood's merchant API. Sandbox and production share the host; the credentials differ. */\nconst API = \"https://merchant-api.ifood.com.br\";\nconst TOKEN_URL = `${API}/authentication/v1.0/oauth/token`;\nconst orderUrl = (externalOrderId: string, action: string): string =>\n `${API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}/${action}`;\n\n/**\n * iFood's order-manager portal. No per-order deep link was found in the\n * snippets, so the app link opens the portal, where the order is on the\n * first screen while it is live.\n */\nexport const IFOOD_PORTAL_URL = \"https://portal.ifood.com.br/\";\n\n/** A token is renewed this long before iFood says it expires. */\nconst TOKEN_MARGIN_MS = 60_000;\n\n/** iFood's OAuth answer, read defensively: a missing field is \"no token\". */\nfunction tokenOf(body: string): { token: string; expiresInSeconds: number } | null {\n try {\n const parsed = JSON.parse(body) as { accessToken?: unknown; expiresIn?: unknown };\n if (typeof parsed.accessToken !== \"string\" || parsed.accessToken === \"\") return null;\n const expires = typeof parsed.expiresIn === \"number\" && parsed.expiresIn > 0 ? parsed.expiresIn : 3600;\n return { token: parsed.accessToken, expiresInSeconds: expires };\n } catch {\n return null;\n }\n}\n\n/**\n * A bearer token for this merchant app, from the per-process cache or a fresh\n * client-credentials grant. Keyed by the app's client id, so two stores with\n * two apps never share one. The token lives in memory only.\n */\nasync function bearer(ctx: AdapterCallContext): Promise<{ token: string } | OutboundResult> {\n const key = `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`;\n const cached = ctx.tokens.get(key);\n if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };\n const response = await ctx.http({\n method: \"POST\",\n url: TOKEN_URL,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grantType: \"client_credentials\",\n clientId: ctx.credentials.clientId,\n clientSecret: ctx.credentials.clientSecret,\n }).toString(),\n });\n if (response.status < 200 || response.status >= 300) return outboundResultOf(response);\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: \"iFood answered the token grant without a token\" };\n ctx.tokens.set(key, { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });\n return { token: token.token };\n}\n\n/** One authenticated POST to an order's resource. */\nfunction postOrder(ctx: AdapterCallContext, externalOrderId: string, action: string, body?: unknown): Promise<OutboundResult> {\n return answered(async () => {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"POST\",\n url: orderUrl(externalOrderId, action),\n headers: {\n Authorization: `Bearer ${auth.token}`,\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n // A 401 is a token that went stale under us: forget it, and the retry fetches another.\n if (response.status === 401) ctx.tokens.delete(`IFOOD:${ctx.environment}:${ctx.credentials.clientId}`);\n return response.status === 401 ? { kind: \"retry\", reason: \"iFood refused the token\" } : outboundResultOf(response);\n });\n}\n\n/** Tell iFood the store accepted the order. No body: the URL names the order. */\nexport function ifoodConfirm(ctx: AdapterCallContext, order: OutboundOrderRef): Promise<OutboundResult> {\n return postOrder(ctx, order.externalOrderId, \"confirm\");\n}\n\n/** Ask iFood to cancel the order with one of its reason codes. */\nexport function ifoodRequestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n): Promise<OutboundResult> {\n return postOrder(ctx, order.externalOrderId, \"requestCancellation\", {\n reason: input.text === \"\" ? input.reason.label : input.text,\n cancellationCode: input.reason.code,\n });\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from \"./copy\";\nimport { normalizeIfoodEvent, verifyIfoodSignature } from \"./normalize\";\nimport { IFOOD_PORTAL_URL, ifoodConfirm, ifoodRequestCancellation } from \"./outbound\";\n\n/**\n * `@12-apps/marketplace/ifood` — iFood, as one adapter on the engine.\n *\n * The owner's rule: adapters live inside the lib, one per subpath, and no\n * provider-specific branch exists anywhere outside an adapter and its\n * registration. Everything iFood is under this folder; the engine reaches it\n * only through the {@link MarketplaceAdapter} port.\n *\n * ```ts\n * import { createIfoodAdapter } from \"@12-apps/marketplace/ifood\";\n * import { IFOOD_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/ifood/pt-BR\";\n *\n * createMarketplaceEngine({ …ports, adapters: [createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR })] });\n * ```\n */\n\n/** The provider id iFood is registered under. */\nexport const IFOOD_PROVIDER = \"IFOOD\";\n\n/** The one reason that means \"an item is unavailable\". */\nconst ITEM_UNAVAILABLE: IfoodReasonCode = \"503\";\n\n/** How long iFood may take to answer a cancellation request: 5 minutes, ESTIMATED (see the adapter's capabilities). */\nexport const IFOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;\n\nexport interface IfoodAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: IfoodAdapterCopy;\n}\n\n/** Build the iFood adapter. Its reasons are static: a dialog never waits on iFood. */\nexport function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapter {\n const reasons: readonly CancellationReason[] = IFOOD_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === ITEM_UNAVAILABLE,\n needsItems: false,\n }));\n const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };\n return {\n provider: IFOOD_PROVIDER,\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n cancelAfterAccept: true,\n asyncCancellationOutcome: true,\n perOrderAppLink: false,\n confirmTakesPreparationTime: false,\n // How long iFood takes, at most, to answer a cancellation request: its\n // CANCELLED or CANCELLATION_REQUEST_FAILED event. ESTIMATED, not read off\n // iFood's documentation, which names no answer deadline: iFood answers a\n // request in seconds when it answers at all, so 5 minutes is generous.\n // A host overrides it with the engine's `cancellationWindowMs`.\n cancellationAnswerWindowMs: IFOOD_CANCELLATION_ANSWER_WINDOW_MS,\n },\n normalize: (payload) => normalizeIfoodEvent(payload, normalizeOptions),\n readSignature: (header) => header(\"x-ifood-signature\") ?? header(\"x-signature\"),\n verifySignature: verifyIfoodSignature,\n cancellationReasons: () => reasons,\n confirm: (ctx, order) => ifoodConfirm(ctx, order),\n requestCancellation: ifoodRequestCancellation,\n // No per-order deep link is known, so the portal, where a live order is\n // on the first screen.\n appLink: () => IFOOD_PORTAL_URL,\n };\n}\n\nexport { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from \"./copy\";\nexport { normalizeIfoodEvent, verifyIfoodSignature } from \"./normalize\";\n"],"mappings":";;;;;;;;;AAaO,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;AC1BA,SAAS,YAAY,uBAAuB;AA2B5C,IAAM,eAAe,oBAAI,IAAI,CAAC,OAAO,UAAU,cAAc,CAAC;AAC9D,IAAM,kBAAkB,oBAAI,IAAI,CAAC,OAAO,aAAa,iBAAiB,CAAC;AAEvE,IAAM,8BAA8B,oBAAI,IAAI,CAAC,QAAQ,6BAA6B,CAAC;AAGnF,SAAS,KAAK,WAAoB,MAAyB;AACzD,MAAI,SAAkB;AACtB,aAAW,OAAO,MAAM;AACtB,QAAI,OAAO,WAAW,YAAY,WAAW,KAAM,QAAO;AAC1D,aAAU,OAAmC,GAAG;AAAA,EAClD;AACA,SAAO;AACT;AAPS;AAST,SAAS,SAAS,OAA+B;AAC/C,MAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,GAAI,QAAO,MAAM,KAAK;AACxE,MAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,EAAG,QAAO,OAAO,KAAK;AAC5E,SAAO;AACT;AAJS;AAcT,SAAS,YAAY,QAAiB,OAAkC;AACtE,aAAW,QAAQ,OAAO;AACxB,UAAM,QAAQ,SAAS,KAAK,QAAQ,GAAG,IAAI,CAAC;AAC5C,QAAI,UAAU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AAAA,IACvD,kBAAkB,MAAM,OAAO;AAAA,EACjC,CAAC;AACH;AATgB;;;AChFT,IAAM,iBAAiB;AAG9B,IAAM,mBAAoC;AAGnC,IAAM,sCAAsC,IAAI;AAQhD,SAAS,mBAAmB,QAAgD;AACjF,QAAM,UAAyC,mBAAmB,IAAI,CAAC,UAAU;AAAA,IAC/E;AAAA,IACA,OAAO,OAAO,KAAK,aAAa,IAAI;AAAA,IACpC,iBAAiB,SAAS;AAAA,IAC1B,YAAY;AAAA,EACd,EAAE;AACF,QAAM,mBAAmB,EAAE,qBAAqB,OAAO,KAAK,oBAAoB;AAChF,SAAO;AAAA,IACL,UAAU;AAAA,IACV,cAAc;AAAA,MACZ,YAAY;AAAA,MACZ,WAAW;AAAA,MACX,mBAAmB;AAAA,MACnB,0BAA0B;AAAA,MAC1B,iBAAiB;AAAA,MACjB,6BAA6B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAM7B,4BAA4B;AAAA,IAC9B;AAAA,IACA,WAAW,wBAAC,YAAY,oBAAoB,SAAS,gBAAgB,GAA1D;AAAA,IACX,eAAe,wBAAC,WAAW,OAAO,mBAAmB,KAAK,OAAO,aAAa,GAA/D;AAAA,IACf,iBAAiB;AAAA,IACjB,qBAAqB,6BAAM,SAAN;AAAA,IACrB,SAAS,wBAAC,KAAK,UAAU,aAAa,KAAK,KAAK,GAAvC;AAAA,IACT,qBAAqB;AAAA;AAAA;AAAA,IAGrB,SAAS,6BAAM,kBAAN;AAAA,EACX;AACF;AAlCgB;","names":[]}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export { A as AcceptanceDecision, a as AcceptanceStatus, B as BulkProblem, b as BulkProblemCode, c as BulkResult, C as CancellationStatus, D as DecideManyResult, d as DecidedRow, e as DecisionInput, f as DecisionProblem, g as DecisionProblemCode, h as DecisionResult, i as DeliveryOutcome, E as ExpirySweepResult, I as IngestResult, j as IngestSettings, k as IngestionTarget, l as IntegrationRowInput, M as MARKETPLACE_OUTBOUND_JOB, m as MarketplaceAdmission, n as MarketplaceAdmissionRequest, o as MarketplaceAdmissionResult, p as MarketplaceAuditEntry, q as MarketplaceAuditPort, r as MarketplaceClockPort, s as MarketplaceDb, t as MarketplaceEngine, u as MarketplaceEngineConfig, v as MarketplaceEnqueuePort, w as MarketplaceIntegrationView, x as MarketplaceLogger, y as MarketplaceMenuLinkView, z as MarketplaceOrderPort, F as MarketplaceOrderState, G as MarketplaceOrderSummary, H as MarketplacePorts, J as MarketplaceRefusal, K as MarketplaceSecretsPort, L as MenuLinkRowInput, O as OUTBOUND_GIVE_UP_MS, N as OUTBOUND_STALE_MS, P as OutboundAction, Q as OutboundAttempt, R as OutboundJobPayload, S as OutboundOutcome, T as OutboundRetryError, U as OutboundSweepResult, V as PendingAcceptance, W as PendingInboxEvent, X as ResolvedOrderLine, Y as SaveMarketplaceIntegrationInput, Z as createMarketplaceEngine, _ as outboundDedupeKey } from './engine-DDE0mnTu.js';
2
- import { M as MarketplaceAdapter, a as MarketplaceProvider, C as CancellationReason } from './adapter-CgCAYBSJ.js';
3
- export { A as AdapterCallContext, b as AdapterTokenCache, c as CancellationOutcome, d as CancellationRequestInput, e as MarketplaceCapabilities, f as MarketplaceCredentials, g as MarketplaceDeliveredBy, h as MarketplaceHttp, i as MarketplaceHttpRequest, j as MarketplaceHttpResponse, k as MarketplaceOrderType, l as NormalizedAddress, m as NormalizedBuyer, N as NormalizedEvent, n as NormalizedMarketplaceOrder, o as NormalizedOrderLine, O as OutboundOrderRef, p as OutboundResult, P as PROVIDER_ID_PATTERN, q as answered, r as outboundResultOf } from './adapter-CgCAYBSJ.js';
1
+ export { A as AcceptanceDecision, a as AcceptanceStatus, B as BulkProblem, b as BulkProblemCode, c as BulkResult, C as CancellationFailureReason, d as CancellationStatus, D as DecideManyResult, e as DecidedRow, f as DecisionInput, g as DecisionProblem, h as DecisionProblemCode, i as DecisionResult, j as DeliveryOutcome, E as ExpirySweepResult, I as IngestResult, k as IngestSettings, l as IngestionTarget, m as IntegrationRowInput, M as MARKETPLACE_OUTBOUND_JOB, n as MarketplaceAdmission, o as MarketplaceAdmissionRequest, p as MarketplaceAdmissionResult, q as MarketplaceAuditEntry, r as MarketplaceAuditPort, s as MarketplaceClockPort, t as MarketplaceDb, u as MarketplaceEngine, v as MarketplaceEngineConfig, w as MarketplaceEnqueuePort, x as MarketplaceIntegrationView, y as MarketplaceLogger, z as MarketplaceMenuLinkView, F as MarketplaceOrderPort, G as MarketplaceOrderState, H as MarketplaceOrderSummary, J as MarketplacePorts, K as MarketplaceRefusal, L as MarketplaceSecretsPort, N as MenuLinkRowInput, O as OUTBOUND_GIVE_UP_MS, P as OUTBOUND_STALE_MS, Q as OutboundAction, R as OutboundAttempt, S as OutboundJobPayload, T as OutboundOutcome, U as OutboundRetryError, V as OutboundSweepResult, W as PendingAcceptance, X as PendingInboxEvent, Y as ResolvedOrderLine, Z as SaveMarketplaceIntegrationInput, _ as createMarketplaceEngine, $ as outboundDedupeKey } from './engine-KrgZ4pA4.js';
2
+ import { M as MarketplaceAdapter, a as MarketplaceProvider, C as CancellationReason } from './adapter-BggtVFf9.js';
3
+ export { A as AdapterCallContext, b as AdapterTokenCache, c as CancellationOutcome, d as CancellationRequestInput, e as MarketplaceCapabilities, f as MarketplaceCredentials, g as MarketplaceDeliveredBy, h as MarketplaceHttp, i as MarketplaceHttpRequest, j as MarketplaceHttpResponse, k as MarketplaceOrderType, l as NormalizedAddress, m as NormalizedBuyer, N as NormalizedEvent, n as NormalizedMarketplaceOrder, o as NormalizedOrderLine, O as OutboundOrderRef, p as OutboundResult, P as PROVIDER_ID_PATTERN, q as answered, r as outboundResultOf } from './adapter-BggtVFf9.js';
4
4
 
5
5
  /**
6
6
  * The adapter registry: the ONE place a provider id becomes a marketplace.
package/dist/index.js CHANGED
@@ -1,21 +1,38 @@
1
1
  import {
2
2
  answered,
3
3
  outboundResultOf
4
- } from "./chunk-OEKTWUQH.js";
4
+ } from "./chunk-7BYVGNU5.js";
5
5
  import {
6
+ CLAIM_SELECT,
7
+ MARKETPLACE_OUTBOUND_JOB,
6
8
  MarketplaceAdapterRegistrationError,
9
+ NO_STANDING_REQUEST,
10
+ OUTBOUND_GIVE_UP_MS,
11
+ OUTBOUND_STALE_MS,
7
12
  OutboundRetryError,
8
13
  PROVIDER_ID_PATTERN,
9
14
  createAdapterRegistry,
15
+ enqueueOutbound,
16
+ failCancellationRequest,
10
17
  listMarketplaceIntegrations,
11
18
  markMarketplaceEventSeen,
19
+ notPendingProblem,
20
+ outboundDedupeKey,
21
+ planCancellation,
22
+ refusalData,
23
+ rejectConfirmed,
24
+ requestData,
25
+ requestsFirst,
12
26
  resolveIngestionTarget,
13
27
  resolveReason,
14
28
  resolveTenantByMerchant,
15
29
  runOutbound,
16
30
  saveMarketplaceIntegration,
17
- suggestReason
18
- } from "./chunk-6OODIO3E.js";
31
+ suggestReason,
32
+ sweepOutbound,
33
+ tellCancellationConfirmed,
34
+ tellCancellationFailed
35
+ } from "./chunk-DVIRN42O.js";
19
36
  import {
20
37
  __name
21
38
  } from "./chunk-7QVYU63E.js";
@@ -57,12 +74,15 @@ __name(listPendingAcceptances, "listPendingAcceptances");
57
74
  async function expireLapsedAcceptances(ctx, now) {
58
75
  const db = await ctx.ports.db();
59
76
  const lapsed = await db.marketplaceAcceptance.findMany({
60
- where: { status: "AWAITING", acknowledgeBy: { lt: now } },
77
+ // An order whose cancellation request waits is left to that request: its
78
+ // answer, or its window's TIMEOUT, ends it first (FUT-4758), so the host
79
+ // never hears EXPIRED and then the confirmation for one order.
80
+ where: { status: "AWAITING", acknowledgeBy: { lt: now }, ...NO_STANDING_REQUEST },
61
81
  select: { id: true, clientId: true, orderId: true }
62
82
  });
63
83
  if (lapsed.length === 0) return { expired: 0, tenants: 0 };
64
84
  const result = await db.marketplaceAcceptance.updateMany({
65
- where: { id: { in: lapsed.map((row) => row.id) }, status: "AWAITING" },
85
+ where: { id: { in: lapsed.map((row) => row.id) }, status: "AWAITING", ...NO_STANDING_REQUEST },
66
86
  data: { status: "EXPIRED", acknowledgedAt: now }
67
87
  });
68
88
  for (const row of lapsed) {
@@ -79,6 +99,10 @@ async function expireLapsedAcceptances(ctx, now) {
79
99
  return { expired: result.count, tenants: tenants.size };
80
100
  }
81
101
  __name(expireLapsedAcceptances, "expireLapsedAcceptances");
102
+ function hasConfirmHook(ctx) {
103
+ return ctx.ports.order.onCancellationConfirmed !== void 0;
104
+ }
105
+ __name(hasConfirmHook, "hasConfirmHook");
82
106
  async function cancelAcceptance(ctx, input) {
83
107
  const db = await ctx.ports.db();
84
108
  const row = await db.marketplaceAcceptance.findFirst({
@@ -87,20 +111,20 @@ async function cancelAcceptance(ctx, input) {
87
111
  provider: input.provider,
88
112
  externalOrderId: input.externalOrderId
89
113
  },
90
- select: { orderId: true }
114
+ select: { orderId: true, cancellationStatus: true }
91
115
  });
92
116
  if (!row) return false;
93
- await ctx.ports.transaction(async (tx) => {
94
- await tx.marketplaceAcceptance.updateMany({
95
- where: { orderId: row.orderId, status: { not: "REJECTED" } },
96
- data: { status: "REJECTED", acknowledgedAt: input.now ?? ctx.ports.clock.now() }
97
- });
98
- await tx.marketplaceAcceptance.updateMany({
117
+ const answered2 = await ctx.ports.transaction(async (tx) => {
118
+ await rejectConfirmed(tx, row.orderId, input.now ?? ctx.ports.clock.now());
119
+ const confirmed = await tx.marketplaceAcceptance.updateMany({
99
120
  where: { orderId: row.orderId, cancellationStatus: { in: ["PENDING", "REQUESTED", "FAILED"] } },
100
- data: { cancellationStatus: "CONFIRMED" }
121
+ data: { cancellationStatus: "CONFIRMED", cancellationFailureReason: null }
101
122
  });
123
+ return confirmed.count > 0;
102
124
  });
103
- await ctx.ports.order.onRefused(input.clientId, row.orderId, "CANCELLED");
125
+ const storeAsked = answered2 || row.cancellationStatus === "CONFIRMED";
126
+ const told = storeAsked && (answered2 ? await tellCancellationConfirmed(ctx, input.clientId, row.orderId) : hasConfirmHook(ctx));
127
+ if (!told) await ctx.ports.order.onRefused(input.clientId, row.orderId, "CANCELLED");
104
128
  ctx.ports.publishChanged(input.clientId);
105
129
  return true;
106
130
  }
@@ -313,103 +337,6 @@ async function upsertMenuLinks(ctx, input) {
313
337
  }
314
338
  __name(upsertMenuLinks, "upsertMenuLinks");
315
339
 
316
- // src/core/cancellation.ts
317
- var CLAIM_SELECT = {
318
- orderId: true,
319
- provider: true,
320
- status: true,
321
- cancellationStatus: true,
322
- lineSkus: true
323
- };
324
- function notPendingProblem(row, path, allowed = ["AWAITING"]) {
325
- if (!row) return { path: [...path, "orderId"], code: "NOT_FOUND" };
326
- if (allowed.includes(row.status) && row.cancellationStatus === null) return null;
327
- const status = row.status;
328
- return { path: [...path, "orderId"], code: status === "EXPIRED" ? "EXPIRED" : "ALREADY_DECIDED", status };
329
- }
330
- __name(notPendingProblem, "notPendingProblem");
331
- function lineSkusOf(row) {
332
- return Array.isArray(row.lineSkus) ? new Set(row.lineSkus.map(String)) : null;
333
- }
334
- __name(lineSkusOf, "lineSkusOf");
335
- function skuProblems(reason, skus, row, path) {
336
- if (reason?.needsItems && skus.length === 0) return [{ path: [...path, "offendingSkus"], code: "ITEMS_REQUIRED" }];
337
- const known = lineSkusOf(row);
338
- if (!known) return [];
339
- return skus.flatMap(
340
- (sku, index) => known.has(sku) ? [] : [{ path: [...path, "offendingSkus", index], code: "UNKNOWN_ITEM" }]
341
- );
342
- }
343
- __name(skuProblems, "skuProblems");
344
- function invalidReasonProblem(adapter, reason, code, path) {
345
- if (code === null || code === void 0 || reason) return null;
346
- const validCodes = adapter.cancellationReasons().map((candidate) => candidate.code);
347
- return { path: [...path, "reasonCode"], code: "INVALID_REASON", validCodes };
348
- }
349
- __name(invalidReasonProblem, "invalidReasonProblem");
350
- function planCancellation(adapter, input, row, path) {
351
- if (!adapter) return { status: null, reason: null, skus: [] };
352
- const reason = resolveReason(adapter, input.reasonCode);
353
- const invalid = invalidReasonProblem(adapter, reason, input.reasonCode, path);
354
- if (invalid) return [invalid];
355
- const skus = [...new Set(input.offendingSkus ?? [])];
356
- const problems = skuProblems(reason, skus, row, path);
357
- if (problems.length > 0) return problems;
358
- const { apiCancel, cancelAfterAccept } = adapter.capabilities;
359
- const canAsk = apiCancel && reason !== null && (row.status === "AWAITING" || cancelAfterAccept);
360
- return { status: canAsk ? "PENDING" : "FAILED", reason, skus };
361
- }
362
- __name(planCancellation, "planCancellation");
363
- function refusalData(plan, fromStatus, now) {
364
- return {
365
- status: "REJECTED",
366
- // An accepted row keeps the instant it was accepted; a row leaving the
367
- // clock is acknowledged now (the table's CHECK pairs the two).
368
- ...fromStatus === "AWAITING" ? { acknowledgedAt: now } : {},
369
- cancellationStatus: plan.status,
370
- cancellationReasonCode: plan.reason?.code ?? null,
371
- cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
372
- cancellationRequestedAt: plan.status === "PENDING" ? now : null
373
- };
374
- }
375
- __name(refusalData, "refusalData");
376
- async function failCancellationRequest(ctx, input) {
377
- const db = await ctx.ports.db();
378
- const moved = await db.marketplaceAcceptance.updateMany({
379
- where: {
380
- clientId: input.clientId,
381
- provider: input.provider,
382
- externalOrderId: input.externalOrderId,
383
- cancellationStatus: { in: ["PENDING", "REQUESTED"] }
384
- },
385
- data: { cancellationStatus: "FAILED" }
386
- });
387
- if (moved.count > 0) ctx.ports.publishChanged(input.clientId);
388
- return moved.count > 0;
389
- }
390
- __name(failCancellationRequest, "failCancellationRequest");
391
-
392
- // src/core/outbound-queue.ts
393
- var MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
394
- function outboundDedupeKey(payload) {
395
- return `${MARKETPLACE_OUTBOUND_JOB}:${payload.action}:${payload.orderId}`;
396
- }
397
- __name(outboundDedupeKey, "outboundDedupeKey");
398
- async function enqueueOutbound(ctx, payload, provider, dedupeKey = outboundDedupeKey(payload)) {
399
- const adapter = ctx.registry.get(provider);
400
- if (!adapter) return false;
401
- const able = payload.action === "confirm" ? adapter.capabilities.apiConfirm : adapter.capabilities.apiCancel;
402
- if (!able) return false;
403
- const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
404
- if (!outcome.enqueued) {
405
- ctx.ports.logger.warn(
406
- `${MARKETPLACE_OUTBOUND_JOB}: ${payload.action} for order ${payload.orderId} was not queued; the outbound sweep will re-queue it` + (outcome.reason ? ` (${outcome.reason})` : "")
407
- );
408
- }
409
- return outcome.enqueued;
410
- }
411
- __name(enqueueOutbound, "enqueueOutbound");
412
-
413
340
  // src/core/decisions.ts
414
341
  var Rollback = class extends Error {
415
342
  constructor(problems) {
@@ -432,29 +359,49 @@ function duplicateProblems(decisions) {
432
359
  });
433
360
  }
434
361
  __name(duplicateProblems, "duplicateProblems");
435
- function decidedOf(input, plan) {
362
+ function decidedOf(input, plan, keptStatus) {
363
+ const decided = input.decision === "ACCEPT" ? "ACCEPTED" : "REJECTED";
436
364
  return {
437
365
  orderId: input.orderId,
438
- status: input.decision === "ACCEPT" ? "ACCEPTED" : "REJECTED",
366
+ status: keptStatus ?? decided,
439
367
  cancellation: plan?.status ?? null,
440
368
  reasonCode: plan?.reason?.code ?? null,
441
369
  offendingSkus: plan?.skus ?? []
442
370
  };
443
371
  }
444
372
  __name(decidedOf, "decidedOf");
373
+ var CLEARED_REQUEST = {
374
+ cancellationStatus: null,
375
+ cancellationReasonCode: null,
376
+ cancellationOffendingSkus: null,
377
+ cancellationRequestedAt: null,
378
+ cancellationFailureReason: null
379
+ };
445
380
  function planOne(ctx, input, index, row, now) {
446
381
  const path = ["decisions", index];
447
382
  const stale = notPendingProblem(row, path);
448
383
  if (stale || !row) return stale ? [stale] : [];
449
384
  if (input.decision === "ACCEPT") {
450
- const data = { status: "ACCEPTED", acknowledgedAt: now, preparationMinutes: input.preparationMinutes ?? null };
451
- return { input, index, row, data, decided: decidedOf(input, null) };
385
+ const data = {
386
+ status: "ACCEPTED",
387
+ acknowledgedAt: now,
388
+ preparationMinutes: input.preparationMinutes ?? null,
389
+ ...row.cancellationStatus === null ? {} : CLEARED_REQUEST
390
+ };
391
+ return { input, index, row, data, decided: decidedOf(input, null), requestOnly: false };
452
392
  }
453
393
  const plan = planCancellation(ctx.registry.get(row.provider), input, row, path);
454
394
  if (Array.isArray(plan)) return plan;
455
- return { input, index, row, data: refusalData(plan, row.status, now), decided: decidedOf(input, plan) };
395
+ if (requestOnly(ctx, plan)) {
396
+ return { input, index, row, data: requestData(plan, now), decided: decidedOf(input, plan, row.status), requestOnly: true };
397
+ }
398
+ return { input, index, row, data: refusalData(plan, row.status, now), decided: decidedOf(input, plan), requestOnly: false };
456
399
  }
457
400
  __name(planOne, "planOne");
401
+ function requestOnly(ctx, plan) {
402
+ return requestsFirst(ctx) && plan.status !== null;
403
+ }
404
+ __name(requestOnly, "requestOnly");
458
405
  async function admitAndClaim(ctx, clientId, planned, validateOnly) {
459
406
  await ctx.ports.transaction(async (tx) => {
460
407
  const refused = [];
@@ -475,7 +422,7 @@ async function admitAndClaim(ctx, clientId, planned, validateOnly) {
475
422
  if (refused.length > 0) throw new Rollback(refused);
476
423
  for (const one of planned) {
477
424
  const claimed = await tx.marketplaceAcceptance.updateMany({
478
- where: { orderId: one.input.orderId, clientId, status: "AWAITING" },
425
+ where: { orderId: one.input.orderId, clientId, status: "AWAITING", ...NO_STANDING_REQUEST },
479
426
  data: one.data
480
427
  });
481
428
  if (claimed.count === 0) refused.push({ path: ["decisions", one.index, "orderId"], code: "CONFLICT" });
@@ -488,14 +435,15 @@ __name(admitAndClaim, "admitAndClaim");
488
435
  async function afterCommit(ctx, clientId, planned) {
489
436
  for (const one of planned) {
490
437
  const { orderId } = one.input;
491
- if (one.decided.status === "ACCEPTED") {
438
+ if (one.input.decision === "ACCEPT") {
492
439
  await enqueueOutbound(ctx, { clientId, orderId, action: "confirm" }, one.row.provider);
493
440
  } else if (one.decided.cancellation === "PENDING") {
494
441
  await enqueueOutbound(ctx, { clientId, orderId, action: "requestCancellation" }, one.row.provider);
495
442
  }
496
443
  try {
497
- if (one.decided.status === "ACCEPTED") await ctx.ports.order.onAccepted(clientId, orderId);
498
- else await ctx.ports.order.onRefused(clientId, orderId, "REJECTED");
444
+ if (one.decided.status === "ACCEPTED" && one.input.decision === "ACCEPT") await ctx.ports.order.onAccepted(clientId, orderId);
445
+ else if (!one.requestOnly) await ctx.ports.order.onRefused(clientId, orderId, "REJECTED");
446
+ else if (one.decided.cancellation === "FAILED") await tellCancellationFailed(ctx, clientId, orderId, "REFUSED");
499
447
  } catch (error) {
500
448
  ctx.ports.logger.error(
501
449
  `marketplace.decide: order ${orderId} is ${one.decided.status} but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
@@ -569,64 +517,26 @@ async function recordStoreCancellation(ctx, input) {
569
517
  if (stale || !row) return stale ? resultOfProblem(stale) : { kind: "stale", reason: "NOT_FOUND", status: null };
570
518
  const plan = planCancellation(ctx.registry.get(row.provider), input, row, []);
571
519
  if (Array.isArray(plan)) return resultOfProblem(plan[0]);
520
+ return claimStoreCancellation(ctx, input, row, plan);
521
+ }
522
+ __name(recordStoreCancellation, "recordStoreCancellation");
523
+ async function claimStoreCancellation(ctx, input, row, plan) {
572
524
  const now = input.now ?? ctx.ports.clock.now();
573
525
  const db = await ctx.ports.db();
526
+ const only = requestOnly(ctx, plan);
574
527
  const claimed = await db.marketplaceAcceptance.updateMany({
575
- where: { orderId: input.orderId, clientId: input.clientId, status: row.status, cancellationStatus: null },
576
- data: refusalData(plan, row.status, now)
528
+ where: { orderId: input.orderId, clientId: input.clientId, status: row.status, ...NO_STANDING_REQUEST },
529
+ data: only ? requestData(plan, now) : refusalData(plan, row.status, now)
577
530
  });
578
531
  if (claimed.count === 0) return { kind: "stale", reason: "CONFLICT", status: null };
579
532
  if (plan.status === "PENDING") {
580
533
  await enqueueOutbound(ctx, { clientId: input.clientId, orderId: input.orderId, action: "requestCancellation" }, row.provider);
581
534
  }
582
535
  ctx.ports.publishChanged(input.clientId);
583
- return { kind: "decided", ...decidedOf({ orderId: input.orderId, decision: "REJECT" }, plan) };
584
- }
585
- __name(recordStoreCancellation, "recordStoreCancellation");
586
-
587
- // src/core/outbound-sweep.ts
588
- var OUTBOUND_STALE_MS = 10 * 6e4;
589
- var OUTBOUND_GIVE_UP_MS = 24 * 60 * 6e4;
590
- var OWED_SELECT = { clientId: true, orderId: true, provider: true };
591
- function sweepDedupeKey(action, orderId, now) {
592
- return `${MARKETPLACE_OUTBOUND_JOB}:${action}:${orderId}:sweep:${now.getTime()}`;
593
- }
594
- __name(sweepDedupeKey, "sweepDedupeKey");
595
- async function requeue(ctx, rows, action, now) {
596
- let queued = 0;
597
- for (const row of rows) {
598
- const payload = { clientId: row.clientId, orderId: row.orderId, action };
599
- if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now))) queued += 1;
600
- }
601
- return queued;
602
- }
603
- __name(requeue, "requeue");
604
- async function sweepOutbound(ctx, now) {
605
- const db = await ctx.ports.db();
606
- const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);
607
- const giveUp = new Date(now.getTime() - OUTBOUND_GIVE_UP_MS);
608
- const abandoned = await db.marketplaceAcceptance.updateMany({
609
- where: { cancellationStatus: "PENDING", cancellationRequestedAt: { lt: giveUp } },
610
- data: { cancellationStatus: "FAILED" }
611
- });
612
- const cancellations = await db.marketplaceAcceptance.findMany({
613
- where: { cancellationStatus: "PENDING", cancellationRequestedAt: { lt: stale, gte: giveUp } },
614
- select: OWED_SELECT
615
- });
616
- const confirms = await db.marketplaceAcceptance.findMany({
617
- where: {
618
- status: "ACCEPTED",
619
- confirmedAt: null,
620
- confirmFailedAt: null,
621
- acknowledgedAt: { lt: stale, gte: giveUp }
622
- },
623
- select: OWED_SELECT
624
- });
625
- const requeued = await requeue(ctx, cancellations, "requestCancellation", now) + await requeue(ctx, confirms, "confirm", now);
626
- if (abandoned.count > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${abandoned.count} cancellation request(s).`);
627
- return { requeued, givenUp: abandoned.count };
536
+ if (only && plan.status === "FAILED") await tellCancellationFailed(ctx, input.clientId, input.orderId, "REFUSED");
537
+ return { kind: "decided", ...decidedOf({ orderId: input.orderId, decision: "REJECT" }, plan, only ? row.status : void 0) };
628
538
  }
629
- __name(sweepOutbound, "sweepOutbound");
539
+ __name(claimStoreCancellation, "claimStoreCancellation");
630
540
 
631
541
  // src/core/inbox.ts
632
542
  async function recordInboxEvent(ctx, input) {
@@ -881,7 +791,8 @@ async function readOrderStates(ctx, clientId, orderIds) {
881
791
  confirmedAt: true,
882
792
  confirmFailedAt: true,
883
793
  cancellationStatus: true,
884
- cancellationReasonCode: true
794
+ cancellationReasonCode: true,
795
+ cancellationFailureReason: true
885
796
  }
886
797
  });
887
798
  return new Map(
@@ -897,6 +808,7 @@ async function readOrderStates(ctx, clientId, orderIds) {
897
808
  confirmFailedAt: row.confirmFailedAt,
898
809
  cancellation: row.cancellationStatus,
899
810
  cancellationReasonCode: row.cancellationReasonCode,
811
+ cancellationFailure: row.cancellationFailureReason,
900
812
  appUrl: adapter ? adapter.appLink(row) : null
901
813
  };
902
814
  return [row.orderId, state];