@12-apps/marketplace 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/ADOPTING.md +29 -4
  2. package/README.md +92 -3
  3. package/dist/99food/index.d.ts +48 -2
  4. package/dist/99food/index.js +84 -1
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-_iuSxvVD.d.ts → adapter-0l_EmuJA.d.ts} +172 -2
  7. package/dist/{chunk-CRYFYDQ2.js → chunk-AYYBRQJV.js} +28 -4
  8. package/dist/chunk-AYYBRQJV.js.map +1 -0
  9. package/dist/chunk-M2V4RFMA.js +23 -0
  10. package/dist/chunk-M2V4RFMA.js.map +1 -0
  11. package/dist/{chunk-24RQZPSV.js → chunk-RVBTARIY.js} +1 -1
  12. package/dist/chunk-RVBTARIY.js.map +1 -0
  13. package/dist/{chunk-D2X7TOR6.js → chunk-XUAFXNOH.js} +449 -85
  14. package/dist/chunk-XUAFXNOH.js.map +1 -0
  15. package/dist/{engine-D-a4mttc.d.ts → engine-CZsP8KWd.d.ts} +222 -2
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +2 -2
  18. package/dist/ifood/index.d.ts +10 -2
  19. package/dist/ifood/index.js +246 -69
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +30 -4
  22. package/dist/index.js +148 -9
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/server.d.ts +3 -2
  25. package/dist/manifest/server.js +2 -2
  26. package/dist/rappi/index.d.ts +1 -1
  27. package/dist/rappi/index.js +7 -1
  28. package/dist/rappi/index.js.map +1 -1
  29. package/dist/server/index.d.ts +12 -8
  30. package/dist/server/index.js +2 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +92 -1
  33. package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
  34. package/src/99food/catalogue.ts +117 -0
  35. package/src/99food/index.ts +4 -0
  36. package/src/99food/outbound.ts +3 -3
  37. package/src/core/adapter.ts +10 -1
  38. package/src/core/catalogue-category.ts +119 -0
  39. package/src/core/catalogue-ids.ts +23 -0
  40. package/src/core/catalogue-job.ts +332 -0
  41. package/src/core/catalogue-port.ts +173 -0
  42. package/src/core/catalogue-store.ts +172 -0
  43. package/src/core/catalogue-sweep.ts +43 -0
  44. package/src/core/catalogue.ts +226 -0
  45. package/src/core/engine.ts +46 -0
  46. package/src/core/outbound-sweep.ts +7 -2
  47. package/src/core/ports.ts +36 -0
  48. package/src/ifood/catalogue.ts +273 -0
  49. package/src/ifood/index.ts +4 -0
  50. package/src/ifood/outbound.ts +9 -6
  51. package/src/index.ts +40 -0
  52. package/src/rappi/index.ts +6 -0
  53. package/src/server/jobs.ts +39 -9
  54. package/dist/chunk-24RQZPSV.js.map +0 -1
  55. package/dist/chunk-CRYFYDQ2.js.map +0 -1
  56. package/dist/chunk-D2X7TOR6.js.map +0 -1
@@ -1,7 +1,7 @@
1
- import { W as OutboundJobPayload, F as FetchOrderJobPayload } from '../engine-D-a4mttc.js';
1
+ import { a9 as OutboundJobPayload, F as FetchOrderJobPayload, j as CatalogueJobPayload } from '../engine-CZsP8KWd.js';
2
2
  import * as _12_apps_wiring from '@12-apps/wiring';
3
3
  import { createApiMarketplace, MarketplaceJobDeps } from '../server/index.js';
4
- import '../adapter-_iuSxvVD.js';
4
+ import '../adapter-0l_EmuJA.js';
5
5
  import 'zod';
6
6
 
7
7
  declare const marketplaceServerManifest: {
@@ -16,6 +16,7 @@ declare const marketplaceServerManifest: {
16
16
  readonly "reconcile-inbox": _12_apps_wiring.WireJobBlueprint<void, MarketplaceJobDeps>;
17
17
  readonly outbound: _12_apps_wiring.WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps>;
18
18
  readonly "fetch-order": _12_apps_wiring.WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps>;
19
+ readonly catalogue: _12_apps_wiring.WireJobBlueprint<CatalogueJobPayload, MarketplaceJobDeps>;
19
20
  readonly "outbound-sweep": _12_apps_wiring.WireJobBlueprint<void, MarketplaceJobDeps>;
20
21
  };
21
22
  };
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  MARKETPLACE_JOBS,
3
3
  createApiMarketplace
4
- } from "../chunk-CRYFYDQ2.js";
4
+ } from "../chunk-AYYBRQJV.js";
5
5
  import "../chunk-UYFYGGCS.js";
6
- import "../chunk-D2X7TOR6.js";
6
+ import "../chunk-XUAFXNOH.js";
7
7
  import "../chunk-7QVYU63E.js";
8
8
 
9
9
  // src/manifest/server.ts
@@ -1,4 +1,4 @@
1
- import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAdapter } from '../adapter-_iuSxvVD.js';
1
+ import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAdapter } from '../adapter-0l_EmuJA.js';
2
2
 
