@12-apps/marketplace 0.0.0-stage → 1.0.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 (85) hide show
  1. package/ADOPTING.md +169 -0
  2. package/README.md +68 -2
  3. package/dist/adapter-CgCAYBSJ.d.ts +279 -0
  4. package/dist/chunk-6OODIO3E.js +395 -0
  5. package/dist/chunk-6OODIO3E.js.map +1 -0
  6. package/dist/chunk-7QVYU63E.js +7 -0
  7. package/dist/chunk-7QVYU63E.js.map +1 -0
  8. package/dist/chunk-BEMTRJYM.js +388 -0
  9. package/dist/chunk-BEMTRJYM.js.map +1 -0
  10. package/dist/chunk-OEKTWUQH.js +28 -0
  11. package/dist/chunk-OEKTWUQH.js.map +1 -0
  12. package/dist/chunk-UYFYGGCS.js +250 -0
  13. package/dist/chunk-UYFYGGCS.js.map +1 -0
  14. package/dist/engine-DDE0mnTu.d.ts +806 -0
  15. package/dist/hono/index.d.ts +38 -0
  16. package/dist/hono/index.js +64 -0
  17. package/dist/hono/index.js.map +1 -0
  18. package/dist/ifood/en-US.d.ts +20 -0
  19. package/dist/ifood/en-US.js +24 -0
  20. package/dist/ifood/en-US.js.map +1 -0
  21. package/dist/ifood/index.d.ts +73 -0
  22. package/dist/ifood/index.js +305 -0
  23. package/dist/ifood/index.js.map +1 -0
  24. package/dist/ifood/pt-BR.d.ts +25 -0
  25. package/dist/ifood/pt-BR.js +24 -0
  26. package/dist/ifood/pt-BR.js.map +1 -0
  27. package/dist/index.d.ts +45 -0
  28. package/dist/index.js +971 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/manifest/index.d.ts +339 -0
  31. package/dist/manifest/index.js +20 -0
  32. package/dist/manifest/index.js.map +1 -0
  33. package/dist/manifest/server.d.ts +23 -0
  34. package/dist/manifest/server.js +18 -0
  35. package/dist/manifest/server.js.map +1 -0
  36. package/dist/server/en-US.d.ts +22 -0
  37. package/dist/server/en-US.js +26 -0
  38. package/dist/server/en-US.js.map +1 -0
  39. package/dist/server/index.d.ts +529 -0
  40. package/dist/server/index.js +41 -0
  41. package/dist/server/index.js.map +1 -0
  42. package/dist/server/pt-BR.d.ts +22 -0
  43. package/dist/server/pt-BR.js +26 -0
  44. package/dist/server/pt-BR.js.map +1 -0
  45. package/package.json +118 -4
  46. package/prisma/marketplace.prisma +241 -0
  47. package/prisma/migrations/20261111200000_marketplace_engine/migration.sql +272 -0
  48. package/src/core/acceptance.ts +197 -0
  49. package/src/core/adapter.ts +184 -0
  50. package/src/core/bulk.ts +203 -0
  51. package/src/core/cancellation.ts +175 -0
  52. package/src/core/decisions.ts +304 -0
  53. package/src/core/engine.ts +229 -0
  54. package/src/core/inbox.ts +172 -0
  55. package/src/core/ingest.ts +168 -0
  56. package/src/core/integration.ts +300 -0
  57. package/src/core/menu-links.ts +166 -0
  58. package/src/core/outbound-queue.ts +63 -0
  59. package/src/core/outbound-sweep.ts +90 -0
  60. package/src/core/outbound.ts +283 -0
  61. package/src/core/pipeline.ts +193 -0
  62. package/src/core/ports.ts +260 -0
  63. package/src/core/registry.ts +107 -0
  64. package/src/core/state.ts +76 -0
  65. package/src/core/types.ts +131 -0
  66. package/src/hono/index.ts +95 -0
  67. package/src/ifood/copy.ts +36 -0
  68. package/src/ifood/en-US.ts +20 -0
  69. package/src/ifood/index.ts +65 -0
  70. package/src/ifood/normalize.ts +281 -0
  71. package/src/ifood/outbound.ts +112 -0
  72. package/src/ifood/pt-BR.ts +25 -0
  73. package/src/index.ts +122 -0
  74. package/src/manifest/index.ts +42 -0
  75. package/src/manifest/server.ts +20 -0
  76. package/src/server/contribution.ts +34 -0
  77. package/src/server/copy.ts +25 -0
  78. package/src/server/en-US.ts +22 -0
  79. package/src/server/http.ts +66 -0
  80. package/src/server/index.ts +55 -0
  81. package/src/server/jobs.ts +131 -0
  82. package/src/server/mcp.ts +306 -0
  83. package/src/server/pt-BR.ts +22 -0
  84. package/src/server/routes.ts +215 -0
  85. package/src/server/webhook.ts +118 -0
