@12-apps/marketplace 1.7.0 → 1.8.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.
- package/ADOPTING.md +17 -0
- package/README.md +56 -0
- package/dist/99food/index.d.ts +4 -2
- package/dist/99food/index.js +32 -3
- package/dist/99food/index.js.map +1 -1
- package/dist/{adapter-DOjTak1H.d.ts → adapter-CYJzu1c9.d.ts} +45 -1
- package/dist/{chunk-YVUZHXUF.js → chunk-6N2HEV3U.js} +4 -4
- package/dist/chunk-6N2HEV3U.js.map +1 -0
- package/dist/{chunk-SJUKBCVO.js → chunk-BMCERPQX.js} +198 -12
- package/dist/chunk-BMCERPQX.js.map +1 -0
- package/dist/{chunk-L3DCOZUU.js → chunk-HEXLCTOG.js} +1 -1
- package/dist/chunk-HEXLCTOG.js.map +1 -0
- package/dist/{chunk-UYFYGGCS.js → chunk-NP4EYKPO.js} +3 -1
- package/dist/chunk-NP4EYKPO.js.map +1 -0
- package/dist/{engine-DG1fg43Y.d.ts → engine-wmW-VuBL.d.ts} +107 -4
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +3 -3
- package/dist/ifood/index.d.ts +1 -1
- package/dist/ifood/index.js +29 -3
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +104 -7
- package/dist/index.js.map +1 -1
- package/dist/manifest/index.d.ts +3 -0
- package/dist/manifest/index.js +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/manifest/server.js +3 -3
- package/dist/rappi/index.d.ts +7 -1
- package/dist/rappi/index.js +20 -3
- package/dist/rappi/index.js.map +1 -1
- package/dist/server/index.d.ts +6 -2
- package/dist/server/index.js +3 -3
- package/package.json +1 -1
- package/prisma/marketplace.prisma +45 -1
- package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
- package/src/99food/index.ts +6 -0
- package/src/99food/normalize.ts +7 -1
- package/src/99food/outbound.ts +55 -0
- package/src/core/adapter.ts +41 -1
- package/src/core/bulk.ts +1 -1
- package/src/core/engine.ts +9 -0
- package/src/core/ingest.ts +6 -0
- package/src/core/integration.ts +17 -0
- package/src/core/lifecycle-port.ts +16 -0
- package/src/core/lifecycle.ts +133 -0
- package/src/core/outbound-queue.ts +24 -4
- package/src/core/outbound-sweep.ts +49 -5
- package/src/core/outbound.ts +11 -0
- package/src/core/pipeline.ts +22 -2
- package/src/core/ports.ts +39 -3
- package/src/core/status-inform.ts +51 -0
- package/src/core/status-job.ts +207 -0
- package/src/core/status-store.ts +85 -0
- package/src/core/types.ts +14 -0
- package/src/ifood/index.ts +7 -1
- package/src/ifood/normalize.ts +17 -0
- package/src/ifood/outbound.ts +35 -0
- package/src/index.ts +6 -0
- package/src/rappi/index.ts +6 -1
- package/src/rappi/normalize.ts +6 -0
- package/src/rappi/outbound.ts +31 -2
- package/src/server/mcp.ts +2 -0
- package/src/server/webhook.ts +3 -1
- package/dist/chunk-L3DCOZUU.js.map +0 -1
- package/dist/chunk-SJUKBCVO.js.map +0 -1
- package/dist/chunk-UYFYGGCS.js.map +0 -1
- package/dist/chunk-YVUZHXUF.js.map +0 -1
package/dist/manifest/index.d.ts
CHANGED
|
@@ -75,6 +75,7 @@ declare const marketplaceManifest: {
|
|
|
75
75
|
}>;
|
|
76
76
|
externalMerchantId: zod.ZodNullable<zod.ZodString>;
|
|
77
77
|
autoAccept: zod.ZodBoolean;
|
|
78
|
+
followStatus: zod.ZodBoolean;
|
|
78
79
|
ackSlaSeconds: zod.ZodNumber;
|
|
79
80
|
connected: zod.ZodBoolean;
|
|
80
81
|
lastEventAt: zod.ZodNullable<zod.ZodString>;
|
|
@@ -127,6 +128,7 @@ declare const marketplaceManifest: {
|
|
|
127
128
|
}>>;
|
|
128
129
|
externalMerchantId: zod.ZodOptional<zod.ZodNullable<zod.ZodString>>;
|
|
129
130
|
autoAccept: zod.ZodOptional<zod.ZodBoolean>;
|
|
131
|
+
followStatus: zod.ZodOptional<zod.ZodBoolean>;
|
|
130
132
|
ackSlaSeconds: zod.ZodOptional<zod.ZodNumber>;
|
|
131
133
|
credentials: zod.ZodOptional<zod.ZodObject<{
|
|
132
134
|
clientId: zod.ZodString;
|
|
@@ -152,6 +154,7 @@ declare const marketplaceManifest: {
|
|
|
152
154
|
}>;
|
|
153
155
|
externalMerchantId: zod.ZodNullable<zod.ZodString>;
|
|
154
156
|
autoAccept: zod.ZodBoolean;
|
|
157
|
+
followStatus: zod.ZodBoolean;
|
|
155
158
|
ackSlaSeconds: zod.ZodNumber;
|
|
156
159
|
connected: zod.ZodBoolean;
|
|
157
160
|
lastEventAt: zod.ZodNullable<zod.ZodString>;
|
package/dist/manifest/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ah as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-wmW-VuBL.js';
|
|
2
2
|
import * as _12_apps_wiring from '@12-apps/wiring';
|
|
3
3
|
import { createApiMarketplace, MarketplaceJobDeps } from '../server/index.js';
|
|
4
|
-
import '../adapter-
|
|
4
|
+
import '../adapter-CYJzu1c9.js';
|
|
5
5
|
import 'zod';
|
|
6
6
|
|
|
7
7
|
declare const marketplaceServerManifest: {
|
package/dist/manifest/server.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
MARKETPLACE_JOBS,
|
|
3
3
|
createApiMarketplace
|
|
4
|
-
} from "../chunk-
|
|
5
|
-
import "../chunk-
|
|
6
|
-
import "../chunk-
|
|
4
|
+
} from "../chunk-6N2HEV3U.js";
|
|
5
|
+
import "../chunk-NP4EYKPO.js";
|
|
6
|
+
import "../chunk-BMCERPQX.js";
|
|
7
7
|
import "../chunk-7QVYU63E.js";
|
|
8
8
|
|
|
9
9
|
// src/manifest/server.ts
|
package/dist/rappi/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-
|
|
1
|
+
import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CYJzu1c9.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* The words the Rappi adapter needs from its host, and nothing else.
|
|
@@ -58,6 +58,12 @@ interface RappiAdapterCopy {
|
|
|
58
58
|
* else is recorded and IGNORED: a missed cancellation is visible in the inbox,
|
|
59
59
|
* a false one would cancel a live order.
|
|
60
60
|
*
|
|
61
|
+
* Rappi maps NO lifecycle event (FUT-4653: no `lifecycle` on any event it
|
|
62
|
+
* normalizes). ESTIMATED: the `event` values of ORDER_OTHER_EVENT are
|
|
63
|
+
* undocumented (https://dev-portal.rappi.com/, read 2026-11-25), so nothing
|
|
64
|
+
* here can name "dispatched" or "concluded" without guessing; such an event
|
|
65
|
+
* stays IGNORED, as before.
|
|
66
|
+
*
|
|
61
67
|
* Rappi payloads carry no event id, so the inbox key is derived from the
|
|
62
68
|
* order and the event, deterministic so a redelivery collides on the inbox's
|
|
63
69
|
* unique index.
|
package/dist/rappi/index.js
CHANGED
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
answered,
|
|
10
10
|
outboundResultOf,
|
|
11
11
|
tokenGrantResultOf
|
|
12
|
-
} from "../chunk-
|
|
12
|
+
} from "../chunk-HEXLCTOG.js";
|
|
13
13
|
import {
|
|
14
14
|
__name
|
|
15
15
|
} from "../chunk-7QVYU63E.js";
|
|
@@ -247,7 +247,7 @@ async function putOrder(ctx, hosts, request) {
|
|
|
247
247
|
const auth = await bearer(ctx, hosts);
|
|
248
248
|
if (!("token" in auth)) return auth;
|
|
249
249
|
const response = await ctx.http({
|
|
250
|
-
method: "PUT",
|
|
250
|
+
method: request.method ?? "PUT",
|
|
251
251
|
url: `${trimmed(hosts.api[ctx.environment])}/orders/${encodeURIComponent(request.externalOrderId)}/${request.action}`,
|
|
252
252
|
headers: {
|
|
253
253
|
"x-authorization": `Bearer ${auth.token}`,
|
|
@@ -280,6 +280,18 @@ function rappiReject(ctx, hosts, order, input) {
|
|
|
280
280
|
});
|
|
281
281
|
}
|
|
282
282
|
__name(rappiReject, "rappiReject");
|
|
283
|
+
function rappiStatusSupported(facts) {
|
|
284
|
+
return facts.step === "READY";
|
|
285
|
+
}
|
|
286
|
+
__name(rappiStatusSupported, "rappiStatusSupported");
|
|
287
|
+
function rappiInformStatus(ctx, hosts, order, facts) {
|
|
288
|
+
if (facts.step !== "READY") return Promise.resolve({ kind: "unsupported" });
|
|
289
|
+
return answered(async () => {
|
|
290
|
+
const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: "ready-for-pickup", method: "POST" });
|
|
291
|
+
return "kind" in response ? response : outboundResultOf(response);
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
__name(rappiInformStatus, "rappiInformStatus");
|
|
283
295
|
|
|
284
296
|
// src/rappi/pause.ts
|
|
285
297
|
function refusalIn(body, storeId) {
|
|
@@ -385,7 +397,10 @@ function createRappiAdapter(config) {
|
|
|
385
397
|
perOrderAppLink: false,
|
|
386
398
|
// `take/{cookingTime}`, in minutes.
|
|
387
399
|
confirmTakesPreparationTime: true,
|
|
388
|
-
cancellationAnswerWindowMs: RAPPI_CANCELLATION_ANSWER_WINDOW_MS
|
|
400
|
+
cancellationAnswerWindowMs: RAPPI_CANCELLATION_ANSWER_WINDOW_MS,
|
|
401
|
+
// READY only, and ESTIMATED (see `./outbound.ts`). Rappi's normalizer maps no
|
|
402
|
+
// lifecycle event: its `event` values are undocumented (see `./normalize.ts`).
|
|
403
|
+
statusSteps: ["READY"]
|
|
389
404
|
},
|
|
390
405
|
normalize: /* @__PURE__ */ __name((payload) => normalizeRappiEvent(payload, normalizeOptions), "normalize"),
|
|
391
406
|
readSignature: /* @__PURE__ */ __name((header) => header(RAPPI_SIGNATURE_HEADER), "readSignature"),
|
|
@@ -393,6 +408,8 @@ function createRappiAdapter(config) {
|
|
|
393
408
|
cancellationReasons: /* @__PURE__ */ __name(() => reasons, "cancellationReasons"),
|
|
394
409
|
confirm: /* @__PURE__ */ __name((ctx, order, input) => rappiTake(ctx, hosts, order, input), "confirm"),
|
|
395
410
|
requestCancellation: /* @__PURE__ */ __name((ctx, order, input) => rappiReject(ctx, hosts, order, input), "requestCancellation"),
|
|
411
|
+
statusSupported: rappiStatusSupported,
|
|
412
|
+
informStatus: /* @__PURE__ */ __name((ctx, order, facts) => rappiInformStatus(ctx, hosts, order, facts), "informStatus"),
|
|
396
413
|
appLink: /* @__PURE__ */ __name(() => config.portalUrl, "appLink"),
|
|
397
414
|
...config.pauseByStoreSwitch ? { availability: rappiAvailability(hosts) } : {}
|
|
398
415
|
};
|
package/dist/rappi/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/rappi/copy.ts","../../src/rappi/normalize.ts","../../src/rappi/outbound.ts","../../src/rappi/pause.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 tokenGrantResultOf,\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. */\nexport function 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 */\nexport async 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 = tokenGrantResultOf(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 {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type OutboundResult,\n} from \"../core/adapter\";\nimport type { MarketplaceAvailability, StorePauseRequest, StorePauseResult } from \"../core/pause-port\";\nimport { RAPPI_PROVIDER } from \"./normalize\";\nimport { bearer, trimmed, type RappiHosts } from \"./outbound\";\n\n/**\n * Rappi's half of the store pause (FUT-4851): a store-wide SWITCH, from\n * Rappi's public developer portal (dev-portal.rappi.com, api-reference\n * \"availability\", read 2026-11-13):\n *\n * `PUT https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api/availability/stores/enable`,\n * synchronous, with `{ stores: [{ store_id, is_enabled }] }`; 200 with a\n * `results` array (`store_id`, `is_enabled`, `operation_result`,\n * `operation_result_type`, `operation_result_message`, `suspended_reason`, …),\n * 400, 403 \"not allowed to update those stores\", 422 too many stores, 502.\n *\n * A switch has no id and no end: the engine turns a store on only when its\n * own record says it turned it off, and turns it on by itself once the\n * kitchen's `until` has passed unrenewed. What it cannot tell apart is a store\n * the owner ALSO closed by hand during the kitchen's pause, which is why the\n * adapter offers this only when the host opts in (`pauseByStoreSwitch`).\n *\n * ESTIMATED: which id `store_id` is (the portal says \"the one from your\n * system\" for this call; the engine sends the connection's merchant id, the\n * store id Rappi's own events carry), and how a per-store failure reads in\n * `results` (an `operation_result` of `false`, or a `operation_result_type`\n * naming an error, is taken as a refusal with `operation_result_message`).\n */\n\ninterface RappiStoreResult {\n store_id?: unknown;\n operation_result?: unknown;\n operation_result_type?: unknown;\n operation_result_message?: unknown;\n}\n\n/** This store's entry in the answer's `results`, judged; null when the answer names it as done. */\nfunction refusalIn(body: string, storeId: string): Exclude<OutboundResult, { kind: \"accepted\" }> | null {\n let results: RappiStoreResult[];\n try {\n const parsed = JSON.parse(body === \"\" ? \"{}\" : body) as { results?: unknown };\n results = Array.isArray(parsed.results) ? (parsed.results as RappiStoreResult[]) : [];\n } catch {\n return null;\n }\n const entry = results.find((result) => String(result.store_id) === storeId);\n if (!entry) return null;\n const type = typeof entry.operation_result_type === \"string\" ? entry.operation_result_type : \"\";\n const failed = entry.operation_result === false || /error|fail/iu.test(type);\n if (!failed) return null;\n const message = typeof entry.operation_result_message === \"string\" ? entry.operation_result_message : type;\n return { kind: \"refused\", status: 200, message: message.slice(0, 300) };\n}\n\nconst tokenKey = (ctx: AdapterCallContext): string => `${RAPPI_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** Turn the store on or off; the answer judged for THIS store. */\nexport function rappiSetStoreEnabled(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n storeId: string,\n enabled: boolean,\n): Promise<OutboundResult> {\n return answered(async () => {\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])}/availability/stores/enable`,\n headers: { \"x-authorization\": `Bearer ${auth.token}`, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ stores: [{ store_id: storeId, is_enabled: enabled }] }),\n });\n if (response.status === 401) {\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"Rappi refused the token\" };\n }\n const result = outboundResultOf(response);\n if (result.kind !== \"accepted\") return result;\n return refusalIn(response.body, storeId) ?? result;\n });\n}\n\n/** Rappi's availability capability: a switch, offered only when the host opts in. */\nexport function rappiAvailability(hosts: RappiHosts): MarketplaceAvailability {\n return {\n kind: \"switch\",\n pause: async (ctx: AdapterCallContext, request: StorePauseRequest): Promise<StorePauseResult> => {\n const result = await rappiSetStoreEnabled(ctx, hosts, request.merchantId, false);\n return result.kind === \"accepted\" ? { kind: \"paused\", externalId: null, until: request.until } : result;\n },\n resume: (ctx, ref) => rappiSetStoreEnabled(ctx, hosts, ref.merchantId, true),\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\";\nimport { rappiAvailability } from \"./pause\";\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 * OPTIONAL, off by default. Offer the store pause (FUT-4851) through Rappi's\n * store on/off switch. A switch has no id, so the engine cannot tell its own\n * closure from one the owner made by hand meanwhile: a store the owner also\n * turned off on Rappi during the kitchen's pause is turned on with it. A\n * host turns this on knowing that.\n */\n pauseByStoreSwitch?: boolean;\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 ...(config.pauseByStoreSwitch ? { availability: rappiAvailability(hosts) } : {}),\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\";\nexport { rappiAvailability, rappiSetStoreEnabled } from \"./pause\";\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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,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,IACT,GAAI,OAAO,qBAAqB,EAAE,cAAc,kBAAkB,KAAK,EAAE,IAAI,CAAC;AAAA,EAChF;AACF;AAvCgB;","names":["tokenKey"]}
|
|
1
|
+
{"version":3,"sources":["../../src/rappi/copy.ts","../../src/rappi/normalize.ts","../../src/rappi/outbound.ts","../../src/rappi/pause.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 maps NO lifecycle event (FUT-4653: no `lifecycle` on any event it\n * normalizes). ESTIMATED: the `event` values of ORDER_OTHER_EVENT are\n * undocumented (https://dev-portal.rappi.com/, read 2026-11-25), so nothing\n * here can name \"dispatched\" or \"concluded\" without guessing; such an event\n * stays IGNORED, as before.\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 tokenGrantResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type MarketplaceHttpResponse,\n type OutboundOrderRef,\n type OutboundResult,\n type StatusFacts,\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. */\nexport function 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 */\nexport async 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 = tokenGrantResultOf(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; method?: \"PUT\" | \"POST\" },\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: request.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\n/**\n * What Rappi is told per step (FUT-4653). READY only: `POST {api}/orders/{id}/ready-for-pickup`\n * (Rappi's dev portal, https://dev-portal.rappi.com/, \"Managing User Orders\",\n * read 2026-11-25), which the portal says is for a store on MANUAL\n * notification (Rappi recommends Automatic): any other store's call may be\n * refused, which ends FAILED and logged, never retried. ESTIMATED: the verb is\n * POST in the portal while the other order calls here are PUT. No endpoint\n * was found for DISPATCHED (Rappi's own couriers carry the order) nor for\n * HANDED_OVER, so those are unsupported.\n */\nexport function rappiStatusSupported(facts: StatusFacts): boolean {\n return facts.step === \"READY\";\n}\n\n/** Tell Rappi a step happened. `unsupported` for every step but READY. */\nexport function rappiInformStatus(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n order: OutboundOrderRef,\n facts: StatusFacts,\n): Promise<OutboundResult | { kind: \"unsupported\" }> {\n if (facts.step !== \"READY\") return Promise.resolve({ kind: \"unsupported\" });\n return answered(async () => {\n const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: \"ready-for-pickup\", method: \"POST\" });\n return \"kind\" in response ? response : outboundResultOf(response);\n });\n}\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type OutboundResult,\n} from \"../core/adapter\";\nimport type { MarketplaceAvailability, StorePauseRequest, StorePauseResult } from \"../core/pause-port\";\nimport { RAPPI_PROVIDER } from \"./normalize\";\nimport { bearer, trimmed, type RappiHosts } from \"./outbound\";\n\n/**\n * Rappi's half of the store pause (FUT-4851): a store-wide SWITCH, from\n * Rappi's public developer portal (dev-portal.rappi.com, api-reference\n * \"availability\", read 2026-11-13):\n *\n * `PUT https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api/availability/stores/enable`,\n * synchronous, with `{ stores: [{ store_id, is_enabled }] }`; 200 with a\n * `results` array (`store_id`, `is_enabled`, `operation_result`,\n * `operation_result_type`, `operation_result_message`, `suspended_reason`, …),\n * 400, 403 \"not allowed to update those stores\", 422 too many stores, 502.\n *\n * A switch has no id and no end: the engine turns a store on only when its\n * own record says it turned it off, and turns it on by itself once the\n * kitchen's `until` has passed unrenewed. What it cannot tell apart is a store\n * the owner ALSO closed by hand during the kitchen's pause, which is why the\n * adapter offers this only when the host opts in (`pauseByStoreSwitch`).\n *\n * ESTIMATED: which id `store_id` is (the portal says \"the one from your\n * system\" for this call; the engine sends the connection's merchant id, the\n * store id Rappi's own events carry), and how a per-store failure reads in\n * `results` (an `operation_result` of `false`, or a `operation_result_type`\n * naming an error, is taken as a refusal with `operation_result_message`).\n */\n\ninterface RappiStoreResult {\n store_id?: unknown;\n operation_result?: unknown;\n operation_result_type?: unknown;\n operation_result_message?: unknown;\n}\n\n/** This store's entry in the answer's `results`, judged; null when the answer names it as done. */\nfunction refusalIn(body: string, storeId: string): Exclude<OutboundResult, { kind: \"accepted\" }> | null {\n let results: RappiStoreResult[];\n try {\n const parsed = JSON.parse(body === \"\" ? \"{}\" : body) as { results?: unknown };\n results = Array.isArray(parsed.results) ? (parsed.results as RappiStoreResult[]) : [];\n } catch {\n return null;\n }\n const entry = results.find((result) => String(result.store_id) === storeId);\n if (!entry) return null;\n const type = typeof entry.operation_result_type === \"string\" ? entry.operation_result_type : \"\";\n const failed = entry.operation_result === false || /error|fail/iu.test(type);\n if (!failed) return null;\n const message = typeof entry.operation_result_message === \"string\" ? entry.operation_result_message : type;\n return { kind: \"refused\", status: 200, message: message.slice(0, 300) };\n}\n\nconst tokenKey = (ctx: AdapterCallContext): string => `${RAPPI_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** Turn the store on or off; the answer judged for THIS store. */\nexport function rappiSetStoreEnabled(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n storeId: string,\n enabled: boolean,\n): Promise<OutboundResult> {\n return answered(async () => {\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])}/availability/stores/enable`,\n headers: { \"x-authorization\": `Bearer ${auth.token}`, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ stores: [{ store_id: storeId, is_enabled: enabled }] }),\n });\n if (response.status === 401) {\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"Rappi refused the token\" };\n }\n const result = outboundResultOf(response);\n if (result.kind !== \"accepted\") return result;\n return refusalIn(response.body, storeId) ?? result;\n });\n}\n\n/** Rappi's availability capability: a switch, offered only when the host opts in. */\nexport function rappiAvailability(hosts: RappiHosts): MarketplaceAvailability {\n return {\n kind: \"switch\",\n pause: async (ctx: AdapterCallContext, request: StorePauseRequest): Promise<StorePauseResult> => {\n const result = await rappiSetStoreEnabled(ctx, hosts, request.merchantId, false);\n return result.kind === \"accepted\" ? { kind: \"paused\", externalId: null, until: request.until } : result;\n },\n resume: (ctx, ref) => rappiSetStoreEnabled(ctx, hosts, ref.merchantId, true),\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 { rappiInformStatus, rappiReject, rappiStatusSupported, rappiTake, type RappiBaseUrls } from \"./outbound\";\nimport { rappiAvailability } from \"./pause\";\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 * OPTIONAL, off by default. Offer the store pause (FUT-4851) through Rappi's\n * store on/off switch. A switch has no id, so the engine cannot tell its own\n * closure from one the owner made by hand meanwhile: a store the owner also\n * turned off on Rappi during the kitchen's pause is turned on with it. A\n * host turns this on knowing that.\n */\n pauseByStoreSwitch?: boolean;\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 // READY only, and ESTIMATED (see `./outbound.ts`). Rappi's normalizer maps no\n // lifecycle event: its `event` values are undocumented (see `./normalize.ts`).\n statusSteps: [\"READY\"],\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 statusSupported: rappiStatusSupported,\n informStatus: (ctx, order, facts) => rappiInformStatus(ctx, hosts, order, facts),\n appLink: () => config.portalUrl,\n ...(config.pauseByStoreSwitch ? { availability: rappiAvailability(hosts) } : {}),\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\";\nexport { rappiAvailability, rappiSetStoreEnabled } from \"./pause\";\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;;;ACoBtH,IAAM,iBAAiB;AAGvB,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AAA,IACT,qBAAqB,wBAAC,KAAK,OAAO,UAAU,YAAY,KAAK,OAAO,OAAO,KAAK,GAA3D;AAAA,IACrB,iBAAiB;AAAA,IACjB,cAAc,wBAAC,KAAK,OAAO,UAAU,kBAAkB,KAAK,OAAO,OAAO,KAAK,GAAjE;AAAA,IACd,SAAS,6BAAM,OAAO,WAAb;AAAA,IACT,GAAI,OAAO,qBAAqB,EAAE,cAAc,kBAAkB,KAAK,EAAE,IAAI,CAAC;AAAA,EAChF;AACF;AA5CgB;","names":["tokenKey"]}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { y as DecisionProblemCode, f as BulkProblemCode,
|
|
1
|
+
import { y as DecisionProblemCode, f as BulkProblemCode, _ as MarketplaceEngine, a4 as MarketplaceLogger, ah as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-wmW-VuBL.js';
|
|
2
2
|
import { WireRoute, WireJobBlueprint } from '@12-apps/wiring';
|
|
3
3
|
import { z } from 'zod';
|
|
4
|
-
import '../adapter-
|
|
4
|
+
import '../adapter-CYJzu1c9.js';
|
|
5
5
|
|
|
6
6
|
/** Every problem code a route can answer, decisions and bulk writes alike. */
|
|
7
7
|
type MarketplaceProblemCode = DecisionProblemCode | BulkProblemCode;
|
|
@@ -199,6 +199,7 @@ declare const upsertMarketplaceIntegrationsBody: z.ZodObject<{
|
|
|
199
199
|
}>>;
|
|
200
200
|
externalMerchantId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
201
201
|
autoAccept: z.ZodOptional<z.ZodBoolean>;
|
|
202
|
+
followStatus: z.ZodOptional<z.ZodBoolean>;
|
|
202
203
|
ackSlaSeconds: z.ZodOptional<z.ZodNumber>;
|
|
203
204
|
credentials: z.ZodOptional<z.ZodObject<{
|
|
204
205
|
clientId: z.ZodString;
|
|
@@ -279,6 +280,7 @@ declare const MARKETPLACE_MCP_TOOLS: readonly [{
|
|
|
279
280
|
}>;
|
|
280
281
|
externalMerchantId: z.ZodNullable<z.ZodString>;
|
|
281
282
|
autoAccept: z.ZodBoolean;
|
|
283
|
+
followStatus: z.ZodBoolean;
|
|
282
284
|
ackSlaSeconds: z.ZodNumber;
|
|
283
285
|
connected: z.ZodBoolean;
|
|
284
286
|
lastEventAt: z.ZodNullable<z.ZodString>;
|
|
@@ -331,6 +333,7 @@ declare const MARKETPLACE_MCP_TOOLS: readonly [{
|
|
|
331
333
|
}>>;
|
|
332
334
|
externalMerchantId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
333
335
|
autoAccept: z.ZodOptional<z.ZodBoolean>;
|
|
336
|
+
followStatus: z.ZodOptional<z.ZodBoolean>;
|
|
334
337
|
ackSlaSeconds: z.ZodOptional<z.ZodNumber>;
|
|
335
338
|
credentials: z.ZodOptional<z.ZodObject<{
|
|
336
339
|
clientId: z.ZodString;
|
|
@@ -356,6 +359,7 @@ declare const MARKETPLACE_MCP_TOOLS: readonly [{
|
|
|
356
359
|
}>;
|
|
357
360
|
externalMerchantId: z.ZodNullable<z.ZodString>;
|
|
358
361
|
autoAccept: z.ZodBoolean;
|
|
362
|
+
followStatus: z.ZodBoolean;
|
|
359
363
|
ackSlaSeconds: z.ZodNumber;
|
|
360
364
|
connected: z.ZodBoolean;
|
|
361
365
|
lastEventAt: z.ZodNullable<z.ZodString>;
|
package/dist/server/index.js
CHANGED
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
MARKETPLACE_SWEEP_QUEUE,
|
|
7
7
|
ORDER_NOT_PENDING_CODE,
|
|
8
8
|
createApiMarketplace
|
|
9
|
-
} from "../chunk-
|
|
9
|
+
} from "../chunk-6N2HEV3U.js";
|
|
10
10
|
import {
|
|
11
11
|
MARKETPLACE_DECIDE,
|
|
12
12
|
MARKETPLACE_MANAGE,
|
|
@@ -19,8 +19,8 @@ import {
|
|
|
19
19
|
marketplaceParams,
|
|
20
20
|
upsertMarketplaceIntegrationsBody,
|
|
21
21
|
upsertMarketplaceMenuLinksBody
|
|
22
|
-
} from "../chunk-
|
|
23
|
-
import "../chunk-
|
|
22
|
+
} from "../chunk-NP4EYKPO.js";
|
|
23
|
+
import "../chunk-BMCERPQX.js";
|
|
24
24
|
import "../chunk-7QVYU63E.js";
|
|
25
25
|
export {
|
|
26
26
|
MARKETPLACE_AVAILABILITY_ATTEMPTS,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@12-apps/marketplace",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.8.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
|
|
4
|
+
// The eight 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.
|
|
@@ -53,6 +53,11 @@ model MarketplaceIntegration {
|
|
|
53
53
|
/// learning it does.
|
|
54
54
|
autoAccept Boolean @default(false) @map("auto_accept")
|
|
55
55
|
|
|
56
|
+
/// Whether the marketplace's DISPATCHED and CONCLUDED events move the pedido
|
|
57
|
+
/// forward here (FUT-4653). Governs the INBOUND move only: telling the
|
|
58
|
+
/// marketplace what the store did is always on where it has an endpoint.
|
|
59
|
+
followStatus Boolean @default(true) @map("follow_status")
|
|
60
|
+
|
|
56
61
|
/// How long this store may take to answer, in seconds. Per-connection because
|
|
57
62
|
/// the marketplace's own cancellation window differs by merchant tier.
|
|
58
63
|
ackSlaSeconds Int @default(300) @map("ack_sla_seconds")
|
|
@@ -407,3 +412,42 @@ model MarketplaceStorePause {
|
|
|
407
412
|
@@index([wanted, until])
|
|
408
413
|
@@map("marketplace_store_pauses")
|
|
409
414
|
}
|
|
415
|
+
|
|
416
|
+
/// One step of a pedido, as the engine told the marketplace or the marketplace
|
|
417
|
+
/// told the engine (FUT-4653).
|
|
418
|
+
///
|
|
419
|
+
/// `source` STORE: the engine tells (or is telling, or failed to tell) the
|
|
420
|
+
/// marketplace the pedido reached `step` (READY, DISPATCHED, HANDED_OVER), and
|
|
421
|
+
/// the row is both the claim that keeps a step from ever being sent twice and
|
|
422
|
+
/// the marker an inbound echo is recognised by. `source` MARKETPLACE, state
|
|
423
|
+
/// NOTED: the marketplace announced `step` (DISPATCHED, CONCLUDED) so the
|
|
424
|
+
/// engine never informs it back. SENDING | SENT | FAILED | NOTED (CHECK).
|
|
425
|
+
/// By-value `clientId` and `orderId`, no foreign key, as every table here.
|
|
426
|
+
model MarketplaceStatusUpdate {
|
|
427
|
+
id String @id @default(uuid())
|
|
428
|
+
clientId String @map("client_id")
|
|
429
|
+
orderId String @map("order_id")
|
|
430
|
+
provider String
|
|
431
|
+
|
|
432
|
+
/// READY | DISPATCHED | HANDED_OVER | CONCLUDED (CHECK).
|
|
433
|
+
step String
|
|
434
|
+
/// STORE | MARKETPLACE (CHECK).
|
|
435
|
+
source String
|
|
436
|
+
/// SENDING | SENT | FAILED | NOTED (CHECK).
|
|
437
|
+
state String
|
|
438
|
+
|
|
439
|
+
/// WHO holds a SENDING claim: the key of the move (or of the sweep's
|
|
440
|
+
/// re-claim) the status job carries. A run re-enters a SENDING row, and
|
|
441
|
+
/// stamps or fails it, only under its own key, so two jobs for one step
|
|
442
|
+
/// never both call the marketplace. Empty on a row the marketplace noted.
|
|
443
|
+
claimKey String @map("claim_key")
|
|
444
|
+
|
|
445
|
+
createdAt DateTime @default(now()) @map("created_at")
|
|
446
|
+
updatedAt DateTime @updatedAt @map("updated_at")
|
|
447
|
+
|
|
448
|
+
@@unique([orderId, step])
|
|
449
|
+
// The sweep reads only rows still SENDING: a PARTIAL index, SQL-only in the
|
|
450
|
+
// migration (marketplace_status_updates_state_updated_at_idx, WHERE state =
|
|
451
|
+
// 'SENDING'), which Prisma cannot express, as marketplace_acceptances_cancellation_waiting_idx.
|
|
452
|
+
@@map("marketplace_status_updates")
|
|
453
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
-- @domains: marketplace
|
|
2
|
+
-- @12-apps/marketplace: following and informing a pedido's status (FUT-4653).
|
|
3
|
+
-- Additive and replay-safe, like the engine's earlier migrations: one new
|
|
4
|
+
-- column with a default, one new table with its CHECKs and indexes. No foreign
|
|
5
|
+
-- key into a host table, and nothing the previous release reads is changed.
|
|
6
|
+
--
|
|
7
|
+
-- `follow_status` is the connection's switch for the INBOUND move: ON for every
|
|
8
|
+
-- existing connection and every new one.
|
|
9
|
+
--
|
|
10
|
+
-- `marketplace_status_updates` holds one row per (order, step): the claim that
|
|
11
|
+
-- keeps a step from ever being sent twice, the marker an inbound echo is
|
|
12
|
+
-- recognised by, and the note of what the marketplace itself announced.
|
|
13
|
+
-- `claim_key` says WHICH run holds a SENDING claim, so two jobs for one step
|
|
14
|
+
-- never both call the marketplace.
|
|
15
|
+
|
|
16
|
+
ALTER TABLE "marketplace_integrations" ADD COLUMN IF NOT EXISTS "follow_status" BOOLEAN NOT NULL DEFAULT true;
|
|
17
|
+
|
|
18
|
+
CREATE TABLE IF NOT EXISTS "marketplace_status_updates" (
|
|
19
|
+
"id" TEXT NOT NULL,
|
|
20
|
+
"client_id" TEXT NOT NULL,
|
|
21
|
+
"order_id" TEXT NOT NULL,
|
|
22
|
+
"provider" TEXT NOT NULL,
|
|
23
|
+
"step" TEXT NOT NULL,
|
|
24
|
+
"source" TEXT NOT NULL,
|
|
25
|
+
"state" TEXT NOT NULL,
|
|
26
|
+
"claim_key" TEXT NOT NULL,
|
|
27
|
+
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
28
|
+
"updated_at" TIMESTAMP(3) NOT NULL,
|
|
29
|
+
|
|
30
|
+
CONSTRAINT "marketplace_status_updates_pkey" PRIMARY KEY ("id")
|
|
31
|
+
);
|
|
32
|
+
|
|
33
|
+
DO $$ BEGIN
|
|
34
|
+
ALTER TABLE "marketplace_status_updates" ADD CONSTRAINT "marketplace_status_updates_provider_shape"
|
|
35
|
+
CHECK ("provider" ~ '^[A-Z][A-Z0-9_]*$');
|
|
36
|
+
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
|
37
|
+
|
|
38
|
+
DO $$ BEGIN
|
|
39
|
+
ALTER TABLE "marketplace_status_updates" ADD CONSTRAINT "marketplace_status_updates_step_check"
|
|
40
|
+
CHECK ("step" IN ('READY', 'DISPATCHED', 'HANDED_OVER', 'CONCLUDED'));
|
|
41
|
+
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
|
42
|
+
|
|
43
|
+
DO $$ BEGIN
|
|
44
|
+
ALTER TABLE "marketplace_status_updates" ADD CONSTRAINT "marketplace_status_updates_source_check"
|
|
45
|
+
CHECK ("source" IN ('STORE', 'MARKETPLACE'));
|
|
46
|
+
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
|
47
|
+
|
|
48
|
+
DO $$ BEGIN
|
|
49
|
+
ALTER TABLE "marketplace_status_updates" ADD CONSTRAINT "marketplace_status_updates_state_check"
|
|
50
|
+
CHECK ("state" IN ('SENDING', 'SENT', 'FAILED', 'NOTED'));
|
|
51
|
+
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
|
52
|
+
|
|
53
|
+
-- One row per step of an order: the claim's unique.
|
|
54
|
+
CREATE UNIQUE INDEX IF NOT EXISTS "marketplace_status_updates_order_id_step_key"
|
|
55
|
+
ON "marketplace_status_updates"("order_id", "step");
|
|
56
|
+
|
|
57
|
+
-- The outbound sweep reads only rows still SENDING.
|
|
58
|
+
CREATE INDEX IF NOT EXISTS "marketplace_status_updates_state_updated_at_idx"
|
|
59
|
+
ON "marketplace_status_updates"("updated_at")
|
|
60
|
+
WHERE "state" = 'SENDING';
|
package/src/99food/index.ts
CHANGED
|
@@ -9,7 +9,9 @@ import { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryEvent, verifyOpenDelive
|
|
|
9
9
|
import {
|
|
10
10
|
openDeliveryConfirm,
|
|
11
11
|
openDeliveryFetchOrder,
|
|
12
|
+
openDeliveryInformStatus,
|
|
12
13
|
openDeliveryRequestCancellation,
|
|
14
|
+
openDeliveryStatusSupported,
|
|
13
15
|
type NinetyNineFoodApiBaseUrls,
|
|
14
16
|
} from "./outbound";
|
|
15
17
|
import { openDeliveryAvailability } from "./pause";
|
|
@@ -109,6 +111,8 @@ export function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig)
|
|
|
109
111
|
// `OrderConfirmed.preparationTime`, in minutes.
|
|
110
112
|
confirmTakesPreparationTime: true,
|
|
111
113
|
cancellationAnswerWindowMs: NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS,
|
|
114
|
+
// Open Delivery's readyForPickup, dispatch and delivered / pickedUp (see `./outbound.ts`).
|
|
115
|
+
statusSteps: ["READY", "DISPATCHED", "HANDED_OVER"],
|
|
112
116
|
},
|
|
113
117
|
normalize: normalizeOpenDeliveryEvent,
|
|
114
118
|
readSignature: (header) => header("x-app-signature"),
|
|
@@ -119,6 +123,8 @@ export function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig)
|
|
|
119
123
|
fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx, bases, order, normalizeOptions),
|
|
120
124
|
confirm: (ctx, order, input) => openDeliveryConfirm(ctx, bases, order, input),
|
|
121
125
|
requestCancellation: (ctx, order, input) => openDeliveryRequestCancellation(ctx, bases, order, input),
|
|
126
|
+
statusSupported: openDeliveryStatusSupported,
|
|
127
|
+
informStatus: (ctx, order, facts) => openDeliveryInformStatus(ctx, bases, order, facts),
|
|
122
128
|
appLink: () => config.portalUrl,
|
|
123
129
|
...(config.pauseByStoreSwitch ? { availability: openDeliveryAvailability(bases) } : {}),
|
|
124
130
|
};
|