@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.
Files changed (83) hide show
  1. package/ADOPTING.md +44 -9
  2. package/README.md +149 -4
  3. package/dist/99food/en-US.d.ts +19 -0
  4. package/dist/99food/en-US.js +23 -0
  5. package/dist/99food/en-US.js.map +1 -0
  6. package/dist/99food/index.d.ts +116 -0
  7. package/dist/99food/index.js +361 -0
  8. package/dist/99food/index.js.map +1 -0
  9. package/dist/99food/pt-BR.d.ts +23 -0
  10. package/dist/99food/pt-BR.js +23 -0
  11. package/dist/99food/pt-BR.js.map +1 -0
  12. package/dist/{adapter-CgCAYBSJ.d.ts → adapter-_iuSxvVD.d.ts} +41 -1
  13. package/dist/{chunk-OEKTWUQH.js → chunk-24RQZPSV.js} +1 -1
  14. package/dist/chunk-24RQZPSV.js.map +1 -0
  15. package/dist/chunk-BD7DS3XM.js +78 -0
  16. package/dist/chunk-BD7DS3XM.js.map +1 -0
  17. package/dist/{chunk-BEMTRJYM.js → chunk-CRYFYDQ2.js} +28 -4
  18. package/dist/{chunk-BEMTRJYM.js.map → chunk-CRYFYDQ2.js.map} +1 -1
  19. package/dist/chunk-D2X7TOR6.js +1240 -0
  20. package/dist/chunk-D2X7TOR6.js.map +1 -0
  21. package/dist/{engine-DDE0mnTu.d.ts → engine-D-a4mttc.d.ts} +117 -17
  22. package/dist/hono/index.d.ts +2 -2
  23. package/dist/hono/index.js +2 -2
  24. package/dist/ifood/index.d.ts +10 -12
  25. package/dist/ifood/index.js +19 -61
  26. package/dist/ifood/index.js.map +1 -1
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.js +113 -497
  29. package/dist/index.js.map +1 -1
  30. package/dist/manifest/server.d.ts +3 -2
  31. package/dist/manifest/server.js +2 -2
  32. package/dist/rappi/en-US.d.ts +14 -0
  33. package/dist/rappi/en-US.js +18 -0
  34. package/dist/rappi/en-US.js.map +1 -0
  35. package/dist/rappi/index.d.ts +190 -0
  36. package/dist/rappi/index.js +353 -0
  37. package/dist/rappi/index.js.map +1 -0
  38. package/dist/rappi/pt-BR.d.ts +18 -0
  39. package/dist/rappi/pt-BR.js +18 -0
  40. package/dist/rappi/pt-BR.js.map +1 -0
  41. package/dist/server/index.d.ts +12 -5
  42. package/dist/server/index.js +4 -2
  43. package/package.json +26 -2
  44. package/prisma/marketplace.prisma +12 -1
  45. package/prisma/migrations/20261112120000_marketplace_cancellation_failure/migration.sql +21 -0
  46. package/src/99food/copy.ts +36 -0
  47. package/src/99food/en-US.ts +19 -0
  48. package/src/99food/index.ts +121 -0
  49. package/src/99food/normalize.ts +263 -0
  50. package/src/99food/outbound.ts +220 -0
  51. package/src/99food/pt-BR.ts +23 -0
  52. package/src/core/acceptance.ts +30 -14
  53. package/src/core/adapter.ts +23 -1
  54. package/src/core/cancellation-outcome.ts +92 -0
  55. package/src/core/cancellation.ts +46 -15
  56. package/src/core/decisions.ts +94 -19
  57. package/src/core/engine.ts +8 -0
  58. package/src/core/fetch-order.ts +253 -0
  59. package/src/core/inbox.ts +8 -2
  60. package/src/core/ingest.ts +10 -2
  61. package/src/core/integration.ts +30 -1
  62. package/src/core/order-fetch-marks.ts +63 -0
  63. package/src/core/outbound-sweep.ts +87 -8
  64. package/src/core/outbound.ts +103 -7
  65. package/src/core/payload-read.ts +101 -0
  66. package/src/core/pipeline.ts +64 -15
  67. package/src/core/ports.ts +32 -0
  68. package/src/core/state.ts +6 -1
  69. package/src/core/types.ts +14 -0
  70. package/src/ifood/index.ts +9 -0
  71. package/src/ifood/normalize.ts +15 -88
  72. package/src/index.ts +10 -1
  73. package/src/rappi/copy.ts +39 -0
  74. package/src/rappi/en-US.ts +14 -0
  75. package/src/rappi/index.ts +155 -0
  76. package/src/rappi/normalize.ts +314 -0
  77. package/src/rappi/outbound.ts +182 -0
  78. package/src/rappi/pt-BR.ts +18 -0
  79. package/src/server/index.ts +1 -0
  80. package/src/server/jobs.ts +38 -4
  81. package/dist/chunk-6OODIO3E.js +0 -395
  82. package/dist/chunk-6OODIO3E.js.map +0 -1
  83. package/dist/chunk-OEKTWUQH.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { N as NormalizedEvent, M as MarketplaceAdapter } from '../adapter-CgCAYBSJ.js';