package/ADOPTING.md ADDED
@@ -0,0 +1,169 @@
1
+ # Adopting @12-apps/marketplace
2
+
3
+ The engine is a library with required ports and no defaults: a host answers
4
+ every question only it can answer, and the engine supplies the mechanism.
5
+ Everything below is what a host binds, in the order it binds it.
6
+
7
+ ## 1. The host ports (`MarketplacePorts`)
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.
11
+
12
+ | port | type | what the host answers |
13
+ |---|---|---|
14
+ | `db` | `() => Promise<MarketplaceDb>` | The Prisma client generated from a schema that includes `prisma/marketplace.prisma`. Structural: the four delegates `marketplaceIntegration`, `marketplaceMenuLink`, `marketplaceInboxEvent`, `marketplaceAcceptance`. |
15
+ | `transaction` | `<T>(fn: (db: MarketplaceDb) => Promise<T>) => Promise<T>` | Prisma's interactive `$transaction`: run `fn` with the transaction's client; a throw rolls back. Every bulk write and every decision (admission + claim) is one transaction. |
16
+ | `order.admit` | `(request: { clientId; orderId; decision: "ACCEPT" \| "REJECT"; admission: MarketplaceAdmission; db: MarketplaceDb }) => Promise<{ admitted: true } \| { admitted: false; code: string; message: string; details?: unknown }>` | Judge each decision BEFORE its claim commits, inside the claim's transaction (`request.db` is the transaction's client: draw the stock there, and a refusal anywhere in the call rolls the draw back). `admission` is `{ admitStockPastZero?: boolean }` as the person stated it. Refuse with your own code: the route answers 409 with it (`MARKETPLACE_STOCK_ASK` and the short lines in `details`). Never called for an ingest or `recordStoreCancellation`. |
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
+ | `order.catalogHas` | `(clientId, subjectRef) => Promise<boolean>` | Does this catalog id exist and belong to this tenant? Asked before a SKU is mapped. |
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). |
21
+ | `order.summarize` | `(clientId, orderIds: readonly string[]) => Promise<Map<string, MarketplaceOrderSummary>>` | The queue's host facts in one read: `{ buyerName, totalCents, unmappedLines, createdAt }`. |
22
+ | `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
+ | `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. |
24
+ | `audit` | `{ record(entry: { clientId; actorId: string \| null; action: "marketplace.integration.archive" \| "marketplace.integration.unarchive"; provider; reason: string \| null; at: Date }, db: MarketplaceDb): Promise<void> }` | Every archive and unarchive of a connection, INSIDE the same transaction: write the line through `db`, so an archive never lands without its line and a failing audit rolls the archive back. `actorId` is `MarketplaceActor.userId`. |
25
+ | `enqueue` | `{ enqueue(name, payload, { dedupeKey? }) => Promise<{ enqueued: boolean; reason?: string }> }` | The wiring `JobsEnqueuePort`. The engine queues only `marketplace.outbound` with `{ clientId, orderId, action }` and dedupe key `marketplace.outbound:<action>:<orderId>`. Never throws. |
26
+ | `clock` | `{ now(): Date }` | What time it is. |
27
+ | `logger` | `{ info, warn, error }` | The wiring `LoggerPort`; bind `assembled.loggers["@12-apps/marketplace"]`. |
28
+ | `publishChanged` | `(clientId) => void` | Tell the staff surfaces something moved. Fire-and-forget. |
29
+ | `defaultAckSlaSeconds` | `number` | The acceptance window a new connection gets (the origin host: 300). |
30
+ | `reconcileBatchSize` | `number` | Stored deliveries one reconciliation pass re-runs (origin: 50). |
31
+ | `maxInboxAttempts` | `number` | Re-runs before a stored delivery is retired (origin: 5). |
32
+
33
+ Plus `adapters: readonly MarketplaceAdapter[]` — one per marketplace the host
34
+ sells through. The list is validated at mount (ids, duplicates, reason lists).
35
+
36
+ ```ts
37
+ import { createMarketplaceEngine } from "@12-apps/marketplace";
38
+ import { createIfoodAdapter } from "@12-apps/marketplace/ifood";
39
+ import { IFOOD_ADAPTER_COPY_PT_BR } from "@12-apps/marketplace/ifood/pt-BR";
40
+
41
+ export const engine = createMarketplaceEngine({
42
+ db: async () => getPrismaClient(),
43
+ transaction: async (fn) => (await getPrismaClient()).$transaction((tx) => fn(tx)),
44
+ order: { admit, create, catalogHas, onAccepted, onRefused, summarize },
45
+ audit: { record: writeAuditLine },
46
+ secrets: { seal: encryptSecret, open: decryptSecret },
47
+ http: marketplaceHttp,
48
+ enqueue: jobs,
49
+ clock: { now: () => new Date() },
50
+ logger: assembled.loggers["@12-apps/marketplace"],
51
+ publishChanged,
52
+ defaultAckSlaSeconds: 300,
53
+ reconcileBatchSize: 50,
54
+ maxInboxAttempts: 5,
55
+ adapters: [createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR })],
56
+ });
57
+ ```
58
+
59
+ ## 2. What the host calls on the engine
60
+
61
+ | call | when |
62
+ |---|---|
63
+ | `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. |
65
+ | `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. |
67
+ | `adapter(provider)`, `reasons(provider)`, `appLink(provider, ref)` | The marketplace's capabilities, reasons and link, without naming it. |
68
+ | `ingest(...)`, `deliver(...)` | A producer that hands over an order directly; the webhook does `deliver` for you. |
69
+
70
+ A host never writes `provider === "IFOOD"`. A capability is asked of
71
+ `engine.adapter(provider).capabilities`.
72
+
73
+ ## 3. The wiring capabilities
74
+
75
+ Adopt through `@12-apps/wiring/consumer`:
76
+
77
+ ```ts
78
+ host.adoptServer({
79
+ manifest: marketplaceManifest, // @12-apps/marketplace/manifest
80
+ server: marketplaceServerManifest, // @12-apps/marketplace/manifest/server
81
+ bindings: {
82
+ http: { mountPath: "/api", config: { engine, copy: MARKETPLACE_SERVER_COPY_PT_BR, tenantBySlug, logger } },
83
+ jobs: { deps: { engine } },
84
+ },
85
+ });
86
+ ```
87
+
88
+ | capability | what it is |
89
+ |---|---|
90
+ | `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 }`. |
92
+ | `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
+ | `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
+ | `db` | `prisma/marketplace.prisma` + `prisma/migrations` (composed). |
95
+ | `observability` | namespace `marketplace`. |
96
+
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
+
101
+ ## 4. What the origin host changes when it adopts this package
102
+
103
+ 1. **Bind the new ports:** `transaction` (`prisma.$transaction`), `order.admit` (move the
104
+ stock ask and the draw of an accept here, from the Quadro's own path, so the board, the
105
+ admin route and the MCP share it), `audit`, `http` (`marketplaceHttp`), `enqueue`,
106
+ `clock`, `logger`. Move any atomic work out of `onAccepted`.
107
+ 2. **`normalizeIfoodEvent(payload, options)`** now takes `{ missingStreetNumber }` (the pack's
108
+ `IFOOD_ADAPTER_COPY_PT_BR.missingStreetNumber` is "s/n"); the host's tests that call it with
109
+ one argument change. Better: call `engine.normalize("IFOOD", payload)`.
110
+ 3. **The webhook's refusals are JSON:** `401 {error:"unauthorized"}`, `404
111
+ {error:"unknown_provider"}`, `400 {error:"invalid_json"}`; an unreadable payload answers
112
+ `{received:true, ignored:"unrecognized_payload"}` (was "unrecognized payload").
113
+ 4. **`GET …/menu-links?unmapped=`** is true only for `"true"` (the host's `z.coerce.boolean`
114
+ read `"false"` as true).
115
+ 5. **The tools and routes are bulk:** `saveMarketplaceIntegration`, `deleteMarketplaceIntegration`,
116
+ `setMarketplaceMenuLink` and `decideMarketplaceOrder` (and `POST …/acceptances/:orderId`)
117
+ become `upsertMarketplaceIntegrations` (delete is now `operation: "archive"`),
118
+ `upsertMarketplaceMenuLinks` and `decideMarketplaceOrders` (`POST …/acceptances` with a
119
+ `decisions` list). Update the admin SPA's calls, the MCP tool groups and the policy table.
120
+ 6. **The guards move to permissions:** connections and SKU links take `marketplace:manage`
121
+ (was `requireTenantAdminBySlug` / `products:*`), the queue and the decision
122
+ `marketplace:decide` (was `orders:read:all` / `requireTenantAdminBySlug`). Grant BOTH to the
123
+ roles that hold store administration today (OWNER, ADMIN) to keep today's access, and
124
+ `marketplace:decide` to whoever reads the queue today.
125
+ 7. **`decide` returns a union** (`decided`, `stale` with a reason, `invalidReason`,
126
+ `refusedByHost`), not `AcceptanceOutcome | null`; `recordStoreCancellation` replaces calling
127
+ `onRefused` after the PATCH cancel.
128
+ 8. **The provider is a string** checked by `engine.knows(provider)`;
129
+ `MARKETPLACE_PROVIDERS`/`isMarketplaceProvider` are gone.
130
+ 9. **Drop the origin host's unmerged `20261111190000_marketplace_outbound`** migration: this
131
+ package's `20261111200000_marketplace_engine` adds the same columns (and more), and
132
+ deployed in the other order the plain `ADD COLUMN` of 190000 would fail.
133
+ 10. **Stop syncing the predecessor's own migration copies over this package's**: keep the
134
+ host's applied `20260814140000`/`20261105120000` files as they are.
135
+ 11. **Orders accepted before adoption are stamped confirmed, never re-sent.** The migration's
136
+ first run over the predecessor's table sets `confirmed_at = acknowledged_at` on every row
137
+ already `ACCEPTED`, because nothing confirmed through an API before this engine; the outbound
138
+ sweep then owes none of them. Fresh databases and replays stamp nothing.
139
+ 12. **`order.create` and `audit.record` receive a transaction client** (last argument): write
140
+ the host's order and the audit line through it, so they commit with the engine's own rows.
141
+ Everything `create` writes goes through that client, the buyer record and the order
142
+ number included, never the host's global client inside the callback: on PGlite, which
143
+ runs one transaction at a time, a write on the global client hangs the ingest, and on
144
+ Postgres a rolled-back ingest would leave an orphan order and a burnt order number.
145
+
146
+ ## 5. The database
147
+
148
+ The partial names no host table: `client_id`, `order_id` and `menu_item_id`
149
+ are by-value scalars. A host that wants referential integrity adds, in its own
150
+ migration:
151
+
152
+ - `marketplace_*.client_id → <tenants>(id) ON DELETE CASCADE`
153
+ - `marketplace_acceptances.order_id → <orders>(id) ON DELETE CASCADE`
154
+ - `marketplace_menu_links.menu_item_id → <catalog>(id) ON DELETE SET NULL`
155
+
156
+ The migration `20261111200000_marketplace_engine` is replay-safe. On a host
157
+ that already has the predecessor's tables it adds the outbound columns
158
+ (including `cancellation_offending_skus`, `cancellation_requested_at`,
159
+ `preparation_minutes`), the order's `line_skus`, `delivered_by` and the
160
+ connection's `archived_at`, keeps the host's foreign keys, and replaces the
161
+ closed provider lists (`*_provider_valid`) with a shape check, so a new
162
+ adapter is never a migration.
163
+
164
+ ## 6. What stays the host's
165
+
166
+ The stock draw at the acceptance, the settlement effects, the board's and the
167
+ order screen's UI, the cancel route itself, the HTTP client's timeout and CA,
168
+ the jobs runtime and its leases, which roles hold the two permissions, and
169
+ every sentence a person reads.
package/README.md CHANGED
@@ -1,3 +1,69 @@
1
- # Temporary Holding Version
1
+ # @12-apps/marketplace
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ One integration engine for every marketplace a store sells through. Each
4
+ marketplace is an **adapter** on that engine, shipped inside this package at
5
+ its own subpath (`@12-apps/marketplace/ifood` today).
6
+
7
+ ```ts
8
+ import { createMarketplaceEngine } from "@12-apps/marketplace";
9
+ import { createIfoodAdapter } from "@12-apps/marketplace/ifood";
10
+ import { IFOOD_ADAPTER_COPY_PT_BR } from "@12-apps/marketplace/ifood/pt-BR";
11
+
12
+ const engine = createMarketplaceEngine({
13
+ ...hostPorts, // db, order, secrets, http, enqueue, clock, logger, publishChanged, the three numbers
14
+ adapters: [createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR })],
15
+ });
16
+ ```
17
+
18
+ Adoption contract, every host port and the wiring: **[ADOPTING.md](./ADOPTING.md)**.
19
+ Why it is shaped this way: the decision record
20
+ [`docs/marketplace/decisions/0001-one-engine-an-adapter-per-marketplace.md`](../../docs/marketplace/decisions/0001-one-engine-an-adapter-per-marketplace.md).
21
+
22
+ ## The owner's two rules
23
+
24
+ 1. "The integration engine must be the same for all integrations: iFood, Rappi,
25
+ 99. Only an adapter is made for each one, to connect to the base engine."
26
+ 2. "This base engine must be a separate lib that implements the wiring package."
27
+
28
+ Engine and adapters share one version. No provider-specific branch exists
29
+ anywhere outside an adapter and its registration: the engine dispatches every
30
+ provider decision through the adapter registry, and a suite registers a fake
31
+ second marketplace and drives ingest, confirm and cancel without touching
32
+ engine code (`src/__tests__/second-adapter.test.ts`).
33
+
34
+ ## What the engine holds
35
+
36
+ | part | what it does |
37
+ |---|---|
38
+ | **Canonical types** | `NormalizedEvent`, `NormalizedMarketplaceOrder`: what every adapter normalizes into. Poorer than any marketplace's payload on purpose; the raw payload stays in the inbox row. |
39
+ | **Inbox** | Every delivery recorded before it is processed, deduped on `(provider, eventId)`. A redelivery is a DB-level no-op; a crash mid-ingest leaves a PENDING row the sweep retries. |
40
+ | **Pipeline** | normalize → inbox → ingest / cancel / cancellation-refused / ignore. Never throws. |
41
+ | **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
+ | **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
+ | **SKU map** | External SKU → host catalog id, every SKU ever seen a row; mapping checks the id is the tenant's. |
45
+ | **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
+ | **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`. |
49
+
50
+ ## Subpaths
51
+
52
+ | export | what |
53
+ |---|---|
54
+ | `@12-apps/marketplace` | the engine, the adapter port and registry, every type |
55
+ | `@12-apps/marketplace/ifood` | `createIfoodAdapter({ copy })` |
56
+ | `@12-apps/marketplace/ifood/pt-BR`, `/en-US` | the iFood adapter's copy packs (reason labels, "no street number") |
57
+ | `@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
+ | `@12-apps/marketplace/server/pt-BR`, `/en-US` | the routes' copy packs |
59
+ | `@12-apps/marketplace/hono` | `marketplaceRouter(config)` — the routes as one Hono router (`hono` is an optional peer) |
60
+ | `@12-apps/marketplace/manifest`, `/manifest/server` | the wiring manifests |
61
+ | `prisma/marketplace.prisma`, `prisma/migrations/*` | the partial (no host table named) and its replay-safe migration |
62
+
63
+ ## iFood is unverified
64
+
65
+ iFood's developer portal refused our reader, so the iFood adapter's URLs, body
66
+ fields and reason codes come from the portal's search snippets (2026-11-11).
67
+ They live only in `src/ifood/outbound.ts` and `src/ifood/copy.ts`, whose
68
+ headers say so, so the homologation run corrects two files. Tests never reach
69
+ iFood: the HTTP client is the host's port.
@@ -0,0 +1,279 @@
1
+ /**
2
+ * The canonical shape every marketplace adapter normalizes INTO.
3
+ *
4
+ * This type is the seam. The engine below it knows no marketplace by name: a
5
+ * marketplace is an adapter registered with the engine (`./adapter`), and the
6
+ * provider id is whatever that adapter says it is. A second marketplace is a
7
+ * second adapter, never a second pipeline, a second acceptance clock or a
8
+ * second idea of what an order is.
9
+ *
10
+ * Deliberately POORER than any marketplace's own payload. Everything a store
11
+ * operates on is here; everything else stays in the inbox row's raw `payload`,
12
+ * which is where a normalization bug is reconstructed from.
13
+ */
14
+ /**
15
+ * A marketplace's id, as its adapter declares it (`"IFOOD"`). Uppercase
16
+ * letters, digits and underscores; the migration's CHECK holds the same shape.
17
+ * A string rather than a closed union, because the set of marketplaces is the
18
+ * set of registered adapters, and a union would make a new one a code change
19
+ * in the engine.
20
+ */
21
+ type MarketplaceProvider = string;
22
+ /** The shape a provider id must have. Shared by the registry and the CHECK. */
23
+ declare const PROVIDER_ID_PATTERN: RegExp;
24
+ /** One line of an incoming order, before it is resolved against the catalog. */
25
+ interface NormalizedOrderLine {
26
+ /** The marketplace's own SKU — the key the SKU map is matched on. */
27
+ externalSku: string;
28
+ /** What the marketplace called it. Snapshotted, and the fallback line text. */
29
+ name: string;
30
+ quantity: number;
31
+ /**
32
+ * Unit price in the smallest currency unit AS THE MARKETPLACE STATES IT. A
33
+ * marketplace's menu carries its own prices, and the buyer's receipt is the
34
+ * marketplace's one: re-pricing from the host's catalog would produce a
35
+ * total nobody was charged.
36
+ */
37
+ unitPriceCents: number;
38
+ /** The buyer's note on this line, when they left one. */
39
+ note: string | null;
40
+ }
41
+ /** The buyer, as much of them as the marketplace discloses. */
42
+ interface NormalizedBuyer {
43
+ /** The marketplace's own stable id for this customer, when it gives one. */
44
+ externalId: string | null;
45
+ name: string | null;
46
+ phone: string | null;
47
+ }
48
+ /** Where a delivery goes, as much of it as the marketplace states. */
49
+ interface NormalizedAddress {
50
+ street: string;
51
+ number: string;
52
+ neighborhood: string;
53
+ complement: string | null;
54
+ /** The sentence that finds the door. */
55
+ reference: string | null;
56
+ postalCode: string | null;
57
+ city: string | null;
58
+ state: string | null;
59
+ }
60
+ /** How the order reaches the buyer: brought to the door, or collected. */
61
+ type MarketplaceOrderType = "DELIVERY" | "TAKEOUT";
62
+ /** WHO carries a delivery: the merchant's own courier, or the marketplace's fleet. */
63
+ type MarketplaceDeliveredBy = "MERCHANT" | "MARKETPLACE";
64
+ /** An incoming marketplace order, normalized. */
65
+ interface NormalizedMarketplaceOrder {
66
+ provider: MarketplaceProvider;
67
+ /** The marketplace's order id — THE idempotency key for the whole pipeline. */
68
+ externalOrderId: string;
69
+ /** The short code the courier and the buyer say out loud. */
70
+ externalDisplayId: string | null;
71
+ buyer: NormalizedBuyer;
72
+ lines: NormalizedOrderLine[];
73
+ /**
74
+ * What the buyer paid, gross. NOT derived from the lines when the
75
+ * marketplace states it: its total carries fees, promotions and rounding the
76
+ * line sum does not, and the number that must match the receipt is this one.
77
+ */
78
+ totalCents: number;
79
+ /** The marketplace's cut, when it states one. NULL is "did not say", not 0. */
80
+ commissionCents: number | null;
81
+ /** The marketplace's own promise to the buyer. */
82
+ deliveryDueAt: Date | null;
83
+ /** When the marketplace says the order was placed. */
84
+ placedAt: Date;
85
+ /** Null when the payload does not say. */
86
+ orderType?: MarketplaceOrderType | null;
87
+ /** Null on a take-out and when unstated. */
88
+ deliveredBy?: MarketplaceDeliveredBy | null;
89
+ /** Null on a take-out and when unstated. */
90
+ deliveryAddress?: NormalizedAddress | null;
91
+ }
92
+ /**
93
+ * What an event says about the STORE's own cancellation request: `CONFIRMED`
94
+ * when the marketplace cancelled the order (a pending request is answered),
95
+ * `FAILED` when it refused the request.
96
+ */
97
+ type CancellationOutcome = "CONFIRMED" | "FAILED";
98
+ /** What an adapter makes of one inbound delivery. */
99
+ interface NormalizedEvent {
100
+ provider: MarketplaceProvider;
101
+ /** The delivery's own id — the inbox dedup key, paired with the provider. */
102
+ eventId: string;
103
+ /** The provider's event type verbatim, kept for the inbox row and the log. */
104
+ eventType: string;
105
+ /** The merchant this event names, used to attribute it to a tenant. */
106
+ externalMerchantId: string | null;
107
+ externalOrderId: string | null;
108
+ /**
109
+ * The order this event carries, or null when the event is one the engine
110
+ * understands and does not ingest. A null here is an IGNORED inbox row (or a
111
+ * cancellation, below), never a failure.
112
+ */
113
+ order: NormalizedMarketplaceOrder | null;
114
+ /** The marketplace has CANCELLED the order. */
115
+ cancelled: boolean;
116
+ /**
117
+ * The answer to the store's own cancellation request, when this event is
118
+ * one. A `cancelled: true` event reads as `CONFIRMED` when this is absent.
119
+ */
120
+ cancellationOutcome?: CancellationOutcome | null;
121
+ }
122
+
123
+ /**
124
+ * The adapter port: everything one marketplace is, behind one shape.
125
+ *
126
+ * The owner's rule, which this file exists to make true: "the integration
127
+ * engine must be the same for all integrations: iFood, Rappi, 99. Only an
128
+ * adapter is made for each one, to connect to the base engine."
129
+ *
130
+ * A marketplace differs from the next in five ways that matter to a store:
131
+ * how its deliveries look and are signed (`normalize`, `readSignature`,
132
+ * `verifySignature`), what it lets a store answer through its API (`confirm`,
133
+ * `requestCancellation`), which reasons a refusal may carry
134
+ * (`cancellationReasons`), and where a person goes when the API cannot do it
135
+ * (`appLink`). Everything else — the inbox, the clock, the SKU map, the
136
+ * outbound bookkeeping and its retries — is the engine's and does not change
137
+ * with the marketplace.
138
+ *
139
+ * What a marketplace CAN do is stated by its adapter as
140
+ * {@link MarketplaceCapabilities} and read by the engine and the host. It is
141
+ * never inferred from the provider's id: a branch on the id outside an adapter
142
+ * would make the next marketplace a code change instead of an adapter.
143
+ *
144
+ * The HTTP client is a host port ({@link MarketplaceHttp}), handed to every
145
+ * outbound call. An adapter never reaches the network on its own, so tests
146
+ * answer the seam and nothing else, and the host owns the timeout, the proxy
147
+ * and the CA.
148
+ */
149
+ /** A marketplace's credentials, as the merchant supplies them. Sealed at rest. */
150
+ interface MarketplaceCredentials {
151
+ clientId: string;
152
+ clientSecret: string;
153
+ /**
154
+ * The shared secret a delivery's signature is verified against. Separate
155
+ * from the OAuth pair: a merchant rotating their webhook secret has not
156
+ * re-onboarded.
157
+ */
158
+ webhookSecret: string | null;
159
+ }
160
+ /** What the host's HTTP client takes. */
161
+ interface MarketplaceHttpRequest {
162
+ method: "GET" | "POST" | "PUT";
163
+ url: string;
164
+ headers: Record<string, string>;
165
+ body?: string;
166
+ }
167
+ /** What the host's HTTP client answers: any status, never a throw for a 4xx or 5xx. */
168
+ interface MarketplaceHttpResponse {
169
+ status: number;
170
+ body: string;
171
+ }
172
+ /** The host's HTTP client. It throws only when no answer arrived (a timeout, a network error). */
173
+ type MarketplaceHttp = (request: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>;
174
+ /** What a marketplace can do, stated by its adapter. */
175
+ interface MarketplaceCapabilities {
176
+ /** Accepting is answered through the API. */
177
+ apiConfirm: boolean;
178
+ /** A cancellation can be requested through the API at all. */
179
+ apiCancel: boolean;
180
+ /** …and still once the order was accepted. */
181
+ cancelAfterAccept: boolean;
182
+ /** The cancellation's outcome arrives later as an event rather than in the answer. */
183
+ asyncCancellationOutcome: boolean;
184
+ /** `appLink` names this order, rather than only the marketplace's portal. */
185
+ perOrderAppLink: boolean;
186
+ /** Confirming states a preparation time. */
187
+ confirmTakesPreparationTime: boolean;
188
+ }
189
+ /** One reason a store may give for refusing or cancelling an order. */
190
+ interface CancellationReason {
191
+ /** The marketplace's own code, sent verbatim. */
192
+ code: string;
193
+ /** The label the host was configured with for this code (a named pack). */
194
+ label: string;
195
+ /** This reason means "an item is unavailable": the host preselects it when stock is short. */
196
+ itemUnavailable: boolean;
197
+ /** The marketplace requires the offending SKUs with this reason. */
198
+ needsItems: boolean;
199
+ }
200
+ /** The order an outbound call is about, as the engine knows it. */
201
+ interface OutboundOrderRef {
202
+ externalOrderId: string;
203
+ externalDisplayId: string | null;
204
+ /** The host's own id for the order. */
205
+ hostOrderCode: string;
206
+ /** When the engine recorded the order. */
207
+ placedAt: Date;
208
+ }
209
+ /** A per-engine token cache an adapter reads and fills. Never persisted. */
210
+ type AdapterTokenCache = Map<string, {
211
+ token: string;
212
+ expiresAt: number;
213
+ }>;
214
+ /** What one outbound call is handed. */
215
+ interface AdapterCallContext {
216
+ http: MarketplaceHttp;
217
+ credentials: MarketplaceCredentials;
218
+ environment: "SANDBOX" | "PRODUCTION";
219
+ /** Written to no row, log or audit entry: memory only, per process. */
220
+ tokens: AdapterTokenCache;
221
+ now: Date;
222
+ }
223
+ /** One outbound call's answer, in the three shapes the engine acts on. */
224
+ type OutboundResult =
225
+ /** 2xx. For a marketplace whose outcome is asynchronous, "the request was taken". */
226
+ {
227
+ kind: "accepted";
228
+ }
229
+ /** A final 4xx (not 408/425/429): never retried. */
230
+ | {
231
+ kind: "refused";
232
+ status: number;
233
+ message: string;
234
+ }
235
+ /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */
236
+ | {
237
+ kind: "retry";
238
+ reason: string;
239
+ };
240
+ /** What a cancellation request carries. */
241
+ interface CancellationRequestInput {
242
+ reason: CancellationReason;
243
+ /** Free text from the store; empty means "the reason's own label". */
244
+ text: string;
245
+ mode: "MANUAL" | "AUTO";
246
+ offendingSkus: readonly string[];
247
+ }
248
+ /** One marketplace, in and out. */
249
+ interface MarketplaceAdapter {
250
+ readonly provider: MarketplaceProvider;
251
+ readonly capabilities: MarketplaceCapabilities;
252
+ /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */
253
+ normalize(payload: unknown): NormalizedEvent | null;
254
+ /** Which header carries this marketplace's signature, read off the request. */
255
+ readSignature(header: (name: string) => string | null): string | null;
256
+ /** Is this delivery's signature the one this store's secret would produce? */
257
+ verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;
258
+ /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */
259
+ cancellationReasons(): readonly CancellationReason[];
260
+ /** Tell the marketplace the store accepted the order. */
261
+ confirm(ctx: AdapterCallContext, order: OutboundOrderRef, input: {
262
+ preparationMinutes: number | null;
263
+ }): Promise<OutboundResult>;
264
+ /** Ask the marketplace to cancel the order, with one of its own reasons. */
265
+ requestCancellation(ctx: AdapterCallContext, order: OutboundOrderRef, input: CancellationRequestInput): Promise<OutboundResult>;
266
+ /** Where "open it on the marketplace" goes: the order when `perOrderAppLink`, else the portal. Always https. */
267
+ appLink(order: Pick<OutboundOrderRef, "externalOrderId" | "externalDisplayId">): string;
268
+ }
269
+ /**
270
+ * Read one HTTP answer the way the engine acts on it. Shared by every adapter
271
+ * whose API speaks plain status codes, so the rule is one rule rather than one
272
+ * per marketplace: 2xx accepted; a 4xx other than 408/425/429 refused and
273
+ * final; everything else (408, 425, 429, 5xx, anything unexpected) retried.
274
+ */
275
+ declare function outboundResultOf(response: MarketplaceHttpResponse): OutboundResult;
276
+ /** A call that never got an answer is a retry, with the reason a log can read. */
277
+ declare function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult>;
278
+
279
+ export { type AdapterCallContext as A, type CancellationReason as C, type MarketplaceAdapter as M, type NormalizedEvent as N, type OutboundOrderRef as O, PROVIDER_ID_PATTERN as P, type MarketplaceProvider as a, type AdapterTokenCache as b, type CancellationOutcome as c, type CancellationRequestInput as d, type MarketplaceCapabilities as e, type MarketplaceCredentials as f, type MarketplaceDeliveredBy as g, type MarketplaceHttp as h, type MarketplaceHttpRequest as i, type MarketplaceHttpResponse as j, type MarketplaceOrderType as k, type NormalizedAddress as l, type NormalizedBuyer as m, type NormalizedMarketplaceOrder as n, type NormalizedOrderLine as o, type OutboundResult as p, answered as q, outboundResultOf as r };