3
3
  /**
4
4
  * The words the Rappi adapter needs from its host, and nothing else.
@@ -8,7 +8,7 @@ import {
8
8
  import {
9
9
  answered,
10
10
  outboundResultOf
11
- } from "../chunk-24RQZPSV.js";
11
+ } from "../chunk-RVBTARIY.js";
12
12
  import {
13
13
  __name
14
14
  } from "../chunk-7QVYU63E.js";
@@ -317,6 +317,12 @@ function createRappiAdapter(config) {
317
317
  const normalizeOptions = { amountUnit: config.amountUnit, missingStreetNumber: config.copy.missingStreetNumber };
318
318
  return {
319
319
  provider: RAPPI_PROVIDER,
320
+ // No `catalogue` (FUT-4768). Rappi's public menu write, `POST …/menu`,
321
+ // replaces the store's WHOLE menu, goes to an approval, and ignores every
322
+ // further menu while one is in approval: a per-product switch on it would
323
+ // wipe what the store keeps on Rappi's portal and report "in the catalogue"
324
+ // for a menu Rappi may have dropped. Its availability endpoints only turn
325
+ // items Rappi already has on and off. See the README, "Catalogue publishing".
320
326
  capabilities: {
321
327
  apiConfirm: true,
322
328
  apiCancel: true,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/rappi/copy.ts","../../src/rappi/normalize.ts","../../src/rappi/outbound.ts","../../src/rappi/index.ts"],"sourcesContent":["/**\n * The words the Rappi 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 * The `cancel_type` values a store may send with `PUT orders/{orderId}/reject`,\n * verbatim from Rappi's public API reference (dev-portal.rappi.com,\n * api-reference/orders, \"PUT orders/{orderId}/reject\"). Pinned by the portal,\n * not estimated.\n */\nexport const RAPPI_REASON_CODES = [\n \"ITEM_OUT_OF_STOCK\",\n \"ITEM_NOT_FOUND\",\n \"ITEM_WRONG_PRICE\",\n \"ORDER_MISSING_INFORMATION\",\n \"ORDER_MISSING_ADDRESS_INFORMATION\",\n \"ORDER_TOTAL_INCORRECT\",\n] as const;\n\nexport type RappiReasonCode = (typeof RAPPI_REASON_CODES)[number];\n\n/**\n * The codes with which the portal REQUIRES the offending items (\"If the value\n * informed for cancel_type is one of the following: ITEM_WRONG_PRICE,\n * ITEM_NOT_FOUND, ITEM_OUT_OF_STOCK. It would be required to include the\n * offending items\").\n */\nexport const RAPPI_ITEM_REASON_CODES: readonly RappiReasonCode[] = [\"ITEM_OUT_OF_STOCK\", \"ITEM_NOT_FOUND\", \"ITEM_WRONG_PRICE\"];\n\nexport interface RappiAdapterCopy {\n /** One label per reason code. Sent as the reject's required `reason` text. */\n reasonLabels: Readonly<Record<RappiReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import { asString, firstDate, firstString, pick, verifyHmacSha256Hex } from \"../core/payload-read\";\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceOrderType,\n NormalizedAddress,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n NormalizedOrderLine,\n} from \"../core/types\";\n\n/**\n * The Rappi adapter's INBOUND half, from Rappi's public developer portal\n * (dev-portal.rappi.com: webhook-events, api-reference/orders), read\n * 2026-11-13.\n *\n * Rappi registers one webhook URL PER EVENT, and its payloads do not name the\n * event they are. So the event is read from the body's shape, as the portal\n * documents each one:\n *\n * - `NEW_ORDER` is \"the same information that we can get from the getOrders\n * endpoint\": one element of `GET orders`, an `order_detail` (with `items`,\n * `totals`, `delivery_information`) beside `customer` and `store`.\n * - `NEW_ORDER_SCHEDULED` is that shape plus `\"action\": \"scheduled\"`, every\n * price zero (the real order follows as `NEW_ORDER`); recorded, ignored.\n * - `NEW_ORDER_SCHEDULED_CANCELLED` is `\"action\": \"cancelled\"` with an\n * `order_detail.order_id`: an order never released to the store; ignored.\n * - `ORDER_EVENT_CANCEL` is `{ event, order_id, store_id }`, `event` naming the\n * cancellation (`canceled_with_charge`).\n * - `ORDER_OTHER_EVENT` is `{ event, order_id, store_id, event_time,\n * additional_information }`; recorded, ignored.\n *\n * ESTIMATED, until the Rappi sandbox confirms it: telling ORDER_EVENT_CANCEL\n * from ORDER_OTHER_EVENT. The portal shows one example of each and names no\n * list of `event` values, so a payload is a cancellation only when it has\n * neither `event_time` nor `additional_information` AND its `event` names a\n * cancellation (`cancel` in it, which `canceled_with_charge` has). Anything\n * else is recorded and IGNORED: a missed cancellation is visible in the inbox,\n * a false one would cancel a live order.\n *\n * Rappi payloads carry no event id, so the inbox key is derived from the\n * order and the event, deterministic so a redelivery collides on the inbox's\n * unique index.\n */\n\n/** The provider id Rappi is registered under. Uppercase: the column's CHECK holds that shape. */\nexport const RAPPI_PROVIDER = \"RAPPI\";\n\n/** The header Rappi signs every webhook in (the portal: \"Rappi-Signature\"; headers are case-insensitive). */\nexport const RAPPI_SIGNATURE_HEADER = \"rappi-signature\";\n\n/**\n * How Rappi states money. The portal types every amount as an `integer` and\n * names no unit (its examples are Colombian and Mexican pesos). Whether a\n * Brazilian store's `price: 2890` is R$ 28,90 or R$ 2.890 is not public, so\n * it is the adapter's REQUIRED config: `MINOR_UNITS` (cents) or `MAJOR_UNITS`\n * (whole reais). ESTIMATED until the sandbox shows a Brazilian order.\n */\nexport type RappiAmountUnit = \"MINOR_UNITS\" | \"MAJOR_UNITS\";\n\nexport interface RappiNormalizeOptions {\n amountUnit: RappiAmountUnit;\n missingStreetNumber: string;\n}\n\n/**\n * Verify a delivery, as the portal's \"Validating Your Signature\" says:\n * `Rappi-Signature: t=<timestamp>,sign=<signature>`; the signed payload is\n * the timestamp, `.`, and the raw body as it arrived; HMAC-SHA256 keyed by\n * the webhook's secret. The digest's encoding is not stated: the portal's\n * example `sign` is 64 hex characters, so it is read as lowercase hex\n * (ESTIMATED). Compared in constant time.\n *\n * The secret is REQUIRED: Rappi gives it when the webhook is registered, so a\n * connection without one refuses every delivery (an unsigned\n * ORDER_EVENT_CANCEL for a known order id would otherwise cancel it). No\n * timestamp tolerance is applied: the portal states none, and a replayed\n * delivery is a duplicate in the inbox.\n */\nexport function verifyRappiSignature(rawBody: string, header: string | null, webhookSecret: string | null): boolean {\n if (!webhookSecret || !header) return false;\n const parts = signatureParts(header);\n if (parts.t === null || parts.sign === null) return false;\n return verifyHmacSha256Hex(`${parts.t}.${rawBody}`, parts.sign, webhookSecret);\n}\n\n/** `t=…,sign=…` split on \",\" then on the first \"=\", as the portal describes. No regex. */\nfunction signatureParts(header: string): { t: string | null; sign: string | null } {\n const found: { t: string | null; sign: string | null } = { t: null, sign: null };\n for (const element of header.split(\",\")) {\n const at = element.indexOf(\"=\");\n if (at < 0) continue;\n const key = element.slice(0, at).trim().toLowerCase();\n const value = element.slice(at + 1).trim();\n if (value === \"\") continue;\n if (key === \"t\") found.t = value;\n if (key === \"sign\") found.sign = value;\n }\n return found;\n}\n\n/** Rappi's store id, from wherever this event shape keeps it. */\nfunction storeIdOf(payload: unknown): string | null {\n return firstString(payload, [[\"store\", \"internal_id\"], [\"order_detail\", \"store\", \"internal_id\"], [\"order_detail\", \"store_id\"], [\"store_id\"]]);\n}\n\n/** One event's frame; the order is filled by the caller. */\nfunction eventOf(\n orderId: string,\n eventType: string,\n payload: unknown,\n extra: Partial<NormalizedEvent> & { eventId?: string } = {},\n): NormalizedEvent {\n return {\n provider: RAPPI_PROVIDER,\n eventId: `${orderId}:${eventType}`,\n eventType,\n externalMerchantId: storeIdOf(payload),\n externalOrderId: orderId,\n order: null,\n cancelled: false,\n cancellationOutcome: null,\n ...extra,\n };\n}\n\n/** A shape with an `order_detail`: NEW_ORDER, or one of the scheduled notices. */\nfunction orderDetailEvent(payload: unknown, options: RappiNormalizeOptions): NormalizedEvent | null {\n const orderId = firstString(payload, [[\"order_detail\", \"order_id\"]]);\n if (!orderId) return null;\n const action = firstString(payload, [[\"action\"]])?.toLowerCase() ?? null;\n if (action === \"scheduled\") return eventOf(orderId, \"NEW_ORDER_SCHEDULED\", payload);\n if (action === \"cancelled\") return eventOf(orderId, \"NEW_ORDER_SCHEDULED_CANCELLED\", payload);\n return eventOf(orderId, \"NEW_ORDER\", payload, { order: normalizeRappiOrder(payload, options) });\n}\n\n/** Whether `event` names a cancellation: \"cancel\" in it, case-insensitive. ESTIMATED (see the file header). */\nfunction namesCancellation(event: string): boolean {\n return event.toLowerCase().includes(\"cancel\");\n}\n\n/** A shape with a top-level `order_id`: ORDER_EVENT_CANCEL or ORDER_OTHER_EVENT (and the tracking stream). */\nfunction orderEvent(payload: unknown): NormalizedEvent | null {\n const orderId = firstString(payload, [[\"order_id\"]]);\n if (!orderId) return null;\n const event = firstString(payload, [[\"event\"]]) ?? \"UNKNOWN\";\n const other = pick(payload, \"event_time\") !== undefined || pick(payload, \"additional_information\") !== undefined;\n const cancelled = !other && namesCancellation(event);\n const eventType = cancelled ? \"ORDER_EVENT_CANCEL\" : \"ORDER_OTHER_EVENT\";\n const at = asString(pick(payload, \"event_time\"));\n return eventOf(orderId, eventType, payload, {\n eventId: [orderId, eventType, event, ...(at ? [at] : [])].join(\":\"),\n cancelled,\n cancellationOutcome: cancelled ? \"CONFIRMED\" : null,\n });\n}\n\n/**\n * Normalize one webhook delivery. Null only when it names no order (PING,\n * MENU_*, STORE_CONNECTIVITY, STORE_PROVISIONING_STATUS): nothing to key on.\n */\nexport function normalizeRappiEvent(payload: unknown, options: RappiNormalizeOptions): NormalizedEvent | null {\n const detail = pick(payload, \"order_detail\");\n if (typeof detail === \"object\" && detail !== null) return orderDetailEvent(payload, options);\n return orderEvent(payload);\n}\n\n/** An amount as Rappi states it, in cents; null when absent or not a number. */\nfunction amountCents(value: unknown, unit: RappiAmountUnit): number | null {\n const numeric = typeof value === \"string\" && value.trim() !== \"\" ? Number(value) : value;\n if (typeof numeric !== \"number\" || !Number.isFinite(numeric)) return null;\n return Math.round(unit === \"MAJOR_UNITS\" ? numeric * 100 : numeric);\n}\n\n/** A stated count, 1 when absent or nonsense. */\nfunction countOf(source: unknown): number {\n const stated = Number(pick(source, \"quantity\") ?? 1);\n return Number.isFinite(stated) && stated > 0 ? stated : 1;\n}\n\nfunction arrayAt(source: unknown, ...path: string[]): unknown[] {\n const found = pick(source, ...path);\n return Array.isArray(found) ? found : [];\n}\n\n/**\n * One unit's price: the item's `price` (\"Unit price for the item without the\n * discount\") plus each subitem's `price × quantity`. ESTIMATED: the portal\n * does not say whether a subitem's quantity is per unit of its item or for the\n * whole line; it is read per unit (a topping on each salad of three).\n */\nfunction unitCents(item: unknown, unit: RappiAmountUnit): number {\n const base = amountCents(pick(item, \"price\"), unit) ?? 0;\n return arrayAt(item, \"subitems\").reduce<number>(\n (sum, sub) => sum + (amountCents(pick(sub, \"price\"), unit) ?? 0) * countOf(sub),\n base,\n );\n}\n\n/** The ticket's note: the subitems (a topping, a dressing) and the buyer's comments. */\nfunction lineNote(item: unknown): string | null {\n const subitems = arrayAt(item, \"subitems\")\n .map((sub) => {\n const name = asString(pick(sub, \"name\"));\n const quantity = countOf(sub);\n return name && quantity > 1 ? `${quantity}x ${name}` : name;\n })\n .filter((name): name is string => name !== null);\n // `comments` is typed an array and shown as a string in the same reference.\n const rawComments = pick(item, \"comments\");\n const comments = (Array.isArray(rawComments) ? rawComments : [rawComments])\n .map(asString)\n .filter((comment): comment is string => comment !== null);\n const note = [subitems.join(\", \"), ...comments].filter((part) => part !== \"\").join(\" · \");\n return note === \"\" ? null : note;\n}\n\n/**\n * One `order_detail.items[]` entry → its lines, which add up EXACTLY to the\n * item's total. A whole quantity is one row at the unit price (`unit × q` is\n * the total, nothing to divide); a fractional one (the portal types quantity\n * an integer, so this is defensive) is one row at its rounded total.\n *\n * The key is the item's `sku` (the store's own, \"the ally grants their own\n * SKU\"), then Rappi's `id`, then the name: an unmapped line is recoverable, a\n * dropped one is not.\n */\nfunction readLines(item: unknown, unit: RappiAmountUnit): NormalizedOrderLine[] {\n const name = firstString(item, [[\"name\"]]);\n const sku = firstString(item, [[\"sku\"], [\"id\"]]) ?? name;\n if (!sku) return [];\n const quantity = countOf(item);\n const each = unitCents(item, unit);\n const row = Number.isInteger(quantity)\n ? { quantity, unitPriceCents: each }\n : { quantity: 1, unitPriceCents: Math.round(each * quantity) };\n return [{ externalSku: sku, name: name ?? sku, ...row, note: lineNote(item) }];\n}\n\n/**\n * `delivery_method`: `delivery` (Rappi's courier), `marketplace` (the store's\n * own: the portal sends the customer's data \"only when delivery method is\n * marketplace\"), `pickup`.\n */\nfunction readMethod(detail: unknown): { orderType: MarketplaceOrderType | null; deliveredBy: MarketplaceDeliveredBy | null } {\n const method = firstString(detail, [[\"delivery_method\"]])?.toLowerCase();\n if (method === \"delivery\") return { orderType: \"DELIVERY\", deliveredBy: \"MARKETPLACE\" };\n if (method === \"marketplace\") return { orderType: \"DELIVERY\", deliveredBy: \"MERCHANT\" };\n if (method === \"pickup\") return { orderType: \"TAKEOUT\", deliveredBy: null };\n return { orderType: null, deliveredBy: null };\n}\n\n/** `order_detail.delivery_information`, the Brazilian fields included (`federal_unit`). */\nfunction readAddress(detail: unknown, missingStreetNumber: string): NormalizedAddress | null {\n const raw = pick(detail, \"delivery_information\");\n const street = firstString(raw, [[\"street_name\"], [\"complete_address\"]]);\n if (street === null) return null;\n return {\n street,\n number: firstString(raw, [[\"street_number\"]]) ?? missingStreetNumber,\n neighborhood: firstString(raw, [[\"neighborhood\"]]) ?? \"\",\n complement: firstString(raw, [[\"complement\"]]),\n reference: firstString(raw, [[\"description\"]]),\n postalCode: firstString(raw, [[\"postal_code\"]])?.replace(/\\D/g, \"\") || null,\n city: firstString(raw, [[\"city\"]]),\n state: firstString(raw, [[\"federal_unit\"]]),\n };\n}\n\n/** The buyer, top-level `customer` as the example has it, or under `order_detail` as the table names it. */\nfunction readBuyer(payload: unknown): NormalizedMarketplaceOrder[\"buyer\"] {\n const customer = pick(payload, \"customer\") ?? pick(payload, \"order_detail\", \"customer\");\n const name = [firstString(customer, [[\"first_name\"]]), firstString(customer, [[\"last_name\"]])]\n .filter((part): part is string => part !== null)\n .join(\" \");\n return { externalId: null, name: name === \"\" ? null : name, phone: firstString(customer, [[\"phone_number\"]]) };\n}\n\n/**\n * Normalize one getOrders element (the NEW_ORDER body). Null when it carries\n * no order id or no line.\n *\n * The total is `totals.total_order`, \"the total amount that the restaurant\n * receives\" (with tip and delivery fee when the store delivers): the figure\n * the store's receipt is reconciled against. Rappi states no commission, so\n * `commissionCents` is null (\"did not say\"), never 0. The merchant the order\n * names is Rappi's store id (`store.internal_id`), the id every other event\n * carries as `store_id`; the engine refuses it for another connection.\n */\nexport function normalizeRappiOrder(payload: unknown, options: RappiNormalizeOptions): NormalizedMarketplaceOrder | null {\n const detail = pick(payload, \"order_detail\");\n const externalOrderId = firstString(detail, [[\"order_id\"]]);\n const lines = arrayAt(detail, \"items\").flatMap((item) => readLines(item, options.amountUnit));\n if (!externalOrderId || lines.length === 0) return null;\n const method = readMethod(detail);\n return {\n provider: RAPPI_PROVIDER,\n externalOrderId,\n // Rappi's order id is the number its app and courier show.\n externalDisplayId: externalOrderId,\n externalMerchantId: storeIdOf(payload),\n buyer: readBuyer(payload),\n lines,\n totalCents:\n amountCents(pick(detail, \"totals\", \"total_order\"), options.amountUnit) ??\n lines.reduce((sum, line) => sum + line.unitPriceCents * line.quantity, 0),\n commissionCents: null,\n // Rappi states no delivery promise on the order.\n deliveryDueAt: null,\n placedAt: firstDate(detail, [[\"created_at\"]]) ?? new Date(),\n orderType: method.orderType,\n deliveredBy: method.deliveredBy,\n deliveryAddress: method.orderType === \"TAKEOUT\" ? null : readAddress(detail, options.missingStreetNumber),\n };\n}\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type MarketplaceHttpResponse,\n type OutboundOrderRef,\n type OutboundResult,\n} from \"../core/adapter\";\nimport { RAPPI_PROVIDER } from \"./normalize\";\n\n/**\n * The Rappi adapter's OUTBOUND half, from Rappi's public developer portal\n * (dev-portal.rappi.com: authentication-process, api-reference/orders), read\n * 2026-11-13: the token, take and reject. The job that calls these, its\n * retries and what a failure shows are the engine's.\n *\n * - Token: `POST https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`,\n * JSON `{ client_id, client_secret }`; \"the system responds with your\n * access_token\", valid \"1 week\"; sent as `x-authorization: Bearer <token>`.\n * - Take: `PUT https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api/orders/{orderId}/take/{cookingTime}`,\n * the cooking time optional (\"leave this field empty to keep the default\");\n * 200 taken, 400 \"Invalid state transition\", 404 not found.\n * - Reject: `PUT …/orders/{orderId}/reject` with `{ reason, cancel_type,\n * items_skus }`, only from SENT; 200 rejected, 400, 404.\n *\n * WHERE is not public per partner: the portal names its domains by country\n * (`{COUNTRY_DOMAIN}`, and a \"new\" one for the token), and Rappi's account\n * manager opens the sandbox. So the orders API's base and the token URL, per\n * environment, are the adapter's REQUIRED config, never a guessed default. Tests never reach\n * Rappi: the HTTP client is the host's port, answered by a fake.\n */\n\n/** One https URL per environment. */\nexport type RappiBaseUrls = Readonly<Record<\"SANDBOX\" | \"PRODUCTION\", string>>;\n\n/**\n * The two places the adapter calls, both host config (the portal's paths\n * carry the origin application's own noun, so they are the host's to state):\n * - `api`: the orders API's base, the portal's\n * `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api`, to\n * which the adapter appends `/orders/{orderId}/…`;\n * - `token`: the token endpoint itself, the portal's\n * `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`.\n */\nexport interface RappiHosts {\n api: RappiBaseUrls;\n token: RappiBaseUrls;\n}\n/** A token is renewed this long before it expires. */\nconst TOKEN_MARGIN_MS = 60_000;\n/**\n * The portal: \"Your access token has a validity of 1 week\". Used when the\n * answer states no `expires_in` (the answer's shape beyond `access_token` is\n * not shown: ESTIMATED).\n */\nconst DEFAULT_TOKEN_SECONDS = 7 * 24 * 60 * 60;\n\n/** A base URL with its trailing slashes cut, by a loop: a `/\\/+$/` regex backtracks polynomially on many slashes. */\nfunction trimmed(base: string): string {\n let end = base.length;\n while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;\n return base.slice(0, end);\n}\n\nconst tokenKey = (ctx: AdapterCallContext): string => `${RAPPI_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** The token answer, read defensively: `access_token`, and `expires_in` when present. */\nfunction tokenOf(body: string): { token: string; expiresInSeconds: number } | null {\n try {\n const parsed = JSON.parse(body) as { access_token?: unknown; expires_in?: unknown };\n if (typeof parsed.access_token !== \"string\" || parsed.access_token === \"\") return null;\n const expires =\n typeof parsed.expires_in === \"number\" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;\n return { token: parsed.access_token, expiresInSeconds: expires };\n } catch {\n return null;\n }\n}\n\n/**\n * A token from the per-process cache, or a fresh one from the token endpoint\n * (the M2M client credentials). Keyed by environment and client id; memory\n * only, written to no row or log.\n */\nasync function bearer(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n): Promise<{ token: string } | Exclude<OutboundResult, { kind: \"accepted\" }>> {\n const cached = ctx.tokens.get(tokenKey(ctx));\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: hosts.token[ctx.environment],\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ client_id: ctx.credentials.clientId, client_secret: ctx.credentials.clientSecret }),\n });\n if (response.status < 200 || response.status >= 300) {\n const result = outboundResultOf(response);\n return result.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected token answer\" } : result;\n }\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: \"Rappi answered the token request without a token\" };\n ctx.tokens.set(tokenKey(ctx), { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });\n return { token: token.token };\n}\n\n/** One authenticated PUT to an order's resource: the raw answer, or the result that ends it. */\nasync function putOrder(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n request: { externalOrderId: string; action: string; body?: unknown },\n): Promise<MarketplaceHttpResponse | Exclude<OutboundResult, { kind: \"accepted\" }>> {\n const auth = await bearer(ctx, hosts);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"PUT\",\n url: `${trimmed(hosts.api[ctx.environment])}/orders/${encodeURIComponent(request.externalOrderId)}/${request.action}`,\n headers: {\n \"x-authorization\": `Bearer ${auth.token}`,\n ...(request.body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(request.body === undefined ? {} : { body: JSON.stringify(request.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) return response;\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"Rappi refused the token\" };\n}\n\n/**\n * Take the order: `PUT …/orders/{orderId}/take/{cookingTime}`, the store's\n * preparation minutes as the cooking time, or `…/take/` to keep the order's\n * own (the portal: outside the order's range, Rappi uses the nearest bound).\n * The empty segment is how the portal's guide spells it\n * (`PUT /orders/{orderId}/take/`); ESTIMATED that Rappi's router serves it\n * (a 404 there would read as a refusal and show the portal link).\n * Every refused answer (400 \"Invalid state transition\", 404) is a refusal: the\n * store sees \"não confirmou\" and the app link.\n */\nexport function rappiTake(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n): Promise<OutboundResult> {\n const minutes = input.preparationMinutes === null ? \"\" : String(Math.round(input.preparationMinutes));\n return answered(async () => {\n const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: `take/${minutes}` });\n return \"kind\" in response ? response : outboundResultOf(response);\n });\n}\n\n/**\n * Reject the order: `PUT …/orders/{orderId}/reject` with `reason` (required\n * free text: the store's, else the reason's label), `cancel_type` (one of the\n * portal's six) and `items_skus` (the offending SKUs, required by the three\n * item reasons). The answer IS the outcome: 200 rejected (the engine stamps\n * CONFIRMED), any refusal FAILED with the app link.\n *\n * `items_skus` carries the engine's SKUs, which are the store's own `sku`\n * where the order states one. A line Rappi sent with no `sku` keys on Rappi's\n * item id, which the portal wants under `items_ids` instead; it is sent under\n * `items_skus` all the same (ESTIMATED: Rappi may refuse it, which reads as a\n * refusal and puts the app link in front of a person).\n */\nexport function rappiReject(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n): Promise<OutboundResult> {\n const body = {\n reason: input.text === \"\" ? input.reason.label : input.text,\n cancel_type: input.reason.code,\n ...(input.offendingSkus.length > 0 ? { items_skus: [...input.offendingSkus] } : {}),\n };\n return answered(async () => {\n const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: \"reject\", body });\n return \"kind\" in response ? response : outboundResultOf(response);\n });\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport { RAPPI_ITEM_REASON_CODES, RAPPI_REASON_CODES, type RappiAdapterCopy, type RappiReasonCode } from \"./copy\";\nimport {\n RAPPI_PROVIDER,\n RAPPI_SIGNATURE_HEADER,\n normalizeRappiEvent,\n verifyRappiSignature,\n type RappiAmountUnit,\n} from \"./normalize\";\nimport { rappiReject, rappiTake, type RappiBaseUrls } from \"./outbound\";\n\n/**\n * `@12-apps/marketplace/rappi` — Rappi, as one adapter on the engine.\n *\n * Built from Rappi's public developer portal (dev-portal.rappi.com), owner's\n * decision 2026-11-11: the NEW_ORDER webhook, take, reject and the M2M client\n * credentials. Everything Rappi is under this folder; the engine reaches it\n * only through the {@link MarketplaceAdapter} port, and registering it is the\n * whole cost:\n *\n * ```ts\n * import { createRappiAdapter } from \"@12-apps/marketplace/rappi\";\n * import { RAPPI_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/rappi/pt-BR\";\n *\n * createMarketplaceEngine({\n * …ports,\n * adapters: [\n * createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR }),\n * createRappiAdapter({ copy: RAPPI_ADAPTER_COPY_PT_BR, apiBaseUrl, tokenUrl, portalUrl, amountUnit }),\n * ],\n * });\n * ```\n *\n * Its webhooks (NEW_ORDER and ORDER_EVENT_CANCEL, each registered with Rappi\n * as its own subscription, all pointing at the same URL) are the engine's one\n * route, `POST /webhooks/marketplace/:tenantSlug/RAPPI`.\n *\n * What Rappi CANNOT do through its public API is stated, never inferred: a\n * reject is only accepted while the order is SENT (before it is taken), and\n * there is no public endpoint to cancel a taken order. So\n * `cancelAfterAccept` is false — the store's cancel of a taken Rappi order is\n * FAILED at once and opens Rappi's portal (the app link) — and the reject's\n * answer is the outcome (`asyncCancellationOutcome: false`).\n */\n\nexport { RAPPI_PROVIDER, RAPPI_SIGNATURE_HEADER } from \"./normalize\";\n\n/**\n * How long a reject may wait to be delivered. From the portal: an order in\n * SENT has \"a time limit of 6 minutes to take or reject the order, otherwise\n * it will transition to TIMEOUT status\", so a reject that has not reached Rappi\n * six minutes after it was asked can no longer be one. The request is failed\n * as TIMEOUT and a person finishes it on Rappi.\n *\n * ESTIMATED: Rappi counts its 6 minutes from the order's arrival, the engine\n * counts this window from the request. A reject asked late in Rappi's window\n * may still be sent after Rappi's TIMEOUT; Rappi then answers 400, which reads\n * as a refusal (FAILED, the portal link): slower than needed, never wrong.\n */\nexport const RAPPI_CANCELLATION_ANSWER_WINDOW_MS = 6 * 60_000;\n\n/** The one reason that means \"an item is unavailable\". */\nconst ITEM_UNAVAILABLE: RappiReasonCode = \"ITEM_OUT_OF_STOCK\";\n\nconst AMOUNT_UNITS: readonly RappiAmountUnit[] = [\"MINOR_UNITS\", \"MAJOR_UNITS\"];\n\nexport interface RappiAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: RappiAdapterCopy;\n /**\n * The orders API's base per environment, https: the portal's\n * `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api` (its\n * samples use the `https://microservices.dev.rappi.com` domain). The adapter\n * appends `/orders/{orderId}/take/…` and `/orders/{orderId}/reject`.\n * Required and defaultless: Rappi's account manager confirms the partner's\n * country domain.\n */\n apiBaseUrl: RappiBaseUrls;\n /**\n * The token endpoint per environment, https, whole: the portal's\n * `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`\n * (\"for integrations services\"). Required and defaultless.\n */\n tokenUrl: RappiBaseUrls;\n /** Where \"open it on Rappi\" goes: the partner portal (Rappi names no per-order link). Required; https only. */\n portalUrl: string;\n /** How Rappi states money for this host's country (see {@link RappiAmountUnit}). Required: ESTIMATED for Brazil. */\n amountUnit: RappiAmountUnit;\n}\n\nfunction assertHttps(name: string, url: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`@12-apps/marketplace/rappi: ${name} is not a URL.`);\n }\n if (parsed.protocol !== \"https:\") throw new Error(`@12-apps/marketplace/rappi: ${name} must be https.`);\n}\n\nfunction assertConfig(config: RappiAdapterConfig): void {\n for (const env of [\"SANDBOX\", \"PRODUCTION\"] as const) {\n assertHttps(`apiBaseUrl.${env}`, config.apiBaseUrl[env]);\n assertHttps(`tokenUrl.${env}`, config.tokenUrl[env]);\n }\n assertHttps(\"portalUrl\", config.portalUrl);\n if (!AMOUNT_UNITS.includes(config.amountUnit)) {\n throw new Error(`@12-apps/marketplace/rappi: amountUnit must be one of ${AMOUNT_UNITS.join(\", \")}.`);\n }\n}\n\n/** Build the Rappi adapter. Its reasons are static: a dialog never waits on Rappi. */\nexport function createRappiAdapter(config: RappiAdapterConfig): MarketplaceAdapter {\n assertConfig(config);\n const hosts = { api: { ...config.apiBaseUrl }, token: { ...config.tokenUrl } };\n const reasons: readonly CancellationReason[] = RAPPI_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === ITEM_UNAVAILABLE,\n needsItems: RAPPI_ITEM_REASON_CODES.includes(code),\n }));\n const normalizeOptions = { amountUnit: config.amountUnit, missingStreetNumber: config.copy.missingStreetNumber };\n return {\n provider: RAPPI_PROVIDER,\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n // Reject only from SENT; no public endpoint cancels a TAKEN order.\n cancelAfterAccept: false,\n // 200 is \"Order successfully rejected\": the answer is the outcome.\n asyncCancellationOutcome: false,\n perOrderAppLink: false,\n // `take/{cookingTime}`, in minutes.\n confirmTakesPreparationTime: true,\n cancellationAnswerWindowMs: RAPPI_CANCELLATION_ANSWER_WINDOW_MS,\n },\n normalize: (payload) => normalizeRappiEvent(payload, normalizeOptions),\n readSignature: (header) => header(RAPPI_SIGNATURE_HEADER),\n verifySignature: verifyRappiSignature,\n cancellationReasons: () => reasons,\n confirm: (ctx, order, input) => rappiTake(ctx, hosts, order, input),\n requestCancellation: (ctx, order, input) => rappiReject(ctx, hosts, order, input),\n appLink: () => config.portalUrl,\n };\n}\n\nexport { RAPPI_ITEM_REASON_CODES, RAPPI_REASON_CODES, type RappiAdapterCopy, type RappiReasonCode } from \"./copy\";\nexport {\n normalizeRappiEvent,\n normalizeRappiOrder,\n verifyRappiSignature,\n type RappiAmountUnit,\n type RappiNormalizeOptions,\n} from \"./normalize\";\nexport type { RappiBaseUrls, RappiHosts } from \"./outbound\";\n"],"mappings":";;;;;;;;;;;;;;;;AAcO,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAUO,IAAM,0BAAsD,CAAC,qBAAqB,kBAAkB,kBAAkB;;;ACctH,IAAM,i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W,OAAO,sBAAsB,GAAzC;AAAA,IACf,iBAAiB;AAAA,IACjB,qBAAqB,6BAAM,SAAN;AAAA,IACrB,SAAS,wBAAC,KAAK,OAAO,UAAU,UAAU,KAAK,OAAO,OAAO,KAAK,GAAzD;AAAA,IACT,qBAAqB,wBAAC,KAAK,OAAO,UAAU,YAAY,KAAK,OAAO,OAAO,KAAK,GAA3D;AAAA,IACrB,SAAS,6BAAM,OAAO,WAAb;AAAA,EACX;AACF;AAhCgB;","names":[]}
