@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
package/ADOPTING.md CHANGED
@@ -6,8 +6,8 @@ Everything below is what a host binds, in the order it binds it.
6
6
 
7
7
  ## 1. The host ports (`MarketplacePorts`)
8
8
 
9
- Every field is REQUIRED. A missing one is a type error at mount, never a
10
- default that quietly adopts another host's policy.
9
+ Every field is REQUIRED unless marked OPTIONAL. A missing required one is a type
10
+ error at mount, never a default that quietly adopts another host's policy.
11
11
 
12
12
  | port | type | what the host answers |
13
13
  |---|---|---|
@@ -17,7 +17,9 @@ default that quietly adopts another host's policy.
17
17
  | `order.create` | `(clientId, order: NormalizedMarketplaceOrder, lines: readonly ResolvedOrderLine[], db: MarketplaceDb) => Promise<string>` | Create the host's own order from a normalized one; return its id. `lines[i].subjectRef` is the mapped catalog id or null (never refuse the order for a null). `db` is the ingest's transaction client: write the order through it, so the order and the acceptance row commit together (a lost race rolls the host's order back instead of leaving an orphan a redelivery would duplicate). |
18
18
  | `order.catalogHas` | `(clientId, subjectRef) => Promise<boolean>` | Does this catalog id exist and belong to this tenant? Asked before a SKU is mapped. |
19
19
  | `order.onAccepted` | `(clientId, orderId) => Promise<void>` | The store accepted, or the connection auto-accepts. Start whatever accepting means here (the ticket, the board). Runs after the commit and AFTER the confirm is queued; a throw is logged and cannot un-accept or lose the confirm. Atomic work (the stock draw) belongs in `admit`. |
20
- | `order.onRefused` | `(clientId, orderId, reason: "REJECTED" \| "EXPIRED" \| "CANCELLED") => Promise<void>` | Refuse/cancel the host order: the store refused on the clock, the clock lapsed, or the marketplace cancelled. After the commit and after the cancellation request is queued; a throw on a decision is logged. NOT called for `recordStoreCancellation` (the host's own cancel already ran). |
20
+ | `order.onRefused` | `(clientId, orderId, reason: "REJECTED" \| "EXPIRED" \| "CANCELLED") => Promise<void>` | Refuse/cancel the host order: the store refused on the clock, the clock lapsed, or the marketplace cancelled. After the commit and after the cancellation request is queued; a throw on a decision is logged. NOT called for `recordStoreCancellation`. A host that binds `onCancellationConfirmed` (request first) does not get `"REJECTED"` from `decide` either, nor `"CANCELLED"` for a cancellation the store asked for: `onCancellationConfirmed` replaces both. |
21
+ | `order.onCancellationConfirmed` | OPTIONAL — binding it OPTS IN to request first. `(clientId, orderId) => Promise<void>` | The marketplace CONFIRMED the store's own cancellation request (its event, or the job's answer for a marketplace that answers in the response); the row is REJECTED/CONFIRMED by then. Run the host's cancel here. Bound: the store's refusals and cancels (`decide` REJECT, `recordStoreCancellation`) only REQUEST the cancellation and keep the order as it was until this is called, once (a redelivered confirmation calls nothing), INSTEAD of `onRefused`. Not bound (a 1.0.0 host): everything as 1.0.0 — REJECTED at request time, `onRefused(…, "REJECTED")` from `decide`, and `onRefused(…, "CANCELLED")` on the confirmation. A throw is logged. |
22
+ | `order.onCancellationFailed` | OPTIONAL. `(clientId, orderId, reason: "REFUSED" \| "TIMEOUT") => Promise<void>` | The store's request FAILED: REFUSED (the marketplace's refusal event, the job's 4xx, its last attempt dying, or — request first — a marketplace whose API cannot take it, at once) or TIMEOUT (the outbound sweep, past the marketplace's answer window, or the 24-hour give-up). Called once, by the path that moved the row. Request first: the order stays as it was (AWAITING or ACCEPTED) and may be accepted again; show the adapter's app link and tell the person. A throw is logged. |
21
23
  | `order.summarize` | `(clientId, orderIds: readonly string[]) => Promise<Map<string, MarketplaceOrderSummary>>` | The queue's host facts in one read: `{ buyerName, totalCents, unmappedLines, createdAt }`. |
22
24
  | `secrets` | `{ seal(plaintext): string; open(sealed): string }` | Seal and open the credential blob with the host's key. `open` THROWS on a blob that will not open. |
23
25
  | `http` | `(req: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>` | The only way the engine reaches a marketplace. Answer any status; throw only when no answer arrived (timeout, network). The host owns the timeout, proxy and CA. |
@@ -29,6 +31,7 @@ default that quietly adopts another host's policy.
29
31
  | `defaultAckSlaSeconds` | `number` | The acceptance window a new connection gets (the origin host: 300). |
30
32
  | `reconcileBatchSize` | `number` | Stored deliveries one reconciliation pass re-runs (origin: 50). |
31
33
  | `maxInboxAttempts` | `number` | Re-runs before a stored delivery is retired (origin: 5). |
34
+ | `cancellationWindowMs` | OPTIONAL. `number` | For a host that requests first (binds `onCancellationConfirmed`): how long a store's cancellation request may wait (PENDING: not yet delivered, or REQUESTED: delivered and unanswered) before the outbound sweep fails it as TIMEOUT, for every adapter; a PENDING request's retries stop with it. A 1.0.0 host has no window: its requests are re-queued and given up after 24 hours, as before. Absent: each adapter's `capabilities.cancellationAnswerWindowMs` (iFood: 5 minutes, estimated); an adapter with none is given up on only after 24 hours. |
32
35
 
33
36
  Plus `adapters: readonly MarketplaceAdapter[]` — one per marketplace the host
34
37
  sells through. The list is validated at mount (ids, duplicates, reason lists).