1
+ import { N as NormalizedEvent, M as MarketplaceAdapter } from '../adapter-_iuSxvVD.js';
2
2
 
3
3
  /**
4
4
  * The words the iFood adapter needs from its host, and nothing else.
@@ -22,16 +22,12 @@ interface IfoodAdapterCopy {
22
22
  }
23
23
 
24
24
  /**
25
- * Verify a delivery against the merchant's webhook secret.
26
- *
27
- * Unsigned deliveries are refused whenever a secret is CONFIGURED. A store that
28
- * has not set one yet is accepted — iFood's own onboarding issues the secret
29
- * after the merchant is certified, so refusing before then would make the
30
- * connection untestable — and that state is visible on the integration screen
31
- * rather than silent.
32
- *
33
- * Compared in constant time over bytes: an early-exit `===` on a hex digest
34
- * leaks the prefix a forger already got right, one request at a time.
25
+ * Verify a delivery against the merchant's webhook secret: iFood signs the raw
26
+ * body with HMAC-SHA256, hex. The rule (an unset secret accepts; a set one
27
+ * refuses an unsigned delivery; constant-time compare) is the engine's
28
+ * {@link verifyHmacSha256Hex}. iFood's own onboarding issues the secret after
29
+ * the merchant is certified, so refusing before then would make the
30
+ * connection untestable.
35
31
  */
36
32
  declare function verifyIfoodSignature(rawBody: string, signature: string | null, webhookSecret: string | null): boolean;
37
33
  /**
@@ -63,6 +59,8 @@ declare function normalizeIfoodEvent(payload: unknown, options: {
63
59
  */
64
60
  /** The provider id iFood is registered under. */
65
61
  declare const IFOOD_PROVIDER = "IFOOD";