1
+ {"version":3,"sources":["../../src/rappi/copy.ts","../../src/rappi/normalize.ts","../../src/rappi/outbound.ts","../../src/rappi/index.ts"],"sourcesContent":["/**\n * The words the Rappi 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 * The `cancel_type` values a store may send with `PUT orders/{orderId}/reject`,\n * verbatim from Rappi's public API reference (dev-portal.rappi.com,\n * api-reference/orders, \"PUT orders/{orderId}/reject\"). Pinned by the portal,\n * not estimated.\n */\nexport const RAPPI_REASON_CODES = [\n \"ITEM_OUT_OF_STOCK\",\n \"ITEM_NOT_FOUND\",\n \"ITEM_WRONG_PRICE\",\n \"ORDER_MISSING_INFORMATION\",\n \"ORDER_MISSING_ADDRESS_INFORMATION\",\n \"ORDER_TOTAL_INCORRECT\",\n] as const;\n\nexport type RappiReasonCode = (typeof RAPPI_REASON_CODES)[number];\n\n/**\n * The codes with which the portal REQUIRES the offending items (\"If the value\n * informed for cancel_type is one of the following: ITEM_WRONG_PRICE,\n * ITEM_NOT_FOUND, ITEM_OUT_OF_STOCK. It would be required to include the\n * offending items\").\n */\nexport const RAPPI_ITEM_REASON_CODES: readonly RappiReasonCode[] = [\"ITEM_OUT_OF_STOCK\", \"ITEM_NOT_FOUND\", \"ITEM_WRONG_PRICE\"];\n\nexport interface RappiAdapterCopy {\n /** One label per reason code. Sent as the reject's required `reason` text. */\n reasonLabels: Readonly<Record<RappiReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import { asString, firstDate, firstString, pick, verifyHmacSha256Hex } from \"../core/payload-read\";\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceOrderType,\n NormalizedAddress,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n NormalizedOrderLine,\n} from \"../core/types\";\n\n/**\n * The Rappi adapter's INBOUND half, from Rappi's public developer portal\n * (dev-portal.rappi.com: webhook-events, api-reference/orders), read\n * 2026-11-13.\n *\n * Rappi registers one webhook URL PER EVENT, and its payloads do not name the\n * event they are. So the event is read from the body's shape, as the portal\n * documents each one:\n *\n * - `NEW_ORDER` is \"the same information that we can get from the getOrders\n * endpoint\": one element of `GET orders`, an `order_detail` (with `items`,\n * `totals`, `delivery_information`) beside `customer` and `store`.\n * - `NEW_ORDER_SCHEDULED` is that shape plus `\"action\": \"scheduled\"`, every\n * price zero (the real order follows as `NEW_ORDER`); recorded, ignored.\n * - `NEW_ORDER_SCHEDULED_CANCELLED` is `\"action\": \"cancelled\"` with an\n * `order_detail.order_id`: an order never released to the store; ignored.\n * - `ORDER_EVENT_CANCEL` is `{ event, order_id, store_id }`, `event` naming the\n * cancellation (`canceled_with_charge`).\n * - `ORDER_OTHER_EVENT` is `{ event, order_id, store_id, event_time,\n * additional_information }`; recorded, ignored.\n *\n * ESTIMATED, until the Rappi sandbox confirms it: telling ORDER_EVENT_CANCEL\n * from ORDER_OTHER_EVENT. The portal shows one example of each and names no\n * list of `event` values, so a payload is a cancellation only when it has\n * neither `event_time` nor `additional_information` AND its `event` names a\n * cancellation (`cancel` in it, which `canceled_with_charge` has). Anything\n * else is recorded and IGNORED: a missed cancellation is visible in the inbox,\n * a false one would cancel a live order.\n *\n * Rappi payloads carry no event id, so the inbox key is derived from the\n * order and the event, deterministic so a redelivery collides on the inbox's\n * unique index.\n */\n\n/** The provider id Rappi is registered under. Uppercase: the column's CHECK holds that shape. */\nexport const RAPPI_PROVIDER = \"RAPPI\";\n\n/** The header Rappi signs every webhook in (the portal: \"Rappi-Signature\"; headers are case-insensitive). */\nexport const RAPPI_SIGNATURE_HEADER = \"rappi-signature\";\n\n/**\n * How Rappi states money. The portal types every amount as an `integer` and\n * names no unit (its examples are Colombian and Mexican pesos). Whether a\n * Brazilian store's `price: 2890` is R$ 28,90 or R$ 2.890 is not public, so\n * it is the adapter's REQUIRED config: `MINOR_UNITS` (cents) or `MAJOR_UNITS`\n * (whole reais). ESTIMATED until the sandbox shows a Brazilian order.\n */\nexport type RappiAmountUnit = \"MINOR_UNITS\" | \"MAJOR_UNITS\";\n\nexport interface RappiNormalizeOptions {\n amountUnit: RappiAmountUnit;\n missingStreetNumber: string;\n}\n\n/**\n * Verify a delivery, as the portal's \"Validating Your Signature\" says:\n * `Rappi-Signature: t=<timestamp>,sign=<signature>`; the signed payload is\n * the timestamp, `.`, and the raw body as it arrived; HMAC-SHA256 keyed by\n * the webhook's secret. The digest's encoding is not stated: the portal's\n * example `sign` is 64 hex characters, so it is read as lowercase hex\n * (ESTIMATED). Compared in constant time.\n *\n * The secret is REQUIRED: Rappi gives it when the webhook is registered, so a\n * connection without one refuses every delivery (an unsigned\n * ORDER_EVENT_CANCEL for a known order id would otherwise cancel it). No\n * timestamp tolerance is applied: the portal states none, and a replayed\n * delivery is a duplicate in the inbox.\n */\nexport function verifyRappiSignature(rawBody: string, header: string | null, webhookSecret: string | null): boolean {\n if (!webhookSecret || !header) return false;\n const parts = signatureParts(header);\n if (parts.t === null || parts.sign === null) return false;\n return verifyHmacSha256Hex(`${parts.t}.${rawBody}`, parts.sign, webhookSecret);\n}\n\n/** `t=…,sign=…` split on \",\" then on the first \"=\", as the portal describes. No regex. */\nfunction signatureParts(header: string): { t: string | null; sign: string | null } {\n const found: { t: string | null; sign: string | null } = { t: null, sign: null };\n for (const element of header.split(\",\")) {\n const at = element.indexOf(\"=\");\n if (at < 0) continue;\n const key = element.slice(0, at).trim().toLowerCase();\n const value = element.slice(at + 1).trim();\n if (value === \"\") continue;\n if (key === \"t\") found.t = value;\n if (key === \"sign\") found.sign = value;\n }\n return found;\n}\n\n/** Rappi's store id, from wherever this event shape keeps it. */\nfunction storeIdOf(payload: unknown): string | null {\n return firstString(payload, [[\"store\", \"internal_id\"], [\"order_detail\", \"store\", \"internal_id\"], [\"order_detail\", \"store_id\"], [\"store_id\"]]);\n}\n\n/** One event's frame; the order is filled by the caller. */\nfunction eventOf(\n orderId: string,\n eventType: string,\n payload: unknown,\n extra: Partial<NormalizedEvent> & { eventId?: string } = {},\n): NormalizedEvent {\n return {\n provider: RAPPI_PROVIDER,\n eventId: `${orderId}:${eventType}`,\n eventType,\n externalMerchantId: storeIdOf(payload),\n externalOrderId: orderId,\n order: null,\n cancelled: false,\n cancellationOutcome: null,\n ...extra,\n };\n}\n\n/** A shape with an `order_detail`: NEW_ORDER, or one of the scheduled notices. */\nfunction orderDetailEvent(payload: unknown, options: RappiNormalizeOptions): NormalizedEvent | null {\n const orderId = firstString(payload, [[\"order_detail\", \"order_id\"]]);\n if (!orderId) return null;\n const action = firstString(payload, [[\"action\"]])?.toLowerCase() ?? null;\n if (action === \"scheduled\") return eventOf(orderId, \"NEW_ORDER_SCHEDULED\", payload);\n if (action === \"cancelled\") return eventOf(orderId, \"NEW_ORDER_SCHEDULED_CANCELLED\", payload);\n return eventOf(orderId, \"NEW_ORDER\", payload, { order: normalizeRappiOrder(payload, options) });\n}\n\n/** Whether `event` names a cancellation: \"cancel\" in it, case-insensitive. ESTIMATED (see the file header). */\nfunction namesCancellation(event: string): boolean {\n return event.toLowerCase().includes(\"cancel\");\n}\n\n/** A shape with a top-level `order_id`: ORDER_EVENT_CANCEL or ORDER_OTHER_EVENT (and the tracking stream). */\nfunction orderEvent(payload: unknown): NormalizedEvent | null {\n const orderId = firstString(payload, [[\"order_id\"]]);\n if (!orderId) return null;\n const event = firstString(payload, [[\"event\"]]) ?? \"UNKNOWN\";\n const other = pick(payload, \"event_time\") !== undefined || pick(payload, \"additional_information\") !== undefined;\n const cancelled = !other && namesCancellation(event);\n const eventType = cancelled ? \"ORDER_EVENT_CANCEL\" : \"ORDER_OTHER_EVENT\";\n const at = asString(pick(payload, \"event_time\"));\n return eventOf(orderId, eventType, payload, {\n eventId: [orderId, eventType, event, ...(at ? [at] : [])].join(\":\"),\n cancelled,\n cancellationOutcome: cancelled ? \"CONFIRMED\" : null,\n });\n}\n\n/**\n * Normalize one webhook delivery. Null only when it names no order (PING,\n * MENU_*, STORE_CONNECTIVITY, STORE_PROVISIONING_STATUS): nothing to key on.\n */\nexport function normalizeRappiEvent(payload: unknown, options: RappiNormalizeOptions): NormalizedEvent | null {\n const detail = pick(payload, \"order_detail\");\n if (typeof detail === \"object\" && detail !== null) return orderDetailEvent(payload, options);\n return orderEvent(payload);\n}\n\n/** An amount as Rappi states it, in cents; null when absent or not a number. */\nfunction amountCents(value: unknown, unit: RappiAmountUnit): number | null {\n const numeric = typeof value === \"string\" && value.trim() !== \"\" ? Number(value) : value;\n if (typeof numeric !== \"number\" || !Number.isFinite(numeric)) return null;\n return Math.round(unit === \"MAJOR_UNITS\" ? numeric * 100 : numeric);\n}\n\n/** A stated count, 1 when absent or nonsense. */\nfunction countOf(source: unknown): number {\n const stated = Number(pick(source, \"quantity\") ?? 1);\n return Number.isFinite(stated) && stated > 0 ? stated : 1;\n}\n\nfunction arrayAt(source: unknown, ...path: string[]): unknown[] {\n const found = pick(source, ...path);\n return Array.isArray(found) ? found : [];\n}\n\n/**\n * One unit's price: the item's `price` (\"Unit price for the item without the\n * discount\") plus each subitem's `price × quantity`. ESTIMATED: the portal\n * does not say whether a subitem's quantity is per unit of its item or for the\n * whole line; it is read per unit (a topping on each salad of three).\n */\nfunction unitCents(item: unknown, unit: RappiAmountUnit): number {\n const base = amountCents(pick(item, \"price\"), unit) ?? 0;\n return arrayAt(item, \"subitems\").reduce<number>(\n (sum, sub) => sum + (amountCents(pick(sub, \"price\"), unit) ?? 0) * countOf(sub),\n base,\n );\n}\n\n/** The ticket's note: the subitems (a topping, a dressing) and the buyer's comments. */\nfunction lineNote(item: unknown): string | null {\n const subitems = arrayAt(item, \"subitems\")\n .map((sub) => {\n const name = asString(pick(sub, \"name\"));\n const quantity = countOf(sub);\n return name && quantity > 1 ? `${quantity}x ${name}` : name;\n })\n .filter((name): name is string => name !== null);\n // `comments` is typed an array and shown as a string in the same reference.\n const rawComments = pick(item, \"comments\");\n const comments = (Array.isArray(rawComments) ? rawComments : [rawComments])\n .map(asString)\n .filter((comment): comment is string => comment !== null);\n const note = [subitems.join(\", \"), ...comments].filter((part) => part !== \"\").join(\" · \");\n return note === \"\" ? null : note;\n}\n\n/**\n * One `order_detail.items[]` entry → its lines, which add up EXACTLY to the\n * item's total. A whole quantity is one row at the unit price (`unit × q` is\n * the total, nothing to divide); a fractional one (the portal types quantity\n * an integer, so this is defensive) is one row at its rounded total.\n *\n * The key is the item's `sku` (the store's own, \"the ally grants their own\n * SKU\"), then Rappi's `id`, then the name: an unmapped line is recoverable, a\n * dropped one is not.\n */\nfunction readLines(item: unknown, unit: RappiAmountUnit): NormalizedOrderLine[] {\n const name = firstString(item, [[\"name\"]]);\n const sku = firstString(item, [[\"sku\"], [\"id\"]]) ?? name;\n if (!sku) return [];\n const quantity = countOf(item);\n const each = unitCents(item, unit);\n const row = Number.isInteger(quantity)\n ? { quantity, unitPriceCents: each }\n : { quantity: 1, unitPriceCents: Math.round(each * quantity) };\n return [{ externalSku: sku, name: name ?? sku, ...row, note: lineNote(item) }];\n}\n\n/**\n * `delivery_method`: `delivery` (Rappi's courier), `marketplace` (the store's\n * own: the portal sends the customer's data \"only when delivery method is\n * marketplace\"), `pickup`.\n */\nfunction readMethod(detail: unknown): { orderType: MarketplaceOrderType | null; deliveredBy: MarketplaceDeliveredBy | null } {\n const method = firstString(detail, [[\"delivery_method\"]])?.toLowerCase();\n if (method === \"delivery\") return { orderType: \"DELIVERY\", deliveredBy: \"MARKETPLACE\" };\n if (method === \"marketplace\") return { orderType: \"DELIVERY\", deliveredBy: \"MERCHANT\" };\n if (method === \"pickup\") return { orderType: \"TAKEOUT\", deliveredBy: null };\n return { orderType: null, deliveredBy: null };\n}\n\n/** `order_detail.delivery_information`, the Brazilian fields included (`federal_unit`). */\nfunction readAddress(detail: unknown, missingStreetNumber: string): NormalizedAddress | null {\n const raw = pick(detail, \"delivery_information\");\n const street = firstString(raw, [[\"street_name\"], [\"complete_address\"]]);\n if (street === null) return null;\n return {\n street,\n number: firstString(raw, [[\"street_number\"]]) ?? missingStreetNumber,\n neighborhood: firstString(raw, [[\"neighborhood\"]]) ?? \"\",\n complement: firstString(raw, [[\"complement\"]]),\n reference: firstString(raw, [[\"description\"]]),\n postalCode: firstString(raw, [[\"postal_code\"]])?.replace(/\\D/g, \"\") || null,\n city: firstString(raw, [[\"city\"]]),\n state: firstString(raw, [[\"federal_unit\"]]),\n };\n}\n\n/** The buyer, top-level `customer` as the example has it, or under `order_detail` as the table names it. */\nfunction readBuyer(payload: unknown): NormalizedMarketplaceOrder[\"buyer\"] {\n const customer = pick(payload, \"customer\") ?? pick(payload, \"order_detail\", \"customer\");\n const name = [firstString(customer, [[\"first_name\"]]), firstString(customer, [[\"last_name\"]])]\n .filter((part): part is string => part !== null)\n .join(\" \");\n return { externalId: null, name: name === \"\" ? null : name, phone: firstString(customer, [[\"phone_number\"]]) };\n}\n\n/**\n * Normalize one getOrders element (the NEW_ORDER body). Null when it carries\n * no order id or no line.\n *\n * The total is `totals.total_order`, \"the total amount that the restaurant\n * receives\" (with tip and delivery fee when the store delivers): the figure\n * the store's receipt is reconciled against. Rappi states no commission, so\n * `commissionCents` is null (\"did not say\"), never 0. The merchant the order\n * names is Rappi's store id (`store.internal_id`), the id every other event\n * carries as `store_id`; the engine refuses it for another connection.\n */\nexport function normalizeRappiOrder(payload: unknown, options: RappiNormalizeOptions): NormalizedMarketplaceOrder | null {\n const detail = pick(payload, \"order_detail\");\n const externalOrderId = firstString(detail, [[\"order_id\"]]);\n const lines = arrayAt(detail, \"items\").flatMap((item) => readLines(item, options.amountUnit));\n if (!externalOrderId || lines.length === 0) return null;\n const method = readMethod(detail);\n return {\n provider: RAPPI_PROVIDER,\n externalOrderId,\n // Rappi's order id is the number its app and courier show.\n externalDisplayId: externalOrderId,\n externalMerchantId: storeIdOf(payload),\n buyer: readBuyer(payload),\n lines,\n totalCents:\n amountCents(pick(detail, \"totals\", \"total_order\"), options.amountUnit) ??\n lines.reduce((sum, line) => sum + line.unitPriceCents * line.quantity, 0),\n commissionCents: null,\n // Rappi states no delivery promise on the order.\n deliveryDueAt: null,\n placedAt: firstDate(detail, [[\"created_at\"]]) ?? new Date(),\n orderType: method.orderType,\n deliveredBy: method.deliveredBy,\n deliveryAddress: method.orderType === \"TAKEOUT\" ? null : readAddress(detail, options.missingStreetNumber),\n };\n}\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type MarketplaceHttpResponse,\n type OutboundOrderRef,\n type OutboundResult,\n} from \"../core/adapter\";\nimport { RAPPI_PROVIDER } from \"./normalize\";\n\n/**\n * The Rappi adapter's OUTBOUND half, from Rappi's public developer portal\n * (dev-portal.rappi.com: authentication-process, api-reference/orders), read\n * 2026-11-13: the token, take and reject. The job that calls these, its\n * retries and what a failure shows are the engine's.\n *\n * - Token: `POST https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`,\n * JSON `{ client_id, client_secret }`; \"the system responds with your\n * access_token\", valid \"1 week\"; sent as `x-authorization: Bearer <token>`.\n * - Take: `PUT https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api/orders/{orderId}/take/{cookingTime}`,\n * the cooking time optional (\"leave this field empty to keep the default\");\n * 200 taken, 400 \"Invalid state transition\", 404 not found.\n * - Reject: `PUT …/orders/{orderId}/reject` with `{ reason, cancel_type,\n * items_skus }`, only from SENT; 200 rejected, 400, 404.\n *\n * WHERE is not public per partner: the portal names its domains by country\n * (`{COUNTRY_DOMAIN}`, and a \"new\" one for the token), and Rappi's account\n * manager opens the sandbox. So the orders API's base and the token URL, per\n * environment, are the adapter's REQUIRED config, never a guessed default. Tests never reach\n * Rappi: the HTTP client is the host's port, answered by a fake.\n */\n\n/** One https URL per environment. */\nexport type RappiBaseUrls = Readonly<Record<\"SANDBOX\" | \"PRODUCTION\", string>>;\n\n/**\n * The two places the adapter calls, both host config (the portal's paths\n * carry the origin application's own noun, so they are the host's to state):\n * - `api`: the orders API's base, the portal's\n * `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api`, to\n * which the adapter appends `/orders/{orderId}/…`;\n * - `token`: the token endpoint itself, the portal's\n * `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`.\n */\nexport interface RappiHosts {\n api: RappiBaseUrls;\n token: RappiBaseUrls;\n}\n/** A token is renewed this long before it expires. */\nconst TOKEN_MARGIN_MS = 60_000;\n/**\n * The portal: \"Your access token has a validity of 1 week\". Used when the\n * answer states no `expires_in` (the answer's shape beyond `access_token` is\n * not shown: ESTIMATED).\n */\nconst DEFAULT_TOKEN_SECONDS = 7 * 24 * 60 * 60;\n\n/** A base URL with its trailing slashes cut, by a loop: a `/\\/+$/` regex backtracks polynomially on many slashes. */\nfunction trimmed(base: string): string {\n let end = base.length;\n while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;\n return base.slice(0, end);\n}\n\nconst tokenKey = (ctx: AdapterCallContext): string => `${RAPPI_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** The token answer, read defensively: `access_token`, and `expires_in` when present. */\nfunction tokenOf(body: string): { token: string; expiresInSeconds: number } | null {\n try {\n const parsed = JSON.parse(body) as { access_token?: unknown; expires_in?: unknown };\n if (typeof parsed.access_token !== \"string\" || parsed.access_token === \"\") return null;\n const expires =\n typeof parsed.expires_in === \"number\" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;\n return { token: parsed.access_token, expiresInSeconds: expires };\n } catch {\n return null;\n }\n}\n\n/**\n * A token from the per-process cache, or a fresh one from the token endpoint\n * (the M2M client credentials). Keyed by environment and client id; memory\n * only, written to no row or log.\n */\nasync function bearer(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n): Promise<{ token: string } | Exclude<OutboundResult, { kind: \"accepted\" }>> {\n const cached = ctx.tokens.get(tokenKey(ctx));\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: hosts.token[ctx.environment],\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ client_id: ctx.credentials.clientId, client_secret: ctx.credentials.clientSecret }),\n });\n if (response.status < 200 || response.status >= 300) {\n const result = outboundResultOf(response);\n return result.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected token answer\" } : result;\n }\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: \"Rappi answered the token request without a token\" };\n ctx.tokens.set(tokenKey(ctx), { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });\n return { token: token.token };\n}\n\n/** One authenticated PUT to an order's resource: the raw answer, or the result that ends it. */\nasync function putOrder(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n request: { externalOrderId: string; action: string; body?: unknown },\n): Promise<MarketplaceHttpResponse | Exclude<OutboundResult, { kind: \"accepted\" }>> {\n const auth = await bearer(ctx, hosts);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"PUT\",\n url: `${trimmed(hosts.api[ctx.environment])}/orders/${encodeURIComponent(request.externalOrderId)}/${request.action}`,\n headers: {\n \"x-authorization\": `Bearer ${auth.token}`,\n ...(request.body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(request.body === undefined ? {} : { body: JSON.stringify(request.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) return response;\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"Rappi refused the token\" };\n}\n\n/**\n * Take the order: `PUT …/orders/{orderId}/take/{cookingTime}`, the store's\n * preparation minutes as the cooking time, or `…/take/` to keep the order's\n * own (the portal: outside the order's range, Rappi uses the nearest bound).\n * The empty segment is how the portal's guide spells it\n * (`PUT /orders/{orderId}/take/`); ESTIMATED that Rappi's router serves it\n * (a 404 there would read as a refusal and show the portal link).\n * Every refused answer (400 \"Invalid state transition\", 404) is a refusal: the\n * store sees \"não confirmou\" and the app link.\n */\nexport function rappiTake(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n): Promise<OutboundResult> {\n const minutes = input.preparationMinutes === null ? \"\" : String(Math.round(input.preparationMinutes));\n return answered(async () => {\n const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: `take/${minutes}` });\n return \"kind\" in response ? response : outboundResultOf(response);\n });\n}\n\n/**\n * Reject the order: `PUT …/orders/{orderId}/reject` with `reason` (required\n * free text: the store's, else the reason's label), `cancel_type` (one of the\n * portal's six) and `items_skus` (the offending SKUs, required by the three\n * item reasons). The answer IS the outcome: 200 rejected (the engine stamps\n * CONFIRMED), any refusal FAILED with the app link.\n *\n * `items_skus` carries the engine's SKUs, which are the store's own `sku`\n * where the order states one. A line Rappi sent with no `sku` keys on Rappi's\n * item id, which the portal wants under `items_ids` instead; it is sent under\n * `items_skus` all the same (ESTIMATED: Rappi may refuse it, which reads as a\n * refusal and puts the app link in front of a person).\n */\nexport function rappiReject(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n): Promise<OutboundResult> {\n const body = {\n reason: input.text === \"\" ? input.reason.label : input.text,\n cancel_type: input.reason.code,\n ...(input.offendingSkus.length > 0 ? { items_skus: [...input.offendingSkus] } : {}),\n };\n return answered(async () => {\n const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: \"reject\", body });\n return \"kind\" in response ? response : outboundResultOf(response);\n });\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport { RAPPI_ITEM_REASON_CODES, RAPPI_REASON_CODES, type RappiAdapterCopy, type RappiReasonCode } from \"./copy\";\nimport {\n RAPPI_PROVIDER,\n RAPPI_SIGNATURE_HEADER,\n normalizeRappiEvent,\n verifyRappiSignature,\n type RappiAmountUnit,\n} from \"./normalize\";\nimport { rappiReject, rappiTake, type RappiBaseUrls } from \"./outbound\";\n\n/**\n * `@12-apps/marketplace/rappi` — Rappi, as one adapter on the engine.\n *\n * Built from Rappi's public developer portal (dev-portal.rappi.com), owner's\n * decision 2026-11-11: the NEW_ORDER webhook, take, reject and the M2M client\n * credentials. Everything Rappi is under this folder; the engine reaches it\n * only through the {@link MarketplaceAdapter} port, and registering it is the\n * whole cost:\n *\n * ```ts\n * import { createRappiAdapter } from \"@12-apps/marketplace/rappi\";\n * import { RAPPI_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/rappi/pt-BR\";\n *\n * createMarketplaceEngine({\n * …ports,\n * adapters: [\n * createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR }),\n * createRappiAdapter({ copy: RAPPI_ADAPTER_COPY_PT_BR, apiBaseUrl, tokenUrl, portalUrl, amountUnit }),\n * ],\n * });\n * ```\n *\n * Its webhooks (NEW_ORDER and ORDER_EVENT_CANCEL, each registered with Rappi\n * as its own subscription, all pointing at the same URL) are the engine's one\n * route, `POST /webhooks/marketplace/:tenantSlug/RAPPI`.\n *\n * What Rappi CANNOT do through its public API is stated, never inferred: a\n * reject is only accepted while the order is SENT (before it is taken), and\n * there is no public endpoint to cancel a taken order. So\n * `cancelAfterAccept` is false — the store's cancel of a taken Rappi order is\n * FAILED at once and opens Rappi's portal (the app link) — and the reject's\n * answer is the outcome (`asyncCancellationOutcome: false`).\n */\n\nexport { RAPPI_PROVIDER, RAPPI_SIGNATURE_HEADER } from \"./normalize\";\n\n/**\n * How long a reject may wait to be delivered. From the portal: an order in\n * SENT has \"a time limit of 6 minutes to take or reject the order, otherwise\n * it will transition to TIMEOUT status\", so a reject that has not reached Rappi\n * six minutes after it was asked can no longer be one. The request is failed\n * as TIMEOUT and a person finishes it on Rappi.\n *\n * ESTIMATED: Rappi counts its 6 minutes from the order's arrival, the engine\n * counts this window from the request. A reject asked late in Rappi's window\n * may still be sent after Rappi's TIMEOUT; Rappi then answers 400, which reads\n * as a refusal (FAILED, the portal link): slower than needed, never wrong.\n */\nexport const RAPPI_CANCELLATION_ANSWER_WINDOW_MS = 6 * 60_000;\n\n/** The one reason that means \"an item is unavailable\". */\nconst ITEM_UNAVAILABLE: RappiReasonCode = \"ITEM_OUT_OF_STOCK\";\n\nconst AMOUNT_UNITS: readonly RappiAmountUnit[] = [\"MINOR_UNITS\", \"MAJOR_UNITS\"];\n\nexport interface RappiAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: RappiAdapterCopy;\n /**\n * The orders API's base per environment, https: the portal's\n * `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api` (its\n * samples use the `https://microservices.dev.rappi.com` domain). The adapter\n * appends `/orders/{orderId}/take/…` and `/orders/{orderId}/reject`.\n * Required and defaultless: Rappi's account manager confirms the partner's\n * country domain.\n */\n apiBaseUrl: RappiBaseUrls;\n /**\n * The token endpoint per environment, https, whole: the portal's\n * `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`\n * (\"for integrations services\"). Required and defaultless.\n */\n tokenUrl: RappiBaseUrls;\n /** Where \"open it on Rappi\" goes: the partner portal (Rappi names no per-order link). Required; https only. */\n portalUrl: string;\n /** How Rappi states money for this host's country (see {@link RappiAmountUnit}). Required: ESTIMATED for Brazil. */\n amountUnit: RappiAmountUnit;\n}\n\nfunction assertHttps(name: string, url: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`@12-apps/marketplace/rappi: ${name} is not a URL.`);\n }\n if (parsed.protocol !== \"https:\") throw new Error(`@12-apps/marketplace/rappi: ${name} must be https.`);\n}\n\nfunction assertConfig(config: RappiAdapterConfig): void {\n for (const env of [\"SANDBOX\", \"PRODUCTION\"] as const) {\n assertHttps(`apiBaseUrl.${env}`, config.apiBaseUrl[env]);\n assertHttps(`tokenUrl.${env}`, config.tokenUrl[env]);\n }\n assertHttps(\"portalUrl\", config.portalUrl);\n if (!AMOUNT_UNITS.includes(config.amountUnit)) {\n throw new Error(`@12-apps/marketplace/rappi: amountUnit must be one of ${AMOUNT_UNITS.join(\", \")}.`);\n }\n}\n\n/** Build the Rappi adapter. Its reasons are static: a dialog never waits on Rappi. */\nexport function createRappiAdapter(config: RappiAdapterConfig): MarketplaceAdapter {\n assertConfig(config);\n const hosts = { api: { ...config.apiBaseUrl }, token: { ...config.tokenUrl } };\n const reasons: readonly CancellationReason[] = RAPPI_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === ITEM_UNAVAILABLE,\n needsItems: RAPPI_ITEM_REASON_CODES.includes(code),\n }));\n const normalizeOptions = { amountUnit: config.amountUnit, missingStreetNumber: config.copy.missingStreetNumber };\n return {\n provider: RAPPI_PROVIDER,\n // No `catalogue` (FUT-4768). Rappi's public menu write, `POST …/menu`,\n // replaces the store's WHOLE menu, goes to an approval, and ignores every\n // further menu while one is in approval: a per-product switch on it would\n // wipe what the store keeps on Rappi's portal and report \"in the catalogue\"\n // for a menu Rappi may have dropped. Its availability endpoints only turn\n // items Rappi already has on and off. See the README, \"Catalogue publishing\".\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n // Reject only from SENT; no public endpoint cancels a TAKEN order.\n cancelAfterAccept: false,\n // 200 is \"Order successfully rejected\": the answer is the outcome.\n asyncCancellationOutcome: false,\n perOrderAppLink: false,\n // `take/{cookingTime}`, in minutes.\n confirmTakesPreparationTime: true,\n cancellationAnswerWindowMs: RAPPI_CANCELLATION_ANSWER_WINDOW_MS,\n },\n normalize: (payload) => normalizeRappiEvent(payload, normalizeOptions),\n readSignature: (header) => header(RAPPI_SIGNATURE_HEADER),\n verifySignature: verifyRappiSignature,\n cancellationReasons: () => reasons,\n confirm: (ctx, order, input) => rappiTake(ctx, hosts, order, input),\n requestCancellation: (ctx, order, input) => rappiReject(ctx, hosts, order, input),\n appLink: () => config.portalUrl,\n };\n}\n\nexport { RAPPI_ITEM_REASON_CODES, RAPPI_REASON_CODES, type RappiAdapterCopy, type RappiReasonCode } from \"./copy\";\nexport {\n normalizeRappiEvent,\n normalizeRappiOrder,\n verifyRappiSignature,\n type RappiAmountUnit,\n type RappiNormalizeOptions,\n} from \"./normalize\";\nexport type { RappiBaseUrls, RappiHosts } from \"./outbound\";\n"],"mappings":";;;;;;;;;;;;;;;;AAcO,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAUO,IAAM,0BAAsD,CAAC,qBAAqB,kBAAkB,kBAAkB;;;ACctH,IAAM,iBAAiB;AAGvB,IAAM,yBAAyB;AA8B/B,SAAS,qBAAqB,SAAiB,QAAuB,eAAuC;AAClH,MAAI,CAAC,iBAAiB,CAAC,OAAQ,QAAO;AACtC,QAAM,QAAQ,eAAe,MAAM;AACnC,MAAI,MAAM,MAAM,QAAQ,MAAM,SAAS,KAAM,QAAO;AACpD,SAAO,oBAAoB,GAAG,MAAM,CAAC,IAAI,OAAO,IAAI,MAAM,MAAM,aAAa;AAC/E;AALgB;AAQhB,SAAS,eAAe,QAA2D;AACjF,QAAM,QAAmD,EAAE,GAAG,MAAM,MAAM,KAAK;AAC/E,aAAW,WAAW,OAAO,MAAM,GAAG,GAAG;AACvC,UAAM,KAAK,QAAQ,QAAQ,GAAG;AAC9B,QAAI,KAAK,EAAG;AACZ,UAAM,MAAM,QAAQ,MAAM,GAAG,EAAE,EAAE,KAAK,EAAE,YAAY;AACpD,UAAM,QAAQ,QAAQ,MAAM,KAAK,CAAC,EAAE,KAAK;AACzC,QAAI,UAAU,GAAI;AAClB,QAAI,QAAQ,IAAK,OAAM,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AS,EAAE;AAC7E,QAAM,UAAyC,mBAAmB,IAAI,CAAC,UAAU;AAAA,IAC/E;AAAA,IACA,OAAO,OAAO,KAAK,aAAa,IAAI;AAAA,IACpC,iBAAiB,SAAS;AAAA,IAC1B,YAAY,wBAAwB,SAAS,IAAI;AAAA,EACnD,EAAE;AACF,QAAM,mBAAmB,EAAE,YAAY,OAAO,YAAY,qBAAqB,OAAO,KAAK,oBAAoB;AAC/G,SAAO;AAAA,IACL,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOV,cAAc;AAAA,MACZ,YAAY;AAAA,MACZ,WAAW;AAAA;AAAA,MAEX,mBAAmB;AAAA;AAAA,MAEnB,0BAA0B;AAAA,MAC1B,iBAAiB;AAAA;AAAA,MAEjB,6BAA6B;AAAA,MAC7B,4BAA4B;AAAA,IAC9B;AAAA,IACA,WAAW,wBAAC,YAAY,oBAAoB,SAAS,gBAAgB,GAA1D;AAAA,IACX,eAAe,wBAAC,WAAW,OAAO,sBAAsB,GAAzC;AAAA,IACf,iBAAiB;AAAA,IACjB,qBAAqB,6BAAM,SAAN;AAAA,IACrB,SAAS,wBAAC,KAAK,OAAO,UAAU,UAAU,KAAK,OAAO,OAAO,KAAK,GAAzD;AAAA,IACT,qBAAqB,wBAAC,KAAK,OAAO,UAAU,YAAY,KAAK,OAAO,OAAO,KAAK,GAA3D;AAAA,IACrB,SAAS,6BAAM,OAAO,WAAb;AAAA,EACX;AACF;AAtCgB;","names":[]}
@@ -1,7 +1,7 @@
1
- import { h as DecisionProblemCode, b as BulkProblemCode, x as MarketplaceEngine, H as MarketplaceLogger, W as OutboundJobPayload, F as FetchOrderJobPayload } from '../engine-D-a4mttc.js';
1
+ import { u as DecisionProblemCode, b as BulkProblemCode, U as MarketplaceEngine, Y as MarketplaceLogger, a9 as OutboundJobPayload, F as FetchOrderJobPayload, j as CatalogueJobPayload } from '../engine-CZsP8KWd.js';
2
2
  import { WireRoute, WireJobBlueprint } from '@12-apps/wiring';