@@ -61,9 +64,9 @@ export const engine = createMarketplaceEngine({
61
64
  | call | when |
62
65
  |---|---|
63
66
  | `decideMany({ clientId, decisions, validateOnly? })` / `decide({ clientId, ...decision })` | Every accept or refusal of an order on the clock, from every surface (the board, the admin route, the MCP tool). One decide path, all-or-nothing. A decision is `{ orderId, decision: "ACCEPT", admission?, preparationMinutes? }` or `{ orderId, decision: "REJECT", reasonCode?, offendingSkus? }`. `decide` answers `decided`, `stale` with `reason` (`ALREADY_DECIDED` with the `status` — answer an ACCEPTED one as done, I4 — `EXPIRED`, `NOT_FOUND`, `CONFLICT`), `invalidReason` (`INVALID_REASON`, `ITEMS_REQUIRED`, `UNKNOWN_ITEM`), or `refusedByHost` (your `admit`'s code). |
64
- | `recordStoreCancellation({ clientId, orderId, reasonCode?, offendingSkus? })` | After the host's own cancel of a marketplace order (before or after accepting it). Stamps the request and queues it; `stale` when the marketplace already cancelled it or a request was already made. |
67
+ | `recordStoreCancellation({ clientId, orderId, reasonCode?, offendingSkus? })` | The store cancels a marketplace order (before or after accepting it). Stamps the request and queues it. A host that binds no `onCancellationConfirmed` cancelled first and gets 1.0.0's stamps (REJECTED at once). A host that binds it (request first) gets the REQUEST only: the status stays AWAITING or ACCEPTED (and `decided.status` says so) until the marketplace confirms; a FAILED request may be asked again. `stale` when the marketplace already cancelled it or a request is already waiting. |
65
68
  | `suggestReason(provider, { itemUnavailable })` | To preselect a reason in the refusal dialog. The host judges the shortage. |
66
- | `orderStates(clientId, orderIds)` | The order reads: `{ status, confirmedAt, confirmFailedAt, cancellation, cancellationReasonCode, appUrl }` per marketplace order, one query. |
69
+ | `orderStates(clientId, orderIds)` | The order reads: `{ status, confirmedAt, confirmFailedAt, cancellation, cancellationReasonCode, cancellationFailure, appUrl }` per marketplace order, one query. `cancellation` PENDING or REQUESTED is a request still waiting: draw it as such. `cancellationFailure` is REFUSED or TIMEOUT when `cancellation` is FAILED. |
67
70
  | `adapter(provider)`, `reasons(provider)`, `appLink(provider, ref)` | The marketplace's capabilities, reasons and link, without naming it. |
68
71
  | `ingest(...)`, `deliver(...)` | A producer that hands over an order directly; the webhook does `deliver` for you. |
69
72
 
@@ -88,15 +91,20 @@ host.adoptServer({
88
91
  | capability | what it is |
89
92
  |---|---|
90
93
  | `http` | `POST /webhooks/marketplace/:tenantSlug/:provider` (`kind: "webhook"`, needs the raw `request`), and per entity one read and one bulk write under `/admin/:tenantSlug/marketplace`: `GET`/`PUT` (connections), `GET`/`PUT /menu-links`, `GET`/`POST /acceptances` (decisions). `@12-apps/marketplace/hono`'s `marketplaceRouter({ ...config, resolveActor })` mounts them in one line. |
91
- | `jobs` | `marketplace.expire-acceptances` (every minute, lease 5 min), `marketplace.reconcile-inbox` (every 5 min, lease 5 min), `marketplace.outbound` (3 attempts, exponential backoff 30 s), `marketplace.outbound-sweep` (every 5 min, lease 5 min: re-queues every call still owed after 10 min, gives a PENDING request up as FAILED after 24 h). Bind `{ engine }`. |
94
+ | `jobs` | `marketplace.expire-acceptances` (every minute, lease 5 min), `marketplace.reconcile-inbox` (every 5 min, lease 5 min), `marketplace.outbound` (3 attempts, exponential backoff 30 s), `marketplace.fetch-order` (on demand, 3 attempts, exponential backoff 5 s: the order body an event only announced; a host that holds it through its `enqueue` port holds every fetch), `marketplace.outbound-sweep` (every 5 min, lease 5 min: re-queues every call still owed after 10 min, gives a PENDING request up as FAILED after 24 h). Bind `{ engine }`. |
92
95
  | `mcp` | Six tools, the bulk-upsert protocol: `listMarketplaceIntegrations` / `upsertMarketplaceIntegrations` (operations `upsert`, `archive`, `unarchive`), `listMarketplaceMenuLinks` / `upsertMarketplaceMenuLinks`, `listMarketplaceAcceptances` / `decideMarketplaceOrders`. Every write takes a list, is all-or-nothing in one transaction, supports `validateOnly`, answers every problem with its path; reads take `ids`. Descriptions are English. |
93
96
  | `permissions` | `marketplace:manage` (connect, map) and `marketplace:decide` (read and answer the queue). The host decides which roles hold them; each route declares its own. |
94
97
  | `db` | `prisma/marketplace.prisma` + `prisma/migrations` (composed). |
95
98
  | `observability` | namespace `marketplace`. |
96
99
 
97
- The route copy (`MarketplaceServerCopy`) and the iFood adapter's copy
98
- (`IfoodAdapterCopy`) are required config; pt-BR and en-US packs ship beside
99
- each.
100
+ The route copy (`MarketplaceServerCopy`) and each adapter's copy
101
+ (`IfoodAdapterCopy`, `NinetyNineFoodAdapterCopy`, `RappiAdapterCopy`) are
102
+ required config; pt-BR and en-US packs ship beside each. The 99Food adapter
103
+ also requires its `apiBaseUrl` per environment and its `portalUrl`, which
104
+ 99Food gives a partner at onboarding. The Rappi adapter requires its
105
+ `apiBaseUrl` and `tokenUrl` per environment (on Rappi's country domains), its
106
+ `portalUrl` and its `amountUnit` (how Rappi states money for the host's
107
+ country); see the README's Rappi section for what is still ESTIMATED.
100
108
 
101
109
  ## 4. What the origin host changes when it adopts this package
102
110
 
@@ -142,6 +150,25 @@ each.
142
150
  number included, never the host's global client inside the callback: on PGlite, which
143
151
  runs one transaction at a time, a write on the global client hangs the ingest, and on
144
152
  Postgres a rolled-back ingest would leave an orphan order and a burnt order number.
153
+ 13. **Request first, cancel on confirm (1.1, FUT-4758) — opt in by binding
154
+ `order.onCancellationConfirmed`.** Without it, 1.0.0's behaviour holds, with two
155
+ differences, both harmless to a host whose cancel is idempotent: a marketplace that
156
+ confirms in its response now also moves the row to REJECTED and calls
157
+ `onRefused(…, "CANCELLED")` (1.0.0 called nothing there), and the event path keeps an
158
+ accepted order's `acknowledged_at` instead of overwriting it with the cancel time. With it, the
159
+ store's refusals and cancels (`decide` REJECT and `recordStoreCancellation`) only request
160
+ the cancellation; the order keeps its status until the marketplace confirms, and the
161
+ acceptance clock leaves an order with a waiting request alone (the request's window ends
162
+ it first). To opt in:
163
+ - bind `order.onCancellationConfirmed` (run the ordinary cancel there);
164
+ - call `recordStoreCancellation` from every cancel entry point, without cancelling;
165
+ - draw `orderStates(…).cancellation` PENDING/REQUESTED as "waiting for the marketplace";
166
+ - keep the store's own reason (its loss record, who asked) for that cancel: the engine
167
+ carries only the marketplace's code;
168
+ - bind `order.onCancellationFailed` (REFUSED or TIMEOUT: the order stays, show the app link);
169
+ - expect the answer window: a request still waiting past it (delivered or not) ends TIMEOUT;
170
+ - run migration `20261112120000_marketplace_cancellation_failure` (one nullable column,
171
+ its CHECK and an index), through the host's plugin-migration sync like the first.
145
172
 
146
173
  ## 5. The database
147
174
 
@@ -153,6 +180,14 @@ migration:
153
180
  - `marketplace_acceptances.order_id → <orders>(id) ON DELETE CASCADE`
154
181
  - `marketplace_menu_links.menu_item_id → <catalog>(id) ON DELETE SET NULL`
155
182
 
183
+ The migrations are replay-safe. `20261112120000_marketplace_cancellation_failure`
184
+ (1.1) adds `marketplace_acceptances.cancellation_failure_reason` (REFUSED or
185
+ TIMEOUT, CHECKed), and a PARTIAL index the expiry of waiting requests reads
186
+ (`marketplace_acceptances_cancellation_waiting_idx`, `WHERE cancellation_status IN
187
+ ('PENDING','REQUESTED')`). Prisma cannot express a partial index, so it is SQL-only and
188
+ the partial declares none: a host that diffs its schema against its database ignores it,
189
+ as it already does for the first migration's partial indexes.
190
+
156
191
  The migration `20261111200000_marketplace_engine` is replay-safe. On a host
157
192
  that already has the predecessor's tables it adds the outbound columns
158
193
  (including `cancellation_offending_skus`, `cancellation_requested_at`,
package/README.md CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  One integration engine for every marketplace a store sells through. Each
4
4
  marketplace is an **adapter** on that engine, shipped inside this package at
5
- its own subpath (`@12-apps/marketplace/ifood` today).
5
+ its own subpath (`@12-apps/marketplace/ifood`, `@12-apps/marketplace/99food`,
6
+ `@12-apps/marketplace/rappi`).
6
7
 
7
8
  ```ts
8
9
  import { createMarketplaceEngine } from "@12-apps/marketplace";
@@ -40,12 +41,13 @@ engine code (`src/__tests__/second-adapter.test.ts`).
40
41
  | **Pipeline** | normalize → inbox → ingest / cancel / cancellation-refused / ignore. Never throws. |
41
42
  | **Ingest** | Idempotent on `(provider, externalOrderId)`. Unmapped SKUs are rows on the attention list, never a rejection. The deadline is stamped at ingest; auto-accept is born accepted in one write and queues the confirm. |
42
43
  | **Acceptance clock** | `AWAITING → ACCEPTED | REJECTED | EXPIRED`, every transition predicated on the current state. The sweep never touches an accepted order. |
43
- | **Decisions** | Many at once, all-or-nothing: accept (with the person's admission and a preparation time), or refuse with a reason code validated against the adapter's own list and, for a reason that needs them, the order's offending SKUs. The host admits each decision inside the claim's transaction (`order.admit`: the stock ask, the draw). The store's own cancel through the host's flow stamps the request too. `suggestReason` preselects the item-unavailable reason when the host says stock is short. |
44
+ | **Decisions** | Many at once, all-or-nothing: accept (with the person's admission and a preparation time), or refuse with a reason code validated against the adapter's own list and, for a reason that needs them, the order's offending SKUs. The host admits each decision inside the claim's transaction (`order.admit`: the stock ask, the draw). For a host that binds `onCancellationConfirmed`, the store's refusal or cancel is a REQUEST: only the request moves, the order stays as it was until the marketplace answers, and the host hears the answer through the optional `onCancellationConfirmed` / `onCancellationFailed` (REFUSED or TIMEOUT). `suggestReason` preselects the item-unavailable reason when the host says stock is short. |
44
45
  | **SKU map** | External SKU → host catalog id, every SKU ever seen a row; mapping checks the id is the tenant's. |
45
46
  | **Integration settings** | Enabled, environment, merchant id, auto-accept, acknowledgement window; credentials sealed as one blob by the host's secrets port, never returned. A connection is archived (reversible, audited), never deleted. |
46
- | **Outbound engine** | The `marketplace.outbound` job: confirm after accept (with the preparation time where the marketplace takes one), cancellation request with the stored reason code and SKUs. 2xx done; a 4xx other than 408/425/429 refused and final; anything else retried until the last attempt, which ends FAILED whatever went wrong. Stamps `confirmed_at`, `confirm_failed_at`, `cancellation_status` (PENDING, REQUESTED, CONFIRMED, FAILED). Idempotent by the row. Queued BEFORE the host's half runs, and the `marketplace.outbound-sweep` job re-queues every call still owed, so nothing is lost. |
47
+ | **Outbound engine** | The `marketplace.outbound` job: confirm after accept (with the preparation time where the marketplace takes one), cancellation request with the stored reason code and SKUs. 2xx done; a 4xx other than 408/425/429 refused and final; anything else retried until the last attempt, which ends FAILED whatever went wrong. Stamps `confirmed_at`, `confirm_failed_at`, `cancellation_status` (PENDING, REQUESTED, CONFIRMED, FAILED). Idempotent by the row. Queued BEFORE the host's half runs, and the `marketplace.outbound-sweep` job re-queues every call still owed, so nothing is lost. The same sweep fails a request still waiting (never delivered, or delivered and unanswered) as TIMEOUT once past its answer window, and its retries stop (the adapter's `cancellationAnswerWindowMs`, or the engine's `cancellationWindowMs`), so no request waits forever. |
48
+ | **Order fetch** | For a marketplace whose events name an order without carrying it (Open Delivery's `CREATED`), the adapter marks the event `orderToFetch`: the webhook records it PENDING and queues `marketplace.fetch-order`, which calls the adapter's `fetchOrder` and ingests through the same ingest path. No request calls out; the reconciliation sweep re-queues a row still owed, and a host that holds the job holds every fetch. |
47
49
  | **Inbound outcomes** | A marketplace CANCELLED confirms a pending request; CANCELLATION_REQUEST_FAILED marks it FAILED; CONFIRMED is terminal. |
48
- | **Adapter port** | `MarketplaceAdapter`: `normalize`, `readSignature`, `verifySignature`, `cancellationReasons`, `confirm`, `requestCancellation`, `appLink`, and `capabilities`. |
50
+ | **Adapter port** | `MarketplaceAdapter`: `normalize`, `readSignature`, `verifySignature`, `cancellationReasons`, `confirm`, `requestCancellation`, `appLink`, `capabilities`, and the optional `fetchOrder`. |
49
51
 
50
52
  ## Subpaths
51
53
 
@@ -54,6 +56,10 @@ engine code (`src/__tests__/second-adapter.test.ts`).
54
56
  | `@12-apps/marketplace` | the engine, the adapter port and registry, every type |
55
57
  | `@12-apps/marketplace/ifood` | `createIfoodAdapter({ copy })` |
56
58
  | `@12-apps/marketplace/ifood/pt-BR`, `/en-US` | the iFood adapter's copy packs (reason labels, "no street number") |
59
+ | `@12-apps/marketplace/99food` | `createNinetyNineFoodAdapter({ copy, apiBaseUrl, portalUrl })`, provider `NINETY_NINE_FOOD`, on Open Delivery |
60
+ | `@12-apps/marketplace/99food/pt-BR`, `/en-US` | the 99Food adapter's copy packs |
61
+ | `@12-apps/marketplace/rappi` | `createRappiAdapter({ copy, apiBaseUrl, tokenUrl, portalUrl, amountUnit })`, provider `RAPPI` |
62
+ | `@12-apps/marketplace/rappi/pt-BR`, `/en-US` | the Rappi adapter's copy packs |
57
63
  | `@12-apps/marketplace/server` | `createApiMarketplace` (route descriptors), `MARKETPLACE_JOBS`, `MARKETPLACE_MCP_TOOLS` (six: a read and a bulk write per entity), `MARKETPLACE_PERMISSIONS`, the strict Zod inputs |
58
64
  | `@12-apps/marketplace/server/pt-BR`, `/en-US` | the routes' copy packs |
59
65
  | `@12-apps/marketplace/hono` | `marketplaceRouter(config)` — the routes as one Hono router (`hono` is an optional peer) |
@@ -67,3 +73,142 @@ fields and reason codes come from the portal's search snippets (2026-11-11).
67
73
  They live only in `src/ifood/outbound.ts` and `src/ifood/copy.ts`, whose
68
74
  headers say so, so the homologation run corrects two files. Tests never reach
69
75
  iFood: the HTTP client is the host's port.
76
+
77
+ ## 99Food, on Open Delivery
78
+
79
+ 99Food completed Open Delivery (Abrasel) adherence, so its adapter speaks
80
+ [Open Delivery v1.7.1](https://abrasel-nacional.github.io/opendelivery/openapi.yaml)
81
+ and is registered as `NINETY_NINE_FOOD`. Its webhook is the engine's one
82
+ route, `POST /webhooks/marketplace/:tenantSlug/NINETY_NINE_FOOD`.
83
+
84
+ ```ts
85
+ import { createNinetyNineFoodAdapter } from "@12-apps/marketplace/99food";
86
+ import { NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR } from "@12-apps/marketplace/99food/pt-BR";
87
+
88
+ createNinetyNineFoodAdapter({
89
+ copy: NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR,
90
+ apiBaseUrl: { SANDBOX: "https://…", PRODUCTION: "https://…" }, // from 99Food, at partner onboarding
91
+ portalUrl: "https://…", // the merchant portal
92
+ });
93
+ ```
94
+
95
+ | part | from the spec |
96
+ |---|---|
97
+ | Webhook | `X-App-Signature`: lowercase hex HMAC-SHA256 of the body, keyed by the CLIENT SECRET. A connection stores that same value as its `webhookSecret`, and a connection without one REFUSES every delivery (the key exists from the moment the store connects). The merchant is the `X-App-MerchantId` header; the engine attributes by the URL's store slug. |
98
+ | Merchant id | A connection's `externalMerchantId` for 99Food is the Open Delivery **merchant id** — the spec's `Merchant.id`, which the merchant's Software Service (the host) generates and registers with 99Food, and which 99Food echoes as `X-App-MerchantId` and `Order.merchant.id`. It is NOT 99Food's own internal id for the store shown on its portal. A fetched order whose `merchant.id` differs is refused and its inbox row settled FAILED, so correcting the connection's id lets the reconciliation sweep fetch it again within the attempt bound. |
99
+ | Events | `CREATED` → fetch the order (`GET /v1/orders/{orderId}`); `CANCELLED` → cancelled (answers a pending request; one that outruns the fetch leaves a marker, and the fetch then ingests nothing — or, when it lands while the ingest is being written, cancels the order it just wrote); `CANCELLATION_REQUEST_DENIED` → the request FAILED. The rest (`CONFIRMED`, `CANCELLATION_REQUESTED`, `ORDER_CANCELLATION_REQUEST`, `DISPATCHED`…) are recorded and IGNORED. |
100
+ | Auth | `POST /oauth/token`, form-encoded `client_credentials`; the token is cached per process. |
101
+ | Confirm | `POST /v1/orders/{orderId}/confirm` with `OrderConfirmed` (`orderExternalCode` = the host's order id, `createdAt`, `preparationTime` when stated). Every 422 is a refusal: the store sees "não confirmou" and the app link. The spec's 422 cannot tell a duplicate from a cancelled order, so a retried confirm whose first answer was lost shows that same harmless alarm. |
102
+ | Cancel | `POST /v1/orders/{orderId}/requestCancellation` with `{ reason, code, mode }`; the eleven merchant codes are the adapter's static reasons. 202, then an event. A 422 whose `cancellationStatus` is `CANCELLED` is done. |
103
+ | Order | `total.orderAmount` is the gross total. The `Order` states no commission, so `commissionCents` is null. An item's lines always add up to its `totalPrice`: a total that does not divide by the quantity is split into (q−1) units at the floor and one carrying the remainder, same SKU. Options and instructions go into the line's note; a weighed item is one line at its total. The acceptance deadline counts from the event's arrival; the liveness stamp and an auto-accept's time are the ingest's own. |
104
+
105
+ The fixtures are the spec's own examples (`src/99food/__tests__/fixtures.ts`).
106
+ `src/99food/__tests__/engine.test.ts` drives the engine through the adapter
107
+ end to end: event, fetch, ingest, aceite, confirm, cancel, the answer.
108
+
109
+ **ESTIMATED, to be checked live once 99Food grants partner access:**
110
+
111
+ - the base URLs and the portal: not public, so they are required config;
112
+ - `OrderConfirmed.createdAt` is sent as the moment of the confirmation (the
113
+ spec's description of that field is copied from the order's);
114
+ - the cancellation answer window, 5 minutes (the spec names none);
115
+ - a token with no `expires_in` lives an hour (the field is optional);
116
+ - `outOfStockItems` is not sent: the spec wants item uuids there, and the
117
+ engine keeps the marketplace's SKUs (`externalCode`);
118
+ - with no `totalPrice`, a line is `unitPrice × quantity + optionsPrice` (options added once: the spec calls it a line figure);
119
+ - with no `externalCode`, a line keys on the item id, which may be per order (then each such order adds an unmapped SKU row);
120
+ - that 99Food sends every event by webhook (Open Delivery also allows
121
+ polling, which this adapter does not do).
122
+
123
+ ## Rappi, from its public developer portal
124
+
125
+ Built now (owner, 2026-11-11) from what [dev-portal.rappi.com](https://dev-portal.rappi.com)
126
+ shows publicly (managing-user-orders, api-reference/orders, webhook-events,
127
+ authentication-process, read 2026-11-13), to be confirmed against Rappi's
128
+ sandbox once Rappi's account manager opens it. Registered as `RAPPI`; its
129
+ webhooks are the engine's one route, `POST /webhooks/marketplace/:tenantSlug/RAPPI`.
130
+
131
+ ```ts
132
+ import { createRappiAdapter } from "@12-apps/marketplace/rappi";
133
+ import { RAPPI_ADAPTER_COPY_PT_BR } from "@12-apps/marketplace/rappi/pt-BR";
134
+
135
+ createRappiAdapter({
136
+ copy: RAPPI_ADAPTER_COPY_PT_BR,
137
+ apiBaseUrl: { SANDBOX: "https://…", PRODUCTION: "https://…" }, // https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api
138
+ tokenUrl: { SANDBOX: "https://…", PRODUCTION: "https://…" }, // https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations
139
+ portalUrl: "https://…", // the partner portal
140
+ amountUnit: "MINOR_UNITS", // or "MAJOR_UNITS": how Rappi states money here
141
+ });
142
+ ```
143
+
144
+ | part | from the portal |
145
+ |---|---|
146
+ | Webhook | Register `NEW_ORDER` and `ORDER_EVENT_CANCEL` (each its own subscription, both pointing at this one URL). `Rappi-Signature: t=<timestamp>,sign=<signature>`, HMAC-SHA256 of `<t>.<raw body>` keyed by the webhook's secret. A connection stores that secret as its `webhookSecret`, and a connection without one REFUSES every delivery. |
147
+ | Events | Rappi's bodies do not name their event, so the adapter reads the shape. An `order_detail` is `NEW_ORDER` → ingested (with `action: "scheduled"` / `"cancelled"`, the two scheduled notices → IGNORED). `{ event, order_id, store_id }` naming a cancellation (`canceled_with_charge`) → cancelled. `ORDER_OTHER_EVENT` (it carries `event_time`) → IGNORED. PING, menu and store events name no order and are acknowledged 200 and dropped. |
148
+ | Merchant id | A connection's `externalMerchantId` for Rappi is **Rappi's store id**: `store.internal_id` on `NEW_ORDER`, `store_id` on every other event. A `NEW_ORDER` naming another store is settled FAILED (so the reconciliation sweep ingests it once the id is corrected) and the webhook answers 500. |
149
+ | Auth | `POST {tokenUrl}` (the portal's `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`), JSON `{ client_id, client_secret }` → `access_token`, valid one week; sent as `x-authorization: Bearer <token>`; cached per process. |
150
+ | Take (the confirm) | `PUT {apiBaseUrl}/orders/{orderId}/take/{cookingTime}` (the portal's base is `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api`), the store's preparation minutes (`take/` keeps the order's own). 400 "Invalid state transition" and 404 are refusals: "não confirmou" and the app link. |
151
+ | Reject (the cancel) | `PUT …/orders/{orderId}/reject` with `{ reason, cancel_type, items_skus }`: one of the portal's six `cancel_type`s, the three item ones requiring the offending SKUs. Only from SENT. The 200 IS the outcome (`asyncCancellationOutcome: false`): CONFIRMED at once. Every refused answer is a refusal (FAILED, the portal link). |
152
+ | Cancel after take | No public endpoint: `cancelAfterAccept: false`, so the store's cancel of a taken order is FAILED at once and opens the partner portal (`appLink`; Rappi names no per-order link). |
153
+ | Windows | Rappi gives a SENT order 6 minutes to be taken or rejected before its own TIMEOUT, so a reject still waiting 6 minutes after it was asked is failed as TIMEOUT (`cancellationAnswerWindowMs`). Rappi counts from the order's arrival and the engine from the request, so a reject asked late may still be sent after Rappi's TIMEOUT and come back 400 (FAILED, the portal link). A connection's acknowledgement window should be at most 360 s. |
154
+ | Order | `totals.total_order`, "the total amount that the restaurant receives", is the total; Rappi states no commission (`commissionCents` null). A line is an item at `price` plus its subitems, `× quantity`, so its rows add up exactly to it; subitems and comments go into the note; an item with no `sku` keys on Rappi's item id. `delivery` is Rappi's courier, `marketplace` the store's own, `pickup` a take-out. |
155
+
156
+ The fixtures are the portal's own examples (`src/rappi/__tests__/fixtures.ts`).
157
+ `src/rappi/__tests__/engine.test.ts` drives the engine through the adapter end
158
+ to end: webhook, ingest, aceite, take, reject, Rappi's cancel, and R3-N2.
159
+
160
+ **ESTIMATED, to be checked against the Rappi sandbox (api.dev.rappi.com):**
161
+
162
+ - the orders API's base and the token URL per environment, and the portal:
163
+ Rappi names its domains by country, so they are required config (whole
164
+ URLs, path included: the paths name the origin application's own noun);
165
+ - how money is stated: integers with no unit in the portal; `amountUnit` is
166
+ required config (`MINOR_UNITS` cents, `MAJOR_UNITS` whole units);
167
+ - that the `NEW_ORDER` body is ONE `GET orders` element (the portal says "the
168
+ same information" and shows no example);
169
+ - telling `ORDER_EVENT_CANCEL` from `ORDER_OTHER_EVENT`: no `event_time` or
170
+ `additional_information`, and `cancel` in the `event` name; anything else is
171
+ recorded and IGNORED, never a cancellation;
172
+ - the signature digest is lowercase hex (the example is 64 hex characters); no
173
+ timestamp tolerance is applied (the portal states none; a replay is an inbox
174
+ duplicate);
175
+ - the token answer's shape beyond `access_token`: an `expires_in` is read when
176
+ present, else the portal's one week;
177
+ - a subitem's `price × quantity` is per unit of its item;
178
+ - an offending item with no `sku` is sent in `items_skus` under Rappi's item
179
+ id, where the portal wants `items_ids`;
180
+ - no `PING` answer: the route answers `{ received: true }`, not Rappi's
181
+ `{ "status": "OK" }`, so do not subscribe `PING` until the host answers it;
182
+ - that Rappi sends every order by webhook: `GET orders` / `orders/status/sent`
183
+ polling is not done by this adapter;
184
+ - that Rappi serves `…/take/` with an empty cooking-time segment (the guide's
185
+ spelling) when the store states no preparation time;
186
+ - the reject window counted from the request, where Rappi counts from the
187
+ order's arrival (see Windows);
188
+ - that the 500 a merchant mismatch answers is harmless: Rappi redelivers, the
189
+ redelivery is an inbox duplicate answered 200; whether Rappi throttles or
190
+ disables a webhook after repeated 500s is not public.
191
+
192
+ Out of scope: the merchant check applies to the NEW_ORDER body only. An
193
+ `ORDER_EVENT_CANCEL` naming another `store_id` under this connection's secret
194
+ still cancels a matching order id: the signature binds the connection's own
195
+ secret, and judging event merchants in the engine would change iFood's path.
196
+
197
+ ### A late synchronous answer (R3-N2)
198
+
199
+ A synchronous marketplace answers a cancellation in the response. When the
200
+ outbound sweep times a request out while the call is still in flight, the
201
+ store may accept the order before the answer lands. The accept clears the
202
+ request but keeps its `cancellation_requested_at` as a TOMBSTONE, and the job
203
+ matches a status-less row of a STILL ACCEPTED order carrying the same
204
+ instant: a late "rejected" to the call in flight still moves the order to
205
+ REJECTED (CONFIRMED) and tells the host `onCancellationConfirmed`. A late
206
+ refusal matches nothing and leaves the accepted order as it is; and once the
207
+ marketplace's own cancel event has rejected the order (telling the host), the
208
+ tombstone answers nothing more, so the host is told once.
209
+
210
+ What it does NOT cover: a call Rappi APPLIED but answered with a 5xx or not at
211
+ all. Its retry runs after the store's accept, finds no request and sends
212
+ nothing, so the order stays ACCEPTED here while cancelled on Rappi. The take
213
+ the accept queued is then answered 400, so the order shows "não confirmou"
214
+ with the portal link and a person settles it there.
@@ -0,0 +1,19 @@
1
+ /** The 99Food adapter's en-US pack: the same reasons, in English. */
2
+ declare const NINETY_NINE_FOOD_ADAPTER_COPY_EN_US: {
3
+ readonly reasonLabels: {
4
+ readonly SYSTEMIC_ISSUES: "System problems";
5
+ readonly DUPLICATE_APPLICATION: "Duplicate order";
6
+ readonly UNAVAILABLE_ITEM: "Item unavailable";
7
+ readonly RESTAURANT_WITHOUT_DELIVERY_PERSON: "No courier available";
8
+ readonly OUTDATED_MENU: "Menu out of date";
9
+ readonly ORDER_OUTSIDE_THE_DELIVERY_AREA: "Address outside the delivery area";
10
+ readonly BLOCKED_CUSTOMER: "Blocked customer";
11
+ readonly OUTSIDE_DELIVERY_HOURS: "Outside delivery hours";
12
+ readonly INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT: "Internal difficulties";
13
+ readonly RISK_AREA: "Risk area";
14
+ readonly DELIVERY_PROBLEM: "Delivery problem";
15
+ };
16
+ readonly missingStreetNumber: "no number";
17
+ };
18
+
19
+ export { NINETY_NINE_FOOD_ADAPTER_COPY_EN_US };
@@ -0,0 +1,23 @@
1
+ import "../chunk-7QVYU63E.js";
2
+
3
+ // src/99food/en-US.ts
4
+ var NINETY_NINE_FOOD_ADAPTER_COPY_EN_US = {
5
+ reasonLabels: {
6
+ SYSTEMIC_ISSUES: "System problems",
7
+ DUPLICATE_APPLICATION: "Duplicate order",
8
+ UNAVAILABLE_ITEM: "Item unavailable",
9
+ RESTAURANT_WITHOUT_DELIVERY_PERSON: "No courier available",
10
+ OUTDATED_MENU: "Menu out of date",
11
+ ORDER_OUTSIDE_THE_DELIVERY_AREA: "Address outside the delivery area",
12
+ BLOCKED_CUSTOMER: "Blocked customer",
13
+ OUTSIDE_DELIVERY_HOURS: "Outside delivery hours",
14
+ INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT: "Internal difficulties",
15
+ RISK_AREA: "Risk area",
16
+ DELIVERY_PROBLEM: "Delivery problem"
17
+ },
18
+ missingStreetNumber: "no number"
19
+ };
20
+ export {
21
+ NINETY_NINE_FOOD_ADAPTER_COPY_EN_US
22
+ };
23
+ //# sourceMappingURL=en-US.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/99food/en-US.ts"],"sourcesContent":["import type { NinetyNineFoodAdapterCopy } from \"./copy\";\n\n/** The 99Food adapter's en-US pack: the same reasons, in English. */\nexport const NINETY_NINE_FOOD_ADAPTER_COPY_EN_US = {\n reasonLabels: {\n SYSTEMIC_ISSUES: \"System problems\",\n DUPLICATE_APPLICATION: \"Duplicate order\",\n UNAVAILABLE_ITEM: \"Item unavailable\",\n RESTAURANT_WITHOUT_DELIVERY_PERSON: \"No courier available\",\n OUTDATED_MENU: \"Menu out of date\",\n ORDER_OUTSIDE_THE_DELIVERY_AREA: \"Address outside the delivery area\",\n BLOCKED_CUSTOMER: \"Blocked customer\",\n OUTSIDE_DELIVERY_HOURS: \"Outside delivery hours\",\n INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT: \"Internal difficulties\",\n RISK_AREA: \"Risk area\",\n DELIVERY_PROBLEM: \"Delivery problem\",\n },\n missingStreetNumber: \"no number\",\n} as const satisfies NinetyNineFoodAdapterCopy;\n"],"mappings":";;;AAGO,IAAM,sCAAsC;AAAA,EACjD,cAAc;AAAA,IACZ,iBAAiB;AAAA,IACjB,uBAAuB;AAAA,IACvB,kBAAkB;AAAA,IAClB,oCAAoC;AAAA,IACpC,eAAe;AAAA,IACf,iCAAiC;AAAA,IACjC,kBAAkB;AAAA,IAClB,wBAAwB;AAAA,IACxB,yCAAyC;AAAA,IACzC,WAAW;AAAA,IACX,kBAAkB;AAAA,EACpB;AAAA,EACA,qBAAqB;AACvB;","names":[]}
@@ -0,0 +1,116 @@
1
+ import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAdapter } from '../adapter-_iuSxvVD.js';
2
+
3
+ /**
4
+ * The words the 99Food adapter needs from its host, and nothing else.
5
+ *
6
+ * Required and defaultless, like every copy port in this repo: the adapter
7
+ * ships no language of its own. Two packs sit beside it (`./pt-BR`,
8
+ * `./en-US`); a host passes one by hand, or its own.
9
+ */
10
+ /**
11
+ * The cancellation codes a merchant may send, verbatim from Open Delivery
12
+ * v1.7.1 (`RequestCancelled.code`). Pinned by the spec, not estimated. The two
13
+ * codes only the marketplace sends (`CONSUMER_CANCELLATION_REQUESTED`,
14
+ * `OTHER_CANCELLATION_REASON`) are not a store's to choose and are left out.
15
+ */
16
+ declare const NINETY_NINE_FOOD_REASON_CODES: readonly ["SYSTEMIC_ISSUES", "DUPLICATE_APPLICATION", "UNAVAILABLE_ITEM", "RESTAURANT_WITHOUT_DELIVERY_PERSON", "OUTDATED_MENU", "ORDER_OUTSIDE_THE_DELIVERY_AREA", "BLOCKED_CUSTOMER", "OUTSIDE_DELIVERY_HOURS", "INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT", "RISK_AREA", "DELIVERY_PROBLEM"];
17
+ type NinetyNineFoodReasonCode = (typeof NINETY_NINE_FOOD_REASON_CODES)[number];
18
+ interface NinetyNineFoodAdapterCopy {
19
+ /** One label per reason code. Sent as the request's `reason` text when the store wrote none. */
20
+ reasonLabels: Readonly<Record<NinetyNineFoodReasonCode, string>>;
21
+ /** What an address with no street number says instead. */
22
+ missingStreetNumber: string;
23
+ }
24
+
25
+ /**
26
+ * The 99Food adapter's OUTBOUND half, on Open Delivery v1.7.1: the OAuth
27
+ * grant, the order fetch, confirm and requestCancellation. Paths, verbs,
28
+ * bodies and answers are the spec's; the job that calls these, its retries
29
+ * and what a failure shows are the engine's.
30
+ *
31
+ * The one thing the spec cannot pin is WHERE: Open Delivery standardizes the
32
+ * paths under each Ordering Application's own base URL, and 99Food gives its
33
+ * base URLs to a partner at onboarding. So the base URL per environment is
34
+ * the adapter's REQUIRED config, never a guessed default. Tests never reach
35
+ * 99Food: the HTTP client is the host's port, answered by a fake.
36
+ */
37
+ /** Where 99Food serves Open Delivery, per environment (given at partner onboarding). */
38
+ type NinetyNineFoodApiBaseUrls = Readonly<Record<"SANDBOX" | "PRODUCTION", string>>;
39
+
40
+ /**
41
+ * The 99Food adapter's INBOUND half, on Open Delivery v1.7.1 (Abrasel).
42
+ *
43
+ * Open Delivery splits what iFood sends at once: the webhook's `Event` names
44
+ * an order (`eventId`, `eventType`, `orderId`, `orderURL`, `createdAt`) and
45
+ * carries no body, and `GET /v1/orders/{orderId}` answers the `Order`. So
46
+ * there are two readers here: {@link normalizeOpenDeliveryEvent} for the
47
+ * webhook (a `CREATED` becomes `orderToFetch`), and
48
+ * {@link normalizeOpenDeliveryOrder} for what the engine's fetch job reads.
49
+ *
50
+ * Every shape below is the spec's (`components/schemas/Event`, `Order`,
51
+ * `Price`, `Address`), and every fixture in the tests is the spec's own
52
+ * example. Read defensively all the same: a missing field produces null, and
53
+ * only a missing order id refuses an event (it is the idempotency key).
54
+ */
55
+ /** The provider id 99Food is registered under. Uppercase: the column's CHECK holds that shape. */
56
+ declare const NINETY_NINE_FOOD_PROVIDER = "NINETY_NINE_FOOD";
57
+ /**
58
+ * Verify a delivery: Open Delivery's `X-App-Signature` is "a lowercased
59
+ * hexadecimal HMAC signature of the webhook HTTP request body, using the
60
+ * client secret as a key and SHA256 as the hash function". The key is the
61
+ * merchant app's CLIENT SECRET, so a store's connection keeps that same value
62
+ * as its webhook secret.
63
+ *
64
+ * Unlike iFood (whose secret is issued after certification), the key exists
65
+ * from the moment the store connects, so an unset secret REFUSES: an unsigned
66
+ * CANCELLED for a known order id would otherwise cancel it.
67
+ */
68
+ declare function verifyOpenDeliverySignature(rawBody: string, signature: string | null, webhookSecret: string | null): boolean;
69
+ /**
70
+ * Normalize one webhook `Event`. Null only when it names no order.
71
+ *
72
+ * - `CREATED` announces an order: `orderToFetch`, the body is the fetch job's.
73
+ * - `CANCELLED` is a cancellation, whether the store asked for it or not.
74
+ * - `CANCELLATION_REQUEST_DENIED` refuses the store's request.
75
+ * - Everything else (`CONFIRMED`, `CANCELLATION_REQUESTED`, `DISPATCHED`, the
76
+ * consumer's `ORDER_CANCELLATION_REQUEST` handshake…) is understood and
77
+ * recorded, and acts on nothing: an IGNORED inbox row.
78
+ *
79
+ * The merchant is named by the `X-App-MerchantId` HEADER, not the body; the
80
+ * engine attributes a delivery by its URL's store slug, so it reads none.
81
+ */
82
+ declare function normalizeOpenDeliveryEvent(payload: unknown): NormalizedEvent | null;
83
+ /**
84
+ * Normalize one `Order` (the answer of `GET /v1/orders/{orderId}`). Null when
85
+ * it carries no id or no line.
86
+ *
87
+ * The total is `total.orderAmount`, "the final value of the order (itemsPrice
88
+ * + otherFees - discounts)": the buyer's receipt, gross. Open Delivery's
89
+ * `Order` states NO commission field, so `commissionCents` is null ("did not
90
+ * say"), never 0; the marketplace's cut arrives with its statement.
91
+ */
92
+ declare function normalizeOpenDeliveryOrder(order: unknown, options: {
93
+ missingStreetNumber: string;
94
+ }): NormalizedMarketplaceOrder | null;
95
+
96
+ /** How long 99Food may take to answer a cancellation request. ESTIMATED: the spec names no deadline. */
97
+ declare const NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS: number;
98
+ interface NinetyNineFoodAdapterConfig {
99
+ /** The words the adapter needs: reason labels and the missing-number text. Required. */
100
+ copy: NinetyNineFoodAdapterCopy;
101
+ /**
102
+ * Where 99Food serves Open Delivery, per environment: the base the spec's
103
+ * paths (`/oauth/token`, `/v1/orders/…`) hang from. Given to a partner at
104
+ * onboarding and not public, so required and defaultless. https only.
105
+ */
106
+ apiBaseUrl: NinetyNineFoodApiBaseUrls;
107
+ /**
108
+ * Where "open it on 99Food" goes: the merchant portal. Open Delivery names no
109
+ * per-order deep link, so the link is the portal. Required; https only.
110
+ */
111
+ portalUrl: string;
112
+ }
113
+ /** Build the 99Food adapter. Its reasons are static: a dialog never waits on 99Food. */
114
+ declare function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig): MarketplaceAdapter;
115
+
116
+ export { NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS, NINETY_NINE_FOOD_PROVIDER, NINETY_NINE_FOOD_REASON_CODES, type NinetyNineFoodAdapterConfig, type NinetyNineFoodAdapterCopy, type NinetyNineFoodApiBaseUrls, type NinetyNineFoodReasonCode, createNinetyNineFoodAdapter, normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, verifyOpenDeliverySignature };