62
+ /** How long iFood may take to answer a cancellation request: 5 minutes, ESTIMATED (see the adapter's capabilities). */
63
+ declare const IFOOD_CANCELLATION_ANSWER_WINDOW_MS: number;
66
64
  interface IfoodAdapterConfig {
67
65
  /** The words the adapter needs: reason labels and the missing-number text. Required. */
68
66
  copy: IfoodAdapterCopy;
@@ -70,4 +68,4 @@ interface IfoodAdapterConfig {
70
68
  /** Build the iFood adapter. Its reasons are static: a dialog never waits on iFood. */
71
69
  declare function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapter;
72
70
 
73
- export { IFOOD_PROVIDER, IFOOD_REASON_CODES, type IfoodAdapterConfig, type IfoodAdapterCopy, type IfoodReasonCode, createIfoodAdapter, normalizeIfoodEvent, verifyIfoodSignature };
71
+ export { IFOOD_CANCELLATION_ANSWER_WINDOW_MS, IFOOD_PROVIDER, IFOOD_REASON_CODES, type IfoodAdapterConfig, type IfoodAdapterCopy, type IfoodReasonCode, createIfoodAdapter, normalizeIfoodEvent, verifyIfoodSignature };
@@ -1,7 +1,15 @@
1
+ import {
2
+ asString,
3
+ firstCents,
4
+ firstDate,
5
+ firstString,
6
+ pick,
7
+ verifyHmacSha256Hex
8
+ } from "../chunk-BD7DS3XM.js";
1
9
  import {
2
10
  answered,
3
11
  outboundResultOf
4
- } from "../chunk-OEKTWUQH.js";
12
+ } from "../chunk-24RQZPSV.js";
5
13
  import {
6
14
  __name
7
15
  } from "../chunk-7QVYU63E.js";
@@ -23,69 +31,11 @@ var IFOOD_REASON_CODES = [
23
31
  ];
24
32
 
25
33
  // src/ifood/normalize.ts
26
- import { createHmac, timingSafeEqual } from "crypto";
27
34
  var ORDER_PLACED = /* @__PURE__ */ new Set(["PLC", "PLACED", "ORDER_PLACED"]);
28
35
  var ORDER_CANCELLED = /* @__PURE__ */ new Set(["CAN", "CANCELLED", "ORDER_CANCELLED"]);
29
36
  var CANCELLATION_REQUEST_FAILED = /* @__PURE__ */ new Set(["CARF", "CANCELLATION_REQUEST_FAILED"]);
30
- function pick(source, ...path) {
31
- let cursor = source;
32
- for (const key of path) {
33
- if (typeof cursor !== "object" || cursor === null) return void 0;
34
- cursor = cursor[key];
35
- }
36
- return cursor;
37
- }
38
- __name(pick, "pick");
39
- function asString(value) {
40
- if (typeof value === "string" && value.trim() !== "") return value.trim();
41
- if (typeof value === "number" && Number.isFinite(value)) return String(value);
42
- return null;
43
- }
44
- __name(asString, "asString");
45
- function firstString(source, paths) {
46
- for (const path of paths) {
47
- const found = asString(pick(source, ...path));
48
- if (found !== null) return found;
49
- }
50
- return null;
51
- }
52
- __name(firstString, "firstString");
53
- function firstCents(source, paths) {
54
- for (const path of paths) {
55
- const found = toCents(pick(source, ...path));
56
- if (found !== null) return found;
57
- }
58
- return null;
59
- }
60
- __name(firstCents, "firstCents");
61
- function toCents(value) {
62
- const numeric = typeof value === "string" ? Number(value) : value;
63
- if (typeof numeric !== "number" || !Number.isFinite(numeric)) return null;
64
- return Math.round(numeric * 100);
65
- }
66
- __name(toCents, "toCents");
67
- function toDate(value) {
68
- const raw = asString(value);
69
- if (!raw) return null;
70
- const parsed = new Date(raw);
71
- return Number.isNaN(parsed.getTime()) ? null : parsed;
72
- }
73
- __name(toDate, "toDate");
74
- function firstDate(source, paths) {
75
- for (const path of paths) {
76
- const found = toDate(pick(source, ...path));
77
- if (found !== null) return found;
78
- }
79
- return null;
80
- }
81
- __name(firstDate, "firstDate");
82
37
  function verifyIfoodSignature(rawBody, signature, webhookSecret) {
83
- if (!webhookSecret) return true;
84
- if (!signature) return false;
85
- const expected = createHmac("sha256", webhookSecret).update(rawBody, "utf8").digest("hex");
86
- const given = Buffer.from(signature.trim().toLowerCase().replace(/^sha256=/u, ""), "utf8");
87
- const mine = Buffer.from(expected, "utf8");
88
- return given.length === mine.length && timingSafeEqual(given, mine);
38
+ return verifyHmacSha256Hex(rawBody, signature, webhookSecret);
89
39
  }
90
40
  __name(verifyIfoodSignature, "verifyIfoodSignature");
91
41
  function readBuyer(order) {
@@ -265,6 +215,7 @@ __name(ifoodRequestCancellation, "ifoodRequestCancellation");
265
215
  // src/ifood/index.ts
266
216
  var IFOOD_PROVIDER = "IFOOD";
267
217
  var ITEM_UNAVAILABLE = "503";
218
+ var IFOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 6e4;
268
219
  function createIfoodAdapter(config) {
269
220
  const reasons = IFOOD_REASON_CODES.map((code) => ({
270
221
  code,
@@ -281,7 +232,13 @@ function createIfoodAdapter(config) {
281
232
  cancelAfterAccept: true,
282
233
  asyncCancellationOutcome: true,
283
234
  perOrderAppLink: false,
284
- confirmTakesPreparationTime: false
235
+ confirmTakesPreparationTime: false,
236
+ // How long iFood takes, at most, to answer a cancellation request: its
237
+ // CANCELLED or CANCELLATION_REQUEST_FAILED event. ESTIMATED, not read off
238
+ // iFood's documentation, which names no answer deadline: iFood answers a
239
+ // request in seconds when it answers at all, so 5 minutes is generous.
240
+ // A host overrides it with the engine's `cancellationWindowMs`.
241
+ cancellationAnswerWindowMs: IFOOD_CANCELLATION_ANSWER_WINDOW_MS
285
242
  },
286
243
  normalize: /* @__PURE__ */ __name((payload) => normalizeIfoodEvent(payload, normalizeOptions), "normalize"),
287
244
  readSignature: /* @__PURE__ */ __name((header) => header("x-ifood-signature") ?? header("x-signature"), "readSignature"),
@@ -296,6 +253,7 @@ function createIfoodAdapter(config) {
296
253
  }
297
254
  __name(createIfoodAdapter, "createIfoodAdapter");
298
255
  export {
256
+ IFOOD_CANCELLATION_ANSWER_WINDOW_MS,
299
257
  IFOOD_PROVIDER,
300
258
  IFOOD_REASON_CODES,
301
259
  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,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,SA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gB;AAKT,SAAS,yBACd,KACA,OACA,OACyB;AACzB,SAAO,UAAU,KAAK,MAAM,iBAAiB,uBAAuB;AAAA,IAClE,QAAQ,MAAM,SAAS,KAAK,MAAM,OAAO,QAAQ,MAAM;AAAA,IACvD,kBAAkB,MAAM,OAAO;AAAA,EACjC,CAAC;AACH;AATgB;;;AChFT,IAAM,iBAAiB;AAG9B,IAAM,mBAAoC;AAQnC,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,IAC/B;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;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 type {\n MarketplaceDeliveredBy,\n MarketplaceOrderType,\n NormalizedAddress,\n NormalizedBuyer,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n NormalizedOrderLine,\n} from \"../core/types\";\nimport {\n asString,\n firstCents,\n firstDate,\n firstString,\n pick,\n verifyHmacSha256Hex,\n} from \"../core/payload-read\";\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/**\n * Verify a delivery against the merchant's webhook secret: iFood signs the raw\n * body with HMAC-SHA256, hex. The rule (an unset secret accepts; a set one\n * refuses an unsigned delivery; constant-time compare) is the engine's\n * {@link verifyHmacSha256Hex}. iFood's own onboarding issues the secret after\n * the merchant is certified, so refusing before then would make the\n * connection untestable.\n */\nexport function verifyIfoodSignature(\n rawBody: string,\n signature: string | null,\n webhookSecret: string | null,\n): boolean {\n return verifyHmacSha256Hex(rawBody, signature, webhookSecret);\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;;;ACOA,IAAM,eAAe,oBAAI,IAAI,CAAC,OAAO,UAAU,cAAc,CAAC;AAC9D,IAAM,kBAAkB,oBA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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, F as FetchOrderJobPayload, k as FetchOrderOutcome, l as FetchOrderRetryError, I as IngestResult, m as IngestSettings, n as IngestionTarget, o as IntegrationRowInput, M as MARKETPLACE_FETCH_ORDER_JOB, p as MARKETPLACE_OUTBOUND_JOB, q as MarketplaceAdmission, r as MarketplaceAdmissionRequest, s as MarketplaceAdmissionResult, t as MarketplaceAuditEntry, u as MarketplaceAuditPort, v as MarketplaceClockPort, w as MarketplaceDb, x as MarketplaceEngine, y as MarketplaceEngineConfig, z as MarketplaceEnqueuePort, G as MarketplaceIntegrationView, H as MarketplaceLogger, J as MarketplaceMenuLinkView, K as MarketplaceOrderPort, L as MarketplaceOrderState, N as MarketplaceOrderSummary, O as MarketplacePorts, P as MarketplaceRefusal, Q as MarketplaceSecretsPort, R as MenuLinkRowInput, S as OUTBOUND_GIVE_UP_MS, T as OUTBOUND_STALE_MS, U as OutboundAction, V as OutboundAttempt, W as OutboundJobPayload, X as OutboundOutcome, Y as OutboundRetryError, Z as OutboundSweepResult, _ as PendingAcceptance, $ as PendingInboxEvent, a0 as ResolvedOrderLine, a1 as SaveMarketplaceIntegrationInput, a2 as createMarketplaceEngine, a3 as outboundDedupeKey } from './engine-D-a4mttc.js';
2
+ import { M as MarketplaceAdapter, b as MarketplaceProvider, C as CancellationReason } from './adapter-_iuSxvVD.js';
3
+ export { A as AdapterCallContext, c as AdapterTokenCache, d as CancellationOutcome, e as CancellationRequestInput, F as FetchOrderResult, f as MarketplaceCapabilities, g as MarketplaceCredentials, h as MarketplaceDeliveredBy, i as MarketplaceHttp, j as MarketplaceHttpRequest, k as MarketplaceHttpResponse, l as MarketplaceOrderType, m as NormalizedAddress, n as NormalizedBuyer, N as NormalizedEvent, a as NormalizedMarketplaceOrder, o as NormalizedOrderLine, O as OutboundOrderRef, p as OutboundResult, P as PROVIDER_ID_PATTERN, q as answered, r as outboundResultOf } from './adapter-_iuSxvVD.js';
4
4
 
5
5
  /**
6
6
  * The adapter registry: the ONE place a provider id becomes a marketplace.