3
3
  import { z } from 'zod';
4
- import '../adapter-_iuSxvVD.js';
4
+ import '../adapter-0l_EmuJA.js';
5
5
 
6
6
  /** Every problem code a route can answer, decisions and bulk writes alike. */
7
7
  type MarketplaceProblemCode = DecisionProblemCode | BulkProblemCode;
@@ -117,22 +117,25 @@ declare const MARKETPLACE_DECIDE = "marketplace:decide";
117
117
  * - `fetch-order`, on demand: one GET of an order a marketplace's event only
118
118
  * announced (`orderToFetch`), then the one ingest path. Three attempts with
119
119
  * backoff; the reconciliation sweep re-queues a row still owed.
120
+ * - `catalogue`, on demand: one publish or withdraw of one product on one
121
+ * marketplace's catalogue (FUT-4768). Three attempts with backoff; the
122
+ * last one stamps FAILED with a failure code.
120
123
  * - `outbound-sweep`, every five minutes: re-queues every call a row still
121
- * owes (a PENDING request, an accept with no confirm stamp) once it is older
122
- * than the job's own retry span, so a refused enqueue or a dead process
123
- * loses nothing.
124
+ * owes (a PENDING request, an accept with no confirm stamp, a catalogue
125
+ * publish or withdraw on its way) once it is older than the job's own retry
126
+ * span, so a refused enqueue or a dead process loses nothing.
124
127
  *
125
128
  * What stays the host's: whether to run them at all, on which runtime, and the
126
129
  * lease implementation. A host with no worker declines `jobs` in writing.
127
130
  *
128
131
  * Bound with `{ engine }`, these arrive at a runner as
129
132
  * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,
130
- * `marketplace.outbound`, `marketplace.fetch-order` and
131
- * `marketplace.outbound-sweep`.
133
+ * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.catalogue`
134
+ * and `marketplace.outbound-sweep`.
132
135
  */
133
136
  /** What the host closes over at bind time: the mounted engine. */
134
137
  interface MarketplaceJobDeps {
135
- engine: Pick<MarketplaceEngine, "expireLapsed" | "retryable" | "reprocess" | "runOutbound" | "runFetchOrder" | "sweepOutbound">;
138
+ engine: Pick<MarketplaceEngine, "expireLapsed" | "retryable" | "reprocess" | "runOutbound" | "runFetchOrder" | "runCatalogue" | "sweepOutbound">;
136
139
  }
137
140
  /** The single-flight queue name (`@12-apps/jobs`' `SWEEP_QUEUE`), as a literal. */
138
141
  declare const MARKETPLACE_SWEEP_QUEUE = "sweeps";
@@ -148,6 +151,7 @@ declare const MARKETPLACE_JOBS: {
148
151
  readonly "reconcile-inbox": WireJobBlueprint<void, MarketplaceJobDeps>;
149
152
  readonly outbound: WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps>;
150
153
  readonly "fetch-order": WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps>;
154
+ readonly catalogue: WireJobBlueprint<CatalogueJobPayload, MarketplaceJobDeps>;
151
155
  readonly "outbound-sweep": WireJobBlueprint<void, MarketplaceJobDeps>;
152
156
  };
153
157
  };
@@ -5,7 +5,7 @@ import {
5
5
  MARKETPLACE_SWEEP_QUEUE,
6
6
  ORDER_NOT_PENDING_CODE,
7
7
  createApiMarketplace
8
- } from "../chunk-CRYFYDQ2.js";
8
+ } from "../chunk-AYYBRQJV.js";
9
9
  import {
10
10
  MARKETPLACE_DECIDE,
11
11
  MARKETPLACE_MANAGE,
@@ -19,7 +19,7 @@ import {
19
19
  upsertMarketplaceIntegrationsBody,
20
20
  upsertMarketplaceMenuLinksBody
21
21
  } from "../chunk-UYFYGGCS.js";
22
- import "../chunk-D2X7TOR6.js";
22
+ import "../chunk-XUAFXNOH.js";
23
23
  import "../chunk-7QVYU63E.js";
24
24
  export {
25
25
  MARKETPLACE_DECIDE,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/marketplace",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "One marketplace integration engine for every marketplace: the durable inbox, the ingest pipeline, the acceptance clock and its sweep, the SKU map, the integration settings with sealed credentials, and the outbound engine (confirm, cancellation request, retries), behind an adapter port. Each marketplace is an adapter at its own subpath (./ifood, ./99food on Open Delivery, ./rappi). Framework-neutral wiring route descriptors (./server) with a Hono adapter (./hono), dep-free job blueprints, MCP tools and the package-owned Prisma partial + migrations.",
@@ -1,7 +1,7 @@
1
1
  // ---------------------------------------------------------------------------
2
2
  // @12-apps/marketplace — CANONICAL Prisma model partial.
3
3
  //
4
- // The four tables the marketplace engine owns. A host does NOT copy these
4
+ // The six tables the marketplace engine owns. A host does NOT copy these
5
5
  // models by hand: it composes this file into its multi-file schema folder from
6
6
  // the `db` capability (`package.json` "wiring.db"), and discovers the
7
7
  // migrations beside it.
@@ -250,3 +250,94 @@ model MarketplaceAcceptance {
250
250
  // SQL-only (migration 20261112120000), since Prisma cannot express the WHERE.
251
251
  @@map("marketplace_acceptances")
252
252
  }
253
+
254
+ /// One host product's place in one marketplace's catalogue (FUT-4768).
255
+ ///
256
+ /// One row per (store, marketplace, product): the store's switch for that
257
+ /// marketplace, and what the marketplace made of it. `productId` is an OPAQUE
258
+ /// host catalog id, like `menuItemId` above; the engine never reads the
259
+ /// product, the host maps it at send time.
260
+ ///
261
+ /// `status` is the MECHANISM's vocabulary (CHECK in the migration):
262
+ /// PUBLISHING (asked, not yet in the catalogue) → PUBLISHED, WITHDRAWING (asked
263
+ /// out) → WITHDRAWN, and FAILED with the marketplace's own reason. A FAILED row
264
+ /// is asked again by the same publish or withdraw.
265
+ model MarketplaceCataloguePublication {
266
+ id String @id @default(uuid())
267
+ clientId String @map("client_id")
268
+ provider String
269
+ /// The host product this row publishes. Opaque here.
270
+ productId String @map("product_id")
271
+
272
+ status String @default("PUBLISHING")
273
+
274
+ /// The store's price for THIS marketplace, in the smallest currency unit.
275
+ /// NULL is "the store's own price"; it never changes the store's price.
276
+ priceCents Int? @map("price_cents")
277
+ /// The price the last successful publish sent, whichever rule chose it.
278
+ sentPriceCents Int? @map("sent_price_cents")
279
+
280
+ /// The marketplace's id for the item, from the last successful publish.
281
+ externalId String? @map("external_id")
282
+
283
+ /// The photo the marketplace holds for the item: the adapter's reference to
284
+ /// it (iFood's uploaded `imagePath`) and the photo URL it was made from, so a
285
+ /// re-publish of the same photo does not upload it again.
286
+ imageRef String? @map("image_ref")
287
+ imageSourceUrl String? @map("image_source_url")
288
+ /// What the last successful publish could not do: IMAGE_TOO_LARGE |
289
+ /// IMAGE_REFUSED (CHECK); NULL when it did everything.
290
+ warningCode String? @map("warning_code")
291
+
292
+ /// Which action FAILED: PUBLISH | WITHDRAW (CHECK); NULL unless FAILED.
293
+ failedAction String? @map("failed_action")
294
+ /// Why it FAILED, a code the host words (CHECK): REFUSED, UNAVAILABLE,
295
+ /// TIMEOUT, NOT_CONNECTED, CREDENTIALS, PRODUCT_GONE, UNSUPPORTED, INTERNAL.
296
+ failureCode String? @map("failure_code")
297
+ /// The marketplace's OWN words for a REFUSED (truncated by the writer);
298
+ /// NULL for every other code. Never an engine message.
299
+ failureReason String? @map("failure_reason")
300
+
301
+ /// When the current action was asked: what the job matches its run to, and
302
+ /// what the outbound sweep ages a row still owed by.
303
+ requestedAt DateTime @map("requested_at")
304
+ publishedAt DateTime? @map("published_at")
305
+ withdrawnAt DateTime? @map("withdrawn_at")
306
+ failedAt DateTime? @map("failed_at")
307
+
308
+ createdAt DateTime @default(now()) @map("created_at")
309
+ updatedAt DateTime @updatedAt @map("updated_at")
310
+
311
+ // Named: Prisma's default (68 characters) is past Postgres's 63, which
312
+ // truncates it, and the database and the schema would then disagree.
313
+ @@unique([clientId, provider, productId], map: "marketplace_catalogue_publications_client_provider_product_key")
314
+ @@index([clientId, productId])
315
+ @@index([status, requestedAt])
316
+ @@map("marketplace_catalogue_publications")
317
+ }
318
+
319
+ /// The marketplace's id for one host category on one connection (FUT-4768).
320
+ ///
321
+ /// A marketplace that is written to (push) groups items in categories it
322
+ /// issues ids for, found or created by name. Stored so every publish into
323
+ /// the same category reuses one id, and CLAIMED while it is being created
324
+ /// (`claimedAt` set, `externalId` still NULL), so two products switched on at
325
+ /// once into a new category create it once, not twice.
326
+ model MarketplaceCatalogueCategory {
327
+ id String @id @default(uuid())
328
+ clientId String @map("client_id")
329
+ provider String
330
+ /// The host category's name, as the item carried it.
331
+ name String
332
+
333
+ /// The marketplace's id for it; NULL while it is being found or created.
334
+ externalId String? @map("external_id")
335
+ /// When a publish claimed the creation; a claim past its staleness is taken over.
336
+ claimedAt DateTime? @map("claimed_at")
337
+
338
+ createdAt DateTime @default(now()) @map("created_at")
339
+ updatedAt DateTime @updatedAt @map("updated_at")
340
+
341
+ @@unique([clientId, provider, name])
342
+ @@map("marketplace_catalogue_categories")
343
+ }
@@ -0,0 +1,97 @@
1
+ -- @domains: marketplace
2
+ -- @12-apps/marketplace: the catalogue publication (FUT-4768). Additive and
3
+ -- replay-safe, like the engine's other migrations: two new tables, their
4
+ -- indexes and their CHECKs. No column of an existing table changes.
5
+ --
6
+ -- One row per (store, marketplace, host product): whether the store wants the
7
+ -- product in that marketplace's catalogue, the price it set for that
8
+ -- marketplace (NULL: the store's own), and what the marketplace made of it.
9
+ -- `product_id` is a by-value scalar, like `menu_item_id`: no foreign key into
10
+ -- a host table.
11
+
12
+ CREATE TABLE IF NOT EXISTS "marketplace_catalogue_publications" (
13
+ "id" TEXT NOT NULL,
14
+ "client_id" TEXT NOT NULL,
15
+ "provider" TEXT NOT NULL,
16
+ "product_id" TEXT NOT NULL,
17
+ "status" TEXT NOT NULL DEFAULT 'PUBLISHING',
18
+ "price_cents" INTEGER,
19
+ "sent_price_cents" INTEGER,
20
+ "external_id" TEXT,
21
+ "image_ref" TEXT,
22
+ "image_source_url" TEXT,
23
+ "warning_code" TEXT,
24
+ "failed_action" TEXT,
25
+ "failure_code" TEXT,
26
+ "failure_reason" TEXT,
27
+ "requested_at" TIMESTAMP(3) NOT NULL,
28
+ "published_at" TIMESTAMP(3),
29
+ "withdrawn_at" TIMESTAMP(3),
30
+ "failed_at" TIMESTAMP(3),
31
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
32
+ "updated_at" TIMESTAMP(3) NOT NULL,
33
+
34
+ CONSTRAINT "marketplace_catalogue_publications_pkey" PRIMARY KEY ("id")
35
+ );
36
+
37
+ CREATE UNIQUE INDEX IF NOT EXISTS "marketplace_catalogue_publications_client_provider_product_key"
38
+ ON "marketplace_catalogue_publications"("client_id", "provider", "product_id");
39
+ CREATE INDEX IF NOT EXISTS "marketplace_catalogue_publications_client_id_product_id_idx"
40
+ ON "marketplace_catalogue_publications"("client_id", "product_id");
41
+ CREATE INDEX IF NOT EXISTS "marketplace_catalogue_publications_status_requested_at_idx"
42
+ ON "marketplace_catalogue_publications"("status", "requested_at");
43
+
44
+ DO $$ BEGIN
45
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_provider_shape"
46
+ CHECK ("provider" ~ '^[A-Z][A-Z0-9_]*$');
47
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
48
+
49
+ DO $$ BEGIN
50
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_status_check"
51
+ CHECK ("status" IN ('PUBLISHING', 'PUBLISHED', 'WITHDRAWING', 'WITHDRAWN', 'FAILED'));
52
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
53
+
54
+ DO $$ BEGIN
55
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_failed_action_check"
56
+ CHECK ("failed_action" IS NULL OR "failed_action" IN ('PUBLISH', 'WITHDRAW'));
57
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
58
+
59
+ DO $$ BEGIN
60
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_failure_code_check"
61
+ CHECK ("failure_code" IS NULL OR "failure_code" IN ('REFUSED', 'UNAVAILABLE', 'TIMEOUT', 'NOT_CONNECTED',
62
+ 'CREDENTIALS', 'PRODUCT_GONE', 'UNSUPPORTED', 'INTERNAL'));
63
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
64
+
65
+ DO $$ BEGIN
66
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_warning_code_check"
67
+ CHECK ("warning_code" IS NULL OR "warning_code" IN ('IMAGE_TOO_LARGE', 'IMAGE_REFUSED'));
68
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
69
+
70
+ DO $$ BEGIN
71
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_price_check"
72
+ CHECK (("price_cents" IS NULL OR "price_cents" > 0)
73
+ AND ("sent_price_cents" IS NULL OR "sent_price_cents" > 0));
74
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
75
+
76
+ -- The marketplace's id for one host category on one connection, found or
77
+ -- created by name once and reused; claimed while it is being created.
78
+ CREATE TABLE IF NOT EXISTS "marketplace_catalogue_categories" (
79
+ "id" TEXT NOT NULL,
80
+ "client_id" TEXT NOT NULL,
81
+ "provider" TEXT NOT NULL,
82
+ "name" TEXT NOT NULL,
83
+ "external_id" TEXT,
84
+ "claimed_at" TIMESTAMP(3),
85
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
86
+ "updated_at" TIMESTAMP(3) NOT NULL,
87
+
88
+ CONSTRAINT "marketplace_catalogue_categories_pkey" PRIMARY KEY ("id")
89
+ );
90
+
91
+ CREATE UNIQUE INDEX IF NOT EXISTS "marketplace_catalogue_categories_client_id_provider_name_key"
92
+ ON "marketplace_catalogue_categories"("client_id", "provider", "name");
93
+
94
+ DO $$ BEGIN
95
+ ALTER TABLE "marketplace_catalogue_categories" ADD CONSTRAINT "marketplace_catalogue_categories_provider_shape"
96
+ CHECK ("provider" ~ '^[A-Z][A-Z0-9_]*$');
97
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;