@12-apps/marketplace 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/ADOPTING.md +37 -7
  2. package/README.md +238 -4
  3. package/dist/99food/en-US.d.ts +19 -0
  4. package/dist/99food/en-US.js +23 -0
  5. package/dist/99food/en-US.js.map +1 -0
  6. package/dist/99food/index.d.ts +162 -0
  7. package/dist/99food/index.js +444 -0
  8. package/dist/99food/index.js.map +1 -0
  9. package/dist/99food/pt-BR.d.ts +23 -0
  10. package/dist/99food/pt-BR.js +23 -0
  11. package/dist/99food/pt-BR.js.map +1 -0
  12. package/dist/{adapter-BggtVFf9.d.ts → adapter-0l_EmuJA.d.ts} +206 -2
  13. package/dist/{chunk-NGNEL4HS.js → chunk-AYYBRQJV.js} +52 -4
  14. package/dist/chunk-AYYBRQJV.js.map +1 -0
  15. package/dist/chunk-BD7DS3XM.js +78 -0
  16. package/dist/chunk-BD7DS3XM.js.map +1 -0
  17. package/dist/chunk-M2V4RFMA.js +23 -0
  18. package/dist/chunk-M2V4RFMA.js.map +1 -0
  19. package/dist/{chunk-7BYVGNU5.js → chunk-RVBTARIY.js} +1 -1
  20. package/dist/chunk-RVBTARIY.js.map +1 -0
  21. package/dist/chunk-XUAFXNOH.js +1604 -0
  22. package/dist/chunk-XUAFXNOH.js.map +1 -0
  23. package/dist/{engine-KrgZ4pA4.d.ts → engine-CZsP8KWd.d.ts} +278 -2
  24. package/dist/hono/index.d.ts +2 -2
  25. package/dist/hono/index.js +2 -2
  26. package/dist/ifood/index.d.ts +16 -12
  27. package/dist/ifood/index.js +248 -121
  28. package/dist/ifood/index.js.map +1 -1
  29. package/dist/index.d.ts +30 -4
  30. package/dist/index.js +189 -346
  31. package/dist/index.js.map +1 -1
  32. package/dist/manifest/server.d.ts +4 -2
  33. package/dist/manifest/server.js +2 -2
  34. package/dist/rappi/en-US.d.ts +14 -0
  35. package/dist/rappi/en-US.js +18 -0
  36. package/dist/rappi/en-US.js.map +1 -0
  37. package/dist/rappi/index.d.ts +190 -0
  38. package/dist/rappi/index.js +359 -0
  39. package/dist/rappi/index.js.map +1 -0
  40. package/dist/rappi/pt-BR.d.ts +18 -0
  41. package/dist/rappi/pt-BR.js +18 -0
  42. package/dist/rappi/pt-BR.js.map +1 -0
  43. package/dist/server/index.d.ts +19 -8
  44. package/dist/server/index.js +4 -2
  45. package/package.json +26 -2
  46. package/prisma/marketplace.prisma +97 -2
  47. package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
  48. package/src/99food/catalogue.ts +117 -0
  49. package/src/99food/copy.ts +36 -0
  50. package/src/99food/en-US.ts +19 -0
  51. package/src/99food/index.ts +125 -0
  52. package/src/99food/normalize.ts +263 -0
  53. package/src/99food/outbound.ts +220 -0
  54. package/src/99food/pt-BR.ts +23 -0
  55. package/src/core/adapter.ts +27 -2
  56. package/src/core/catalogue-category.ts +119 -0
  57. package/src/core/catalogue-ids.ts +23 -0
  58. package/src/core/catalogue-job.ts +332 -0
  59. package/src/core/catalogue-port.ts +173 -0
  60. package/src/core/catalogue-store.ts +172 -0
  61. package/src/core/catalogue-sweep.ts +43 -0
  62. package/src/core/catalogue.ts +226 -0
  63. package/src/core/decisions.ts +16 -4
  64. package/src/core/engine.ts +54 -0
  65. package/src/core/fetch-order.ts +253 -0
  66. package/src/core/inbox.ts +8 -2
  67. package/src/core/ingest.ts +10 -2
  68. package/src/core/integration.ts +30 -1
  69. package/src/core/order-fetch-marks.ts +63 -0
  70. package/src/core/outbound-sweep.ts +7 -2
  71. package/src/core/outbound.ts +22 -2
  72. package/src/core/payload-read.ts +101 -0
  73. package/src/core/pipeline.ts +64 -15
  74. package/src/core/ports.ts +36 -0
  75. package/src/core/types.ts +14 -0
  76. package/src/ifood/catalogue.ts +273 -0
  77. package/src/ifood/index.ts +4 -0
  78. package/src/ifood/normalize.ts +15 -88
  79. package/src/ifood/outbound.ts +9 -6
  80. package/src/index.ts +49 -1
  81. package/src/rappi/copy.ts +39 -0
  82. package/src/rappi/en-US.ts +14 -0
  83. package/src/rappi/index.ts +161 -0
  84. package/src/rappi/normalize.ts +314 -0
  85. package/src/rappi/outbound.ts +182 -0
  86. package/src/rappi/pt-BR.ts +18 -0
  87. package/src/server/index.ts +1 -0
  88. package/src/server/jobs.ts +71 -8
  89. package/dist/chunk-7BYVGNU5.js.map +0 -1
  90. package/dist/chunk-DVIRN42O.js +0 -707
  91. package/dist/chunk-DVIRN42O.js.map +0 -1
  92. package/dist/chunk-NGNEL4HS.js.map +0 -1
@@ -0,0 +1,190 @@
1
+ import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAdapter } from '../adapter-0l_EmuJA.js';
2
+
3
+ /**
4
+ * The words the Rappi adapter needs from its host, and nothing else.
5
+ *
6
+ * Required and defaultless, like every copy port in this repo: the adapter
7
+ * ships no language of its own. Two packs sit beside it (`./pt-BR`,
8
+ * `./en-US`); a host passes one by hand, or its own.
9
+ */
10
+ /**
11
+ * The `cancel_type` values a store may send with `PUT orders/{orderId}/reject`,
12
+ * verbatim from Rappi's public API reference (dev-portal.rappi.com,
13
+ * api-reference/orders, "PUT orders/{orderId}/reject"). Pinned by the portal,
14
+ * not estimated.
15
+ */
16
+ declare const RAPPI_REASON_CODES: readonly ["ITEM_OUT_OF_STOCK", "ITEM_NOT_FOUND", "ITEM_WRONG_PRICE", "ORDER_MISSING_INFORMATION", "ORDER_MISSING_ADDRESS_INFORMATION", "ORDER_TOTAL_INCORRECT"];
17
+ type RappiReasonCode = (typeof RAPPI_REASON_CODES)[number];
18
+ /**
19
+ * The codes with which the portal REQUIRES the offending items ("If the value
20
+ * informed for cancel_type is one of the following: ITEM_WRONG_PRICE,
21
+ * ITEM_NOT_FOUND, ITEM_OUT_OF_STOCK. It would be required to include the
22
+ * offending items").
23
+ */
24
+ declare const RAPPI_ITEM_REASON_CODES: readonly RappiReasonCode[];
25
+ interface RappiAdapterCopy {
26
+ /** One label per reason code. Sent as the reject's required `reason` text. */
27
+ reasonLabels: Readonly<Record<RappiReasonCode, string>>;
28
+ /** What an address with no street number says instead. */
29
+ missingStreetNumber: string;
30
+ }
31
+
32
+ /**
33
+ * The Rappi adapter's INBOUND half, from Rappi's public developer portal
34
+ * (dev-portal.rappi.com: webhook-events, api-reference/orders), read
35
+ * 2026-11-13.
36
+ *
37
+ * Rappi registers one webhook URL PER EVENT, and its payloads do not name the
38
+ * event they are. So the event is read from the body's shape, as the portal
39
+ * documents each one:
40
+ *
41
+ * - `NEW_ORDER` is "the same information that we can get from the getOrders
42
+ * endpoint": one element of `GET orders`, an `order_detail` (with `items`,
43
+ * `totals`, `delivery_information`) beside `customer` and `store`.
44
+ * - `NEW_ORDER_SCHEDULED` is that shape plus `"action": "scheduled"`, every
45
+ * price zero (the real order follows as `NEW_ORDER`); recorded, ignored.
46
+ * - `NEW_ORDER_SCHEDULED_CANCELLED` is `"action": "cancelled"` with an
47
+ * `order_detail.order_id`: an order never released to the store; ignored.
48
+ * - `ORDER_EVENT_CANCEL` is `{ event, order_id, store_id }`, `event` naming the
49
+ * cancellation (`canceled_with_charge`).
50
+ * - `ORDER_OTHER_EVENT` is `{ event, order_id, store_id, event_time,
51
+ * additional_information }`; recorded, ignored.
52
+ *
53
+ * ESTIMATED, until the Rappi sandbox confirms it: telling ORDER_EVENT_CANCEL
54
+ * from ORDER_OTHER_EVENT. The portal shows one example of each and names no
55
+ * list of `event` values, so a payload is a cancellation only when it has
56
+ * neither `event_time` nor `additional_information` AND its `event` names a
57
+ * cancellation (`cancel` in it, which `canceled_with_charge` has). Anything
58
+ * else is recorded and IGNORED: a missed cancellation is visible in the inbox,
59
+ * a false one would cancel a live order.
60
+ *
61
+ * Rappi payloads carry no event id, so the inbox key is derived from the
62
+ * order and the event, deterministic so a redelivery collides on the inbox's
63
+ * unique index.
64
+ */
65
+ /** The provider id Rappi is registered under. Uppercase: the column's CHECK holds that shape. */
66
+ declare const RAPPI_PROVIDER = "RAPPI";
67
+ /** The header Rappi signs every webhook in (the portal: "Rappi-Signature"; headers are case-insensitive). */
68
+ declare const RAPPI_SIGNATURE_HEADER = "rappi-signature";
69
+ /**
70
+ * How Rappi states money. The portal types every amount as an `integer` and
71
+ * names no unit (its examples are Colombian and Mexican pesos). Whether a
72
+ * Brazilian store's `price: 2890` is R$ 28,90 or R$ 2.890 is not public, so
73
+ * it is the adapter's REQUIRED config: `MINOR_UNITS` (cents) or `MAJOR_UNITS`
74
+ * (whole reais). ESTIMATED until the sandbox shows a Brazilian order.
75
+ */
76
+ type RappiAmountUnit = "MINOR_UNITS" | "MAJOR_UNITS";
77
+ interface RappiNormalizeOptions {
78
+ amountUnit: RappiAmountUnit;
79
+ missingStreetNumber: string;
80
+ }
81
+ /**
82
+ * Verify a delivery, as the portal's "Validating Your Signature" says:
83
+ * `Rappi-Signature: t=<timestamp>,sign=<signature>`; the signed payload is
84
+ * the timestamp, `.`, and the raw body as it arrived; HMAC-SHA256 keyed by
85
+ * the webhook's secret. The digest's encoding is not stated: the portal's
86
+ * example `sign` is 64 hex characters, so it is read as lowercase hex
87
+ * (ESTIMATED). Compared in constant time.
88
+ *
89
+ * The secret is REQUIRED: Rappi gives it when the webhook is registered, so a
90
+ * connection without one refuses every delivery (an unsigned
91
+ * ORDER_EVENT_CANCEL for a known order id would otherwise cancel it). No
92
+ * timestamp tolerance is applied: the portal states none, and a replayed
93
+ * delivery is a duplicate in the inbox.
94
+ */
95
+ declare function verifyRappiSignature(rawBody: string, header: string | null, webhookSecret: string | null): boolean;
96
+ /**
97
+ * Normalize one webhook delivery. Null only when it names no order (PING,
98
+ * MENU_*, STORE_CONNECTIVITY, STORE_PROVISIONING_STATUS): nothing to key on.
99
+ */
100
+ declare function normalizeRappiEvent(payload: unknown, options: RappiNormalizeOptions): NormalizedEvent | null;
101
+ /**
102
+ * Normalize one getOrders element (the NEW_ORDER body). Null when it carries
103
+ * no order id or no line.
104
+ *
105
+ * The total is `totals.total_order`, "the total amount that the restaurant
106
+ * receives" (with tip and delivery fee when the store delivers): the figure
107
+ * the store's receipt is reconciled against. Rappi states no commission, so
108
+ * `commissionCents` is null ("did not say"), never 0. The merchant the order
109
+ * names is Rappi's store id (`store.internal_id`), the id every other event
110
+ * carries as `store_id`; the engine refuses it for another connection.
111
+ */
112
+ declare function normalizeRappiOrder(payload: unknown, options: RappiNormalizeOptions): NormalizedMarketplaceOrder | null;
113
+
114
+ /**
115
+ * The Rappi adapter's OUTBOUND half, from Rappi's public developer portal
116
+ * (dev-portal.rappi.com: authentication-process, api-reference/orders), read
117
+ * 2026-11-13: the token, take and reject. The job that calls these, its
118
+ * retries and what a failure shows are the engine's.
119
+ *
120
+ * - Token: `POST https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`,
121
+ * JSON `{ client_id, client_secret }`; "the system responds with your
122
+ * access_token", valid "1 week"; sent as `x-authorization: Bearer <token>`.
123
+ * - Take: `PUT https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api/orders/{orderId}/take/{cookingTime}`,
124
+ * the cooking time optional ("leave this field empty to keep the default");
125
+ * 200 taken, 400 "Invalid state transition", 404 not found.
126
+ * - Reject: `PUT …/orders/{orderId}/reject` with `{ reason, cancel_type,
127
+ * items_skus }`, only from SENT; 200 rejected, 400, 404.
128
+ *
129
+ * WHERE is not public per partner: the portal names its domains by country
130
+ * (`{COUNTRY_DOMAIN}`, and a "new" one for the token), and Rappi's account
131
+ * manager opens the sandbox. So the orders API's base and the token URL, per
132
+ * environment, are the adapter's REQUIRED config, never a guessed default. Tests never reach
133
+ * Rappi: the HTTP client is the host's port, answered by a fake.
134
+ */
135
+ /** One https URL per environment. */
136
+ type RappiBaseUrls = Readonly<Record<"SANDBOX" | "PRODUCTION", string>>;
137
+ /**
138
+ * The two places the adapter calls, both host config (the portal's paths
139
+ * carry the origin application's own noun, so they are the host's to state):
140
+ * - `api`: the orders API's base, the portal's
141
+ * `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api`, to
142
+ * which the adapter appends `/orders/{orderId}/…`;
143
+ * - `token`: the token endpoint itself, the portal's
144
+ * `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`.
145
+ */
146
+ interface RappiHosts {
147
+ api: RappiBaseUrls;
148
+ token: RappiBaseUrls;
149
+ }
150
+
151
+ /**
152
+ * How long a reject may wait to be delivered. From the portal: an order in
153
+ * SENT has "a time limit of 6 minutes to take or reject the order, otherwise
154
+ * it will transition to TIMEOUT status", so a reject that has not reached Rappi
155
+ * six minutes after it was asked can no longer be one. The request is failed
156
+ * as TIMEOUT and a person finishes it on Rappi.
157
+ *
158
+ * ESTIMATED: Rappi counts its 6 minutes from the order's arrival, the engine
159
+ * counts this window from the request. A reject asked late in Rappi's window
160
+ * may still be sent after Rappi's TIMEOUT; Rappi then answers 400, which reads
161
+ * as a refusal (FAILED, the portal link): slower than needed, never wrong.
162
+ */
163
+ declare const RAPPI_CANCELLATION_ANSWER_WINDOW_MS: number;
164
+ interface RappiAdapterConfig {
165
+ /** The words the adapter needs: reason labels and the missing-number text. Required. */
166
+ copy: RappiAdapterCopy;
167
+ /**
168
+ * The orders API's base per environment, https: the portal's
169
+ * `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api` (its
170
+ * samples use the `https://microservices.dev.rappi.com` domain). The adapter
171
+ * appends `/orders/{orderId}/take/…` and `/orders/{orderId}/reject`.
172
+ * Required and defaultless: Rappi's account manager confirms the partner's
173
+ * country domain.
174
+ */
175
+ apiBaseUrl: RappiBaseUrls;
176
+ /**
177
+ * The token endpoint per environment, https, whole: the portal's
178
+ * `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`
179
+ * ("for integrations services"). Required and defaultless.
180
+ */
181
+ tokenUrl: RappiBaseUrls;
182
+ /** Where "open it on Rappi" goes: the partner portal (Rappi names no per-order link). Required; https only. */
183
+ portalUrl: string;
184
+ /** How Rappi states money for this host's country (see {@link RappiAmountUnit}). Required: ESTIMATED for Brazil. */
185
+ amountUnit: RappiAmountUnit;
186
+ }
187
+ /** Build the Rappi adapter. Its reasons are static: a dialog never waits on Rappi. */
188
+ declare function createRappiAdapter(config: RappiAdapterConfig): MarketplaceAdapter;
189
+
190
+ export { RAPPI_CANCELLATION_ANSWER_WINDOW_MS, RAPPI_ITEM_REASON_CODES, RAPPI_PROVIDER, RAPPI_REASON_CODES, RAPPI_SIGNATURE_HEADER, type RappiAdapterConfig, type RappiAdapterCopy, type RappiAmountUnit, type RappiBaseUrls, type RappiHosts, type RappiNormalizeOptions, type RappiReasonCode, createRappiAdapter, normalizeRappiEvent, normalizeRappiOrder, verifyRappiSignature };
@@ -0,0 +1,359 @@
1
+ import {
2
+ asString,
3
+ firstDate,
4
+ firstString,
5
+ pick,
6
+ verifyHmacSha256Hex
7
+ } from "../chunk-BD7DS3XM.js";
8
+ import {
9
+ answered,
10
+ outboundResultOf
11
+ } from "../chunk-RVBTARIY.js";
12
+ import {
13
+ __name
14
+ } from "../chunk-7QVYU63E.js";
15
+
16
+ // src/rappi/copy.ts
17
+ var RAPPI_REASON_CODES = [
18
+ "ITEM_OUT_OF_STOCK",
19
+ "ITEM_NOT_FOUND",
20
+ "ITEM_WRONG_PRICE",
21
+ "ORDER_MISSING_INFORMATION",
22
+ "ORDER_MISSING_ADDRESS_INFORMATION",
23
+ "ORDER_TOTAL_INCORRECT"
24
+ ];
25
+ var RAPPI_ITEM_REASON_CODES = ["ITEM_OUT_OF_STOCK", "ITEM_NOT_FOUND", "ITEM_WRONG_PRICE"];
26
+
27
+ // src/rappi/normalize.ts
28
+ var RAPPI_PROVIDER = "RAPPI";
29
+ var RAPPI_SIGNATURE_HEADER = "rappi-signature";
30
+ function verifyRappiSignature(rawBody, header, webhookSecret) {
31
+ if (!webhookSecret || !header) return false;
32
+ const parts = signatureParts(header);
33
+ if (parts.t === null || parts.sign === null) return false;
34
+ return verifyHmacSha256Hex(`${parts.t}.${rawBody}`, parts.sign, webhookSecret);
35
+ }
36
+ __name(verifyRappiSignature, "verifyRappiSignature");
37
+ function signatureParts(header) {
38
+ const found = { t: null, sign: null };
39
+ for (const element of header.split(",")) {
40
+ const at = element.indexOf("=");
41
+ if (at < 0) continue;
42
+ const key = element.slice(0, at).trim().toLowerCase();
43
+ const value = element.slice(at + 1).trim();
44
+ if (value === "") continue;
45
+ if (key === "t") found.t = value;
46
+ if (key === "sign") found.sign = value;
47
+ }
48
+ return found;
49
+ }
50
+ __name(signatureParts, "signatureParts");
51
+ function storeIdOf(payload) {
52
+ return firstString(payload, [["store", "internal_id"], ["order_detail", "store", "internal_id"], ["order_detail", "store_id"], ["store_id"]]);
53
+ }
54
+ __name(storeIdOf, "storeIdOf");
55
+ function eventOf(orderId, eventType, payload, extra = {}) {
56
+ return {
57
+ provider: RAPPI_PROVIDER,
58
+ eventId: `${orderId}:${eventType}`,
59
+ eventType,
60
+ externalMerchantId: storeIdOf(payload),
61
+ externalOrderId: orderId,
62
+ order: null,
63
+ cancelled: false,
64
+ cancellationOutcome: null,
65
+ ...extra
66
+ };
67
+ }
68
+ __name(eventOf, "eventOf");
69
+ function orderDetailEvent(payload, options) {
70
+ const orderId = firstString(payload, [["order_detail", "order_id"]]);
71
+ if (!orderId) return null;
72
+ const action = firstString(payload, [["action"]])?.toLowerCase() ?? null;
73
+ if (action === "scheduled") return eventOf(orderId, "NEW_ORDER_SCHEDULED", payload);
74
+ if (action === "cancelled") return eventOf(orderId, "NEW_ORDER_SCHEDULED_CANCELLED", payload);
75
+ return eventOf(orderId, "NEW_ORDER", payload, { order: normalizeRappiOrder(payload, options) });
76
+ }
77
+ __name(orderDetailEvent, "orderDetailEvent");
78
+ function namesCancellation(event) {
79
+ return event.toLowerCase().includes("cancel");
80
+ }
81
+ __name(namesCancellation, "namesCancellation");
82
+ function orderEvent(payload) {
83
+ const orderId = firstString(payload, [["order_id"]]);
84
+ if (!orderId) return null;
85
+ const event = firstString(payload, [["event"]]) ?? "UNKNOWN";
86
+ const other = pick(payload, "event_time") !== void 0 || pick(payload, "additional_information") !== void 0;
87
+ const cancelled = !other && namesCancellation(event);
88
+ const eventType = cancelled ? "ORDER_EVENT_CANCEL" : "ORDER_OTHER_EVENT";
89
+ const at = asString(pick(payload, "event_time"));
90
+ return eventOf(orderId, eventType, payload, {
91
+ eventId: [orderId, eventType, event, ...at ? [at] : []].join(":"),
92
+ cancelled,
93
+ cancellationOutcome: cancelled ? "CONFIRMED" : null
94
+ });
95
+ }
96
+ __name(orderEvent, "orderEvent");
97
+ function normalizeRappiEvent(payload, options) {
98
+ const detail = pick(payload, "order_detail");
99
+ if (typeof detail === "object" && detail !== null) return orderDetailEvent(payload, options);
100
+ return orderEvent(payload);
101
+ }
102
+ __name(normalizeRappiEvent, "normalizeRappiEvent");
103
+ function amountCents(value, unit) {
104
+ const numeric = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
105
+ if (typeof numeric !== "number" || !Number.isFinite(numeric)) return null;
106
+ return Math.round(unit === "MAJOR_UNITS" ? numeric * 100 : numeric);
107
+ }
108
+ __name(amountCents, "amountCents");
109
+ function countOf(source) {
110
+ const stated = Number(pick(source, "quantity") ?? 1);
111
+ return Number.isFinite(stated) && stated > 0 ? stated : 1;
112
+ }
113
+ __name(countOf, "countOf");
114
+ function arrayAt(source, ...path) {
115
+ const found = pick(source, ...path);
116
+ return Array.isArray(found) ? found : [];
117
+ }
118
+ __name(arrayAt, "arrayAt");
119
+ function unitCents(item, unit) {
120
+ const base = amountCents(pick(item, "price"), unit) ?? 0;
121
+ return arrayAt(item, "subitems").reduce(
122
+ (sum, sub) => sum + (amountCents(pick(sub, "price"), unit) ?? 0) * countOf(sub),
123
+ base
124
+ );
125
+ }
126
+ __name(unitCents, "unitCents");
127
+ function lineNote(item) {
128
+ const subitems = arrayAt(item, "subitems").map((sub) => {
129
+ const name = asString(pick(sub, "name"));
130
+ const quantity = countOf(sub);
131
+ return name && quantity > 1 ? `${quantity}x ${name}` : name;
132
+ }).filter((name) => name !== null);
133
+ const rawComments = pick(item, "comments");
134
+ const comments = (Array.isArray(rawComments) ? rawComments : [rawComments]).map(asString).filter((comment) => comment !== null);
135
+ const note = [subitems.join(", "), ...comments].filter((part) => part !== "").join(" \xB7 ");
136
+ return note === "" ? null : note;
137
+ }
138
+ __name(lineNote, "lineNote");
139
+ function readLines(item, unit) {
140
+ const name = firstString(item, [["name"]]);
141
+ const sku = firstString(item, [["sku"], ["id"]]) ?? name;
142
+ if (!sku) return [];
143
+ const quantity = countOf(item);
144
+ const each = unitCents(item, unit);
145
+ const row = Number.isInteger(quantity) ? { quantity, unitPriceCents: each } : { quantity: 1, unitPriceCents: Math.round(each * quantity) };
146
+ return [{ externalSku: sku, name: name ?? sku, ...row, note: lineNote(item) }];
147
+ }
148
+ __name(readLines, "readLines");
149
+ function readMethod(detail) {
150
+ const method = firstString(detail, [["delivery_method"]])?.toLowerCase();
151
+ if (method === "delivery") return { orderType: "DELIVERY", deliveredBy: "MARKETPLACE" };
152
+ if (method === "marketplace") return { orderType: "DELIVERY", deliveredBy: "MERCHANT" };
153
+ if (method === "pickup") return { orderType: "TAKEOUT", deliveredBy: null };
154
+ return { orderType: null, deliveredBy: null };
155
+ }
156
+ __name(readMethod, "readMethod");
157
+ function readAddress(detail, missingStreetNumber) {
158
+ const raw = pick(detail, "delivery_information");
159
+ const street = firstString(raw, [["street_name"], ["complete_address"]]);
160
+ if (street === null) return null;
161
+ return {
162
+ street,
163
+ number: firstString(raw, [["street_number"]]) ?? missingStreetNumber,
164
+ neighborhood: firstString(raw, [["neighborhood"]]) ?? "",
165
+ complement: firstString(raw, [["complement"]]),
166
+ reference: firstString(raw, [["description"]]),
167
+ postalCode: firstString(raw, [["postal_code"]])?.replace(/\D/g, "") || null,
168
+ city: firstString(raw, [["city"]]),
169
+ state: firstString(raw, [["federal_unit"]])
170
+ };
171
+ }
172
+ __name(readAddress, "readAddress");
173
+ function readBuyer(payload) {
174
+ const customer = pick(payload, "customer") ?? pick(payload, "order_detail", "customer");
175
+ const name = [firstString(customer, [["first_name"]]), firstString(customer, [["last_name"]])].filter((part) => part !== null).join(" ");
176
+ return { externalId: null, name: name === "" ? null : name, phone: firstString(customer, [["phone_number"]]) };
177
+ }
178
+ __name(readBuyer, "readBuyer");
179
+ function normalizeRappiOrder(payload, options) {
180
+ const detail = pick(payload, "order_detail");
181
+ const externalOrderId = firstString(detail, [["order_id"]]);
182
+ const lines = arrayAt(detail, "items").flatMap((item) => readLines(item, options.amountUnit));
183
+ if (!externalOrderId || lines.length === 0) return null;
184
+ const method = readMethod(detail);
185
+ return {
186
+ provider: RAPPI_PROVIDER,
187
+ externalOrderId,
188
+ // Rappi's order id is the number its app and courier show.
189
+ externalDisplayId: externalOrderId,
190
+ externalMerchantId: storeIdOf(payload),
191
+ buyer: readBuyer(payload),
192
+ lines,
193
+ totalCents: amountCents(pick(detail, "totals", "total_order"), options.amountUnit) ?? lines.reduce((sum, line) => sum + line.unitPriceCents * line.quantity, 0),
194
+ commissionCents: null,
195
+ // Rappi states no delivery promise on the order.
196
+ deliveryDueAt: null,
197
+ placedAt: firstDate(detail, [["created_at"]]) ?? /* @__PURE__ */ new Date(),
198
+ orderType: method.orderType,
199
+ deliveredBy: method.deliveredBy,
200
+ deliveryAddress: method.orderType === "TAKEOUT" ? null : readAddress(detail, options.missingStreetNumber)
201
+ };
202
+ }
203
+ __name(normalizeRappiOrder, "normalizeRappiOrder");
204
+
205
+ // src/rappi/outbound.ts
206
+ var TOKEN_MARGIN_MS = 6e4;
207
+ var DEFAULT_TOKEN_SECONDS = 7 * 24 * 60 * 60;
208
+ function trimmed(base) {
209
+ let end = base.length;
210
+ while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;
211
+ return base.slice(0, end);
212
+ }
213
+ __name(trimmed, "trimmed");
214
+ var tokenKey = /* @__PURE__ */ __name((ctx) => `${RAPPI_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`, "tokenKey");
215
+ function tokenOf(body) {
216
+ try {
217
+ const parsed = JSON.parse(body);
218
+ if (typeof parsed.access_token !== "string" || parsed.access_token === "") return null;
219
+ const expires = typeof parsed.expires_in === "number" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;
220
+ return { token: parsed.access_token, expiresInSeconds: expires };
221
+ } catch {
222
+ return null;
223
+ }
224
+ }
225
+ __name(tokenOf, "tokenOf");
226
+ async function bearer(ctx, hosts) {
227
+ const cached = ctx.tokens.get(tokenKey(ctx));
228
+ if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
229
+ const response = await ctx.http({
230
+ method: "POST",
231
+ url: hosts.token[ctx.environment],
232
+ headers: { "Content-Type": "application/json" },
233
+ body: JSON.stringify({ client_id: ctx.credentials.clientId, client_secret: ctx.credentials.clientSecret })
234
+ });
235
+ if (response.status < 200 || response.status >= 300) {
236
+ const result = outboundResultOf(response);
237
+ return result.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : result;
238
+ }
239
+ const token = tokenOf(response.body);
240
+ if (!token) return { kind: "retry", reason: "Rappi answered the token request without a token" };
241
+ ctx.tokens.set(tokenKey(ctx), { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1e3 });
242
+ return { token: token.token };
243
+ }
244
+ __name(bearer, "bearer");
245
+ async function putOrder(ctx, hosts, request) {
246
+ const auth = await bearer(ctx, hosts);
247
+ if (!("token" in auth)) return auth;
248
+ const response = await ctx.http({
249
+ method: "PUT",
250
+ url: `${trimmed(hosts.api[ctx.environment])}/orders/${encodeURIComponent(request.externalOrderId)}/${request.action}`,
251
+ headers: {
252
+ "x-authorization": `Bearer ${auth.token}`,
253
+ ...request.body === void 0 ? {} : { "Content-Type": "application/json" }
254
+ },
255
+ ...request.body === void 0 ? {} : { body: JSON.stringify(request.body) }
256
+ });
257
+ if (response.status !== 401) return response;
258
+ ctx.tokens.delete(tokenKey(ctx));
259
+ return { kind: "retry", reason: "Rappi refused the token" };
260
+ }
261
+ __name(putOrder, "putOrder");
262
+ function rappiTake(ctx, hosts, order, input) {
263
+ const minutes = input.preparationMinutes === null ? "" : String(Math.round(input.preparationMinutes));
264
+ return answered(async () => {
265
+ const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: `take/${minutes}` });
266
+ return "kind" in response ? response : outboundResultOf(response);
267
+ });
268
+ }
269
+ __name(rappiTake, "rappiTake");
270
+ function rappiReject(ctx, hosts, order, input) {
271
+ const body = {
272
+ reason: input.text === "" ? input.reason.label : input.text,
273
+ cancel_type: input.reason.code,
274
+ ...input.offendingSkus.length > 0 ? { items_skus: [...input.offendingSkus] } : {}
275
+ };
276
+ return answered(async () => {
277
+ const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: "reject", body });
278
+ return "kind" in response ? response : outboundResultOf(response);
279
+ });
280
+ }
281
+ __name(rappiReject, "rappiReject");
282
+
283
+ // src/rappi/index.ts
284
+ var RAPPI_CANCELLATION_ANSWER_WINDOW_MS = 6 * 6e4;
285
+ var ITEM_UNAVAILABLE = "ITEM_OUT_OF_STOCK";
286
+ var AMOUNT_UNITS = ["MINOR_UNITS", "MAJOR_UNITS"];
287
+ function assertHttps(name, url) {
288
+ let parsed;
289
+ try {
290
+ parsed = new URL(url);
291
+ } catch {
292
+ throw new Error(`@12-apps/marketplace/rappi: ${name} is not a URL.`);
293
+ }
294
+ if (parsed.protocol !== "https:") throw new Error(`@12-apps/marketplace/rappi: ${name} must be https.`);
295
+ }
296
+ __name(assertHttps, "assertHttps");
297
+ function assertConfig(config) {
298
+ for (const env of ["SANDBOX", "PRODUCTION"]) {
299
+ assertHttps(`apiBaseUrl.${env}`, config.apiBaseUrl[env]);
300
+ assertHttps(`tokenUrl.${env}`, config.tokenUrl[env]);
301
+ }
302
+ assertHttps("portalUrl", config.portalUrl);
303
+ if (!AMOUNT_UNITS.includes(config.amountUnit)) {
304
+ throw new Error(`@12-apps/marketplace/rappi: amountUnit must be one of ${AMOUNT_UNITS.join(", ")}.`);
305
+ }
306
+ }
307
+ __name(assertConfig, "assertConfig");
308
+ function createRappiAdapter(config) {
309
+ assertConfig(config);
310
+ const hosts = { api: { ...config.apiBaseUrl }, token: { ...config.tokenUrl } };
311
+ const reasons = RAPPI_REASON_CODES.map((code) => ({
312
+ code,
313
+ label: config.copy.reasonLabels[code],
314
+ itemUnavailable: code === ITEM_UNAVAILABLE,
315
+ needsItems: RAPPI_ITEM_REASON_CODES.includes(code)
316
+ }));
317
+ const normalizeOptions = { amountUnit: config.amountUnit, missingStreetNumber: config.copy.missingStreetNumber };
318
+ return {
319
+ provider: RAPPI_PROVIDER,
320
+ // No `catalogue` (FUT-4768). Rappi's public menu write, `POST …/menu`,
321
+ // replaces the store's WHOLE menu, goes to an approval, and ignores every
322
+ // further menu while one is in approval: a per-product switch on it would
323
+ // wipe what the store keeps on Rappi's portal and report "in the catalogue"
324
+ // for a menu Rappi may have dropped. Its availability endpoints only turn
325
+ // items Rappi already has on and off. See the README, "Catalogue publishing".
326
+ capabilities: {
327
+ apiConfirm: true,
328
+ apiCancel: true,
329
+ // Reject only from SENT; no public endpoint cancels a TAKEN order.
330
+ cancelAfterAccept: false,
331
+ // 200 is "Order successfully rejected": the answer is the outcome.
332
+ asyncCancellationOutcome: false,
333
+ perOrderAppLink: false,
334
+ // `take/{cookingTime}`, in minutes.
335
+ confirmTakesPreparationTime: true,
336
+ cancellationAnswerWindowMs: RAPPI_CANCELLATION_ANSWER_WINDOW_MS
337
+ },
338
+ normalize: /* @__PURE__ */ __name((payload) => normalizeRappiEvent(payload, normalizeOptions), "normalize"),
339
+ readSignature: /* @__PURE__ */ __name((header) => header(RAPPI_SIGNATURE_HEADER), "readSignature"),
340
+ verifySignature: verifyRappiSignature,
341
+ cancellationReasons: /* @__PURE__ */ __name(() => reasons, "cancellationReasons"),
342
+ confirm: /* @__PURE__ */ __name((ctx, order, input) => rappiTake(ctx, hosts, order, input), "confirm"),
343
+ requestCancellation: /* @__PURE__ */ __name((ctx, order, input) => rappiReject(ctx, hosts, order, input), "requestCancellation"),
344
+ appLink: /* @__PURE__ */ __name(() => config.portalUrl, "appLink")
345
+ };
346
+ }
347
+ __name(createRappiAdapter, "createRappiAdapter");
348
+ export {
349
+ RAPPI_CANCELLATION_ANSWER_WINDOW_MS,
350
+ RAPPI_ITEM_REASON_CODES,
351
+ RAPPI_PROVIDER,
352
+ RAPPI_REASON_CODES,
353
+ RAPPI_SIGNATURE_HEADER,
354
+ createRappiAdapter,
355
+ normalizeRappiEvent,
356
+ normalizeRappiOrder,
357
+ verifyRappiSignature
358
+ };
359
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/rappi/copy.ts","../../src/rappi/normalize.ts","../../src/rappi/outbound.ts","../../src/rappi/index.ts"],"sourcesContent":["/**\n * The words the Rappi adapter needs from its host, and nothing else.\n *\n * Required and defaultless, like every copy port in this repo: the adapter\n * ships no language of its own. Two packs sit beside it (`./pt-BR`,\n * `./en-US`); a host passes one by hand, or its own.\n */\n\n/**\n * The `cancel_type` values a store may send with `PUT orders/{orderId}/reject`,\n * verbatim from Rappi's public API reference (dev-portal.rappi.com,\n * api-reference/orders, \"PUT orders/{orderId}/reject\"). Pinned by the portal,\n * not estimated.\n */\nexport const RAPPI_REASON_CODES = [\n \"ITEM_OUT_OF_STOCK\",\n \"ITEM_NOT_FOUND\",\n \"ITEM_WRONG_PRICE\",\n \"ORDER_MISSING_INFORMATION\",\n \"ORDER_MISSING_ADDRESS_INFORMATION\",\n \"ORDER_TOTAL_INCORRECT\",\n] as const;\n\nexport type RappiReasonCode = (typeof RAPPI_REASON_CODES)[number];\n\n/**\n * The codes with which the portal REQUIRES the offending items (\"If the value\n * informed for cancel_type is one of the following: ITEM_WRONG_PRICE,\n * ITEM_NOT_FOUND, ITEM_OUT_OF_STOCK. It would be required to include the\n * offending items\").\n */\nexport const RAPPI_ITEM_REASON_CODES: readonly RappiReasonCode[] = [\"ITEM_OUT_OF_STOCK\", \"ITEM_NOT_FOUND\", \"ITEM_WRONG_PRICE\"];\n\nexport interface RappiAdapterCopy {\n /** One label per reason code. Sent as the reject's required `reason` text. */\n reasonLabels: Readonly<Record<RappiReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import { asString, firstDate, firstString, pick, verifyHmacSha256Hex } from \"../core/payload-read\";\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceOrderType,\n NormalizedAddress,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n NormalizedOrderLine,\n} from \"../core/types\";\n\n/**\n * The Rappi adapter's INBOUND half, from Rappi's public developer portal\n * (dev-portal.rappi.com: webhook-events, api-reference/orders), read\n * 2026-11-13.\n *\n * Rappi registers one webhook URL PER EVENT, and its payloads do not name the\n * event they are. So the event is read from the body's shape, as the portal\n * documents each one:\n *\n * - `NEW_ORDER` is \"the same information that we can get from the getOrders\n * endpoint\": one element of `GET orders`, an `order_detail` (with `items`,\n * `totals`, `delivery_information`) beside `customer` and `store`.\n * - `NEW_ORDER_SCHEDULED` is that shape plus `\"action\": \"scheduled\"`, every\n * price zero (the real order follows as `NEW_ORDER`); recorded, ignored.\n * - `NEW_ORDER_SCHEDULED_CANCELLED` is `\"action\": \"cancelled\"` with an\n * `order_detail.order_id`: an order never released to the store; ignored.\n * - `ORDER_EVENT_CANCEL` is `{ event, order_id, store_id }`, `event` naming the\n * cancellation (`canceled_with_charge`).\n * - `ORDER_OTHER_EVENT` is `{ event, order_id, store_id, event_time,\n * additional_information }`; recorded, ignored.\n *\n * ESTIMATED, until the Rappi sandbox confirms it: telling ORDER_EVENT_CANCEL\n * from ORDER_OTHER_EVENT. The portal shows one example of each and names no\n * list of `event` values, so a payload is a cancellation only when it has\n * neither `event_time` nor `additional_information` AND its `event` names a\n * cancellation (`cancel` in it, which `canceled_with_charge` has). Anything\n * else is recorded and IGNORED: a missed cancellation is visible in the inbox,\n * a false one would cancel a live order.\n *\n * Rappi payloads carry no event id, so the inbox key is derived from the\n * order and the event, deterministic so a redelivery collides on the inbox's\n * unique index.\n */\n\n/** The provider id Rappi is registered under. Uppercase: the column's CHECK holds that shape. */\nexport const RAPPI_PROVIDER = \"RAPPI\";\n\n/** The header Rappi signs every webhook in (the portal: \"Rappi-Signature\"; headers are case-insensitive). */\nexport const RAPPI_SIGNATURE_HEADER = \"rappi-signature\";\n\n/**\n * How Rappi states money. The portal types every amount as an `integer` and\n * names no unit (its examples are Colombian and Mexican pesos). Whether a\n * Brazilian store's `price: 2890` is R$ 28,90 or R$ 2.890 is not public, so\n * it is the adapter's REQUIRED config: `MINOR_UNITS` (cents) or `MAJOR_UNITS`\n * (whole reais). ESTIMATED until the sandbox shows a Brazilian order.\n */\nexport type RappiAmountUnit = \"MINOR_UNITS\" | \"MAJOR_UNITS\";\n\nexport interface RappiNormalizeOptions {\n amountUnit: RappiAmountUnit;\n missingStreetNumber: string;\n}\n\n/**\n * Verify a delivery, as the portal's \"Validating Your Signature\" says:\n * `Rappi-Signature: t=<timestamp>,sign=<signature>`; the signed payload is\n * the timestamp, `.`, and the raw body as it arrived; HMAC-SHA256 keyed by\n * the webhook's secret. The digest's encoding is not stated: the portal's\n * example `sign` is 64 hex characters, so it is read as lowercase hex\n * (ESTIMATED). Compared in constant time.\n *\n * The secret is REQUIRED: Rappi gives it when the webhook is registered, so a\n * connection without one refuses every delivery (an unsigned\n * ORDER_EVENT_CANCEL for a known order id would otherwise cancel it). No\n * timestamp tolerance is applied: the portal states none, and a replayed\n * delivery is a duplicate in the inbox.\n */\nexport function verifyRappiSignature(rawBody: string, header: string | null, webhookSecret: string | null): boolean {\n if (!webhookSecret || !header) return false;\n const parts = signatureParts(header);\n if (parts.t === null || parts.sign === null) return false;\n return verifyHmacSha256Hex(`${parts.t}.${rawBody}`, parts.sign, webhookSecret);\n}\n\n/** `t=…,sign=…` split on \",\" then on the first \"=\", as the portal describes. No regex. */\nfunction signatureParts(header: string): { t: string | null; sign: string | null } {\n const found: { t: string | null; sign: string | null } = { t: null, sign: null };\n for (const element of header.split(\",\")) {\n const at = element.indexOf(\"=\");\n if (at < 0) continue;\n const key = element.slice(0, at).trim().toLowerCase();\n const value = element.slice(at + 1).trim();\n if (value === \"\") continue;\n if (key === \"t\") found.t = value;\n if (key === \"sign\") found.sign = value;\n }\n return found;\n}\n\n/** Rappi's store id, from wherever this event shape keeps it. */\nfunction storeIdOf(payload: unknown): string | null {\n return firstString(payload, [[\"store\", \"internal_id\"], [\"order_detail\", \"store\", \"internal_id\"], [\"order_detail\", \"store_id\"], [\"store_id\"]]);\n}\n\n/** One event's frame; the order is filled by the caller. */\nfunction eventOf(\n orderId: string,\n eventType: string,\n payload: unknown,\n extra: Partial<NormalizedEvent> & { eventId?: string } = {},\n): NormalizedEvent {\n return {\n provider: RAPPI_PROVIDER,\n eventId: `${orderId}:${eventType}`,\n eventType,\n externalMerchantId: storeIdOf(payload),\n externalOrderId: orderId,\n order: null,\n cancelled: false,\n cancellationOutcome: null,\n ...extra,\n };\n}\n\n/** A shape with an `order_detail`: NEW_ORDER, or one of the scheduled notices. */\nfunction orderDetailEvent(payload: unknown, options: RappiNormalizeOptions): NormalizedEvent | null {\n const orderId = firstString(payload, [[\"order_detail\", \"order_id\"]]);\n if (!orderId) return null;\n const action = firstString(payload, [[\"action\"]])?.toLowerCase() ?? null;\n if (action === \"scheduled\") return eventOf(orderId, \"NEW_ORDER_SCHEDULED\", payload);\n if (action === \"cancelled\") return eventOf(orderId, \"NEW_ORDER_SCHEDULED_CANCELLED\", payload);\n return eventOf(orderId, \"NEW_ORDER\", payload, { order: normalizeRappiOrder(payload, options) });\n}\n\n/** Whether `event` names a cancellation: \"cancel\" in it, case-insensitive. ESTIMATED (see the file header). */\nfunction namesCancellation(event: string): boolean {\n return event.toLowerCase().includes(\"cancel\");\n}\n\n/** A shape with a top-level `order_id`: ORDER_EVENT_CANCEL or ORDER_OTHER_EVENT (and the tracking stream). */\nfunction orderEvent(payload: unknown): NormalizedEvent | null {\n const orderId = firstString(payload, [[\"order_id\"]]);\n if (!orderId) return null;\n const event = firstString(payload, [[\"event\"]]) ?? \"UNKNOWN\";\n const other = pick(payload, \"event_time\") !== undefined || pick(payload, \"additional_information\") !== undefined;\n const cancelled = !other && namesCancellation(event);\n const eventType = cancelled ? \"ORDER_EVENT_CANCEL\" : \"ORDER_OTHER_EVENT\";\n const at = asString(pick(payload, \"event_time\"));\n return eventOf(orderId, eventType, payload, {\n eventId: [orderId, eventType, event, ...(at ? [at] : [])].join(\":\"),\n cancelled,\n cancellationOutcome: cancelled ? \"CONFIRMED\" : null,\n });\n}\n\n/**\n * Normalize one webhook delivery. Null only when it names no order (PING,\n * MENU_*, STORE_CONNECTIVITY, STORE_PROVISIONING_STATUS): nothing to key on.\n */\nexport function normalizeRappiEvent(payload: unknown, options: RappiNormalizeOptions): NormalizedEvent | null {\n const detail = pick(payload, \"order_detail\");\n if (typeof detail === \"object\" && detail !== null) return orderDetailEvent(payload, options);\n return orderEvent(payload);\n}\n\n/** An amount as Rappi states it, in cents; null when absent or not a number. */\nfunction amountCents(value: unknown, unit: RappiAmountUnit): number | null {\n const numeric = typeof value === \"string\" && value.trim() !== \"\" ? Number(value) : value;\n if (typeof numeric !== \"number\" || !Number.isFinite(numeric)) return null;\n return Math.round(unit === \"MAJOR_UNITS\" ? numeric * 100 : numeric);\n}\n\n/** A stated count, 1 when absent or nonsense. */\nfunction countOf(source: unknown): number {\n const stated = Number(pick(source, \"quantity\") ?? 1);\n return Number.isFinite(stated) && stated > 0 ? stated : 1;\n}\n\nfunction arrayAt(source: unknown, ...path: string[]): unknown[] {\n const found = pick(source, ...path);\n return Array.isArray(found) ? found : [];\n}\n\n/**\n * One unit's price: the item's `price` (\"Unit price for the item without the\n * discount\") plus each subitem's `price × quantity`. ESTIMATED: the portal\n * does not say whether a subitem's quantity is per unit of its item or for the\n * whole line; it is read per unit (a topping on each salad of three).\n */\nfunction unitCents(item: unknown, unit: RappiAmountUnit): number {\n const base = amountCents(pick(item, \"price\"), unit) ?? 0;\n return arrayAt(item, \"subitems\").reduce<number>(\n (sum, sub) => sum + (amountCents(pick(sub, \"price\"), unit) ?? 0) * countOf(sub),\n base,\n );\n}\n\n/** The ticket's note: the subitems (a topping, a dressing) and the buyer's comments. */\nfunction lineNote(item: unknown): string | null {\n const subitems = arrayAt(item, \"subitems\")\n .map((sub) => {\n const name = asString(pick(sub, \"name\"));\n const quantity = countOf(sub);\n return name && quantity > 1 ? `${quantity}x ${name}` : name;\n })\n .filter((name): name is string => name !== null);\n // `comments` is typed an array and shown as a string in the same reference.\n const rawComments = pick(item, \"comments\");\n const comments = (Array.isArray(rawComments) ? rawComments : [rawComments])\n .map(asString)\n .filter((comment): comment is string => comment !== null);\n const note = [subitems.join(\", \"), ...comments].filter((part) => part !== \"\").join(\" · \");\n return note === \"\" ? null : note;\n}\n\n/**\n * One `order_detail.items[]` entry → its lines, which add up EXACTLY to the\n * item's total. A whole quantity is one row at the unit price (`unit × q` is\n * the total, nothing to divide); a fractional one (the portal types quantity\n * an integer, so this is defensive) is one row at its rounded total.\n *\n * The key is the item's `sku` (the store's own, \"the ally grants their own\n * SKU\"), then Rappi's `id`, then the name: an unmapped line is recoverable, a\n * dropped one is not.\n */\nfunction readLines(item: unknown, unit: RappiAmountUnit): NormalizedOrderLine[] {\n const name = firstString(item, [[\"name\"]]);\n const sku = firstString(item, [[\"sku\"], [\"id\"]]) ?? name;\n if (!sku) return [];\n const quantity = countOf(item);\n const each = unitCents(item, unit);\n const row = Number.isInteger(quantity)\n ? { quantity, unitPriceCents: each }\n : { quantity: 1, unitPriceCents: Math.round(each * quantity) };\n return [{ externalSku: sku, name: name ?? sku, ...row, note: lineNote(item) }];\n}\n\n/**\n * `delivery_method`: `delivery` (Rappi's courier), `marketplace` (the store's\n * own: the portal sends the customer's data \"only when delivery method is\n * marketplace\"), `pickup`.\n */\nfunction readMethod(detail: unknown): { orderType: MarketplaceOrderType | null; deliveredBy: MarketplaceDeliveredBy | null } {\n const method = firstString(detail, [[\"delivery_method\"]])?.toLowerCase();\n if (method === \"delivery\") return { orderType: \"DELIVERY\", deliveredBy: \"MARKETPLACE\" };\n if (method === \"marketplace\") return { orderType: \"DELIVERY\", deliveredBy: \"MERCHANT\" };\n if (method === \"pickup\") return { orderType: \"TAKEOUT\", deliveredBy: null };\n return { orderType: null, deliveredBy: null };\n}\n\n/** `order_detail.delivery_information`, the Brazilian fields included (`federal_unit`). */\nfunction readAddress(detail: unknown, missingStreetNumber: string): NormalizedAddress | null {\n const raw = pick(detail, \"delivery_information\");\n const street = firstString(raw, [[\"street_name\"], [\"complete_address\"]]);\n if (street === null) return null;\n return {\n street,\n number: firstString(raw, [[\"street_number\"]]) ?? missingStreetNumber,\n neighborhood: firstString(raw, [[\"neighborhood\"]]) ?? \"\",\n complement: firstString(raw, [[\"complement\"]]),\n reference: firstString(raw, [[\"description\"]]),\n postalCode: firstString(raw, [[\"postal_code\"]])?.replace(/\\D/g, \"\") || null,\n city: firstString(raw, [[\"city\"]]),\n state: firstString(raw, [[\"federal_unit\"]]),\n };\n}\n\n/** The buyer, top-level `customer` as the example has it, or under `order_detail` as the table names it. */\nfunction readBuyer(payload: unknown): NormalizedMarketplaceOrder[\"buyer\"] {\n const customer = pick(payload, \"customer\") ?? pick(payload, \"order_detail\", \"customer\");\n const name = [firstString(customer, [[\"first_name\"]]), firstString(customer, [[\"last_name\"]])]\n .filter((part): part is string => part !== null)\n .join(\" \");\n return { externalId: null, name: name === \"\" ? null : name, phone: firstString(customer, [[\"phone_number\"]]) };\n}\n\n/**\n * Normalize one getOrders element (the NEW_ORDER body). Null when it carries\n * no order id or no line.\n *\n * The total is `totals.total_order`, \"the total amount that the restaurant\n * receives\" (with tip and delivery fee when the store delivers): the figure\n * the store's receipt is reconciled against. Rappi states no commission, so\n * `commissionCents` is null (\"did not say\"), never 0. The merchant the order\n * names is Rappi's store id (`store.internal_id`), the id every other event\n * carries as `store_id`; the engine refuses it for another connection.\n */\nexport function normalizeRappiOrder(payload: unknown, options: RappiNormalizeOptions): NormalizedMarketplaceOrder | null {\n const detail = pick(payload, \"order_detail\");\n const externalOrderId = firstString(detail, [[\"order_id\"]]);\n const lines = arrayAt(detail, \"items\").flatMap((item) => readLines(item, options.amountUnit));\n if (!externalOrderId || lines.length === 0) return null;\n const method = readMethod(detail);\n return {\n provider: RAPPI_PROVIDER,\n externalOrderId,\n // Rappi's order id is the number its app and courier show.\n externalDisplayId: externalOrderId,\n externalMerchantId: storeIdOf(payload),\n buyer: readBuyer(payload),\n lines,\n totalCents:\n amountCents(pick(detail, \"totals\", \"total_order\"), options.amountUnit) ??\n lines.reduce((sum, line) => sum + line.unitPriceCents * line.quantity, 0),\n commissionCents: null,\n // Rappi states no delivery promise on the order.\n deliveryDueAt: null,\n placedAt: firstDate(detail, [[\"created_at\"]]) ?? new Date(),\n orderType: method.orderType,\n deliveredBy: method.deliveredBy,\n deliveryAddress: method.orderType === \"TAKEOUT\" ? null : readAddress(detail, options.missingStreetNumber),\n };\n}\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type MarketplaceHttpResponse,\n type OutboundOrderRef,\n type OutboundResult,\n} from \"../core/adapter\";\nimport { RAPPI_PROVIDER } from \"./normalize\";\n\n/**\n * The Rappi adapter's OUTBOUND half, from Rappi's public developer portal\n * (dev-portal.rappi.com: authentication-process, api-reference/orders), read\n * 2026-11-13: the token, take and reject. The job that calls these, its\n * retries and what a failure shows are the engine's.\n *\n * - Token: `POST https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`,\n * JSON `{ client_id, client_secret }`; \"the system responds with your\n * access_token\", valid \"1 week\"; sent as `x-authorization: Bearer <token>`.\n * - Take: `PUT https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api/orders/{orderId}/take/{cookingTime}`,\n * the cooking time optional (\"leave this field empty to keep the default\");\n * 200 taken, 400 \"Invalid state transition\", 404 not found.\n * - Reject: `PUT …/orders/{orderId}/reject` with `{ reason, cancel_type,\n * items_skus }`, only from SENT; 200 rejected, 400, 404.\n *\n * WHERE is not public per partner: the portal names its domains by country\n * (`{COUNTRY_DOMAIN}`, and a \"new\" one for the token), and Rappi's account\n * manager opens the sandbox. So the orders API's base and the token URL, per\n * environment, are the adapter's REQUIRED config, never a guessed default. Tests never reach\n * Rappi: the HTTP client is the host's port, answered by a fake.\n */\n\n/** One https URL per environment. */\nexport type RappiBaseUrls = Readonly<Record<\"SANDBOX\" | \"PRODUCTION\", string>>;\n\n/**\n * The two places the adapter calls, both host config (the portal's paths\n * carry the origin application's own noun, so they are the host's to state):\n * - `api`: the orders API's base, the portal's\n * `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api`, to\n * which the adapter appends `/orders/{orderId}/…`;\n * - `token`: the token endpoint itself, the portal's\n * `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`.\n */\nexport interface RappiHosts {\n api: RappiBaseUrls;\n token: RappiBaseUrls;\n}\n/** A token is renewed this long before it expires. */\nconst TOKEN_MARGIN_MS = 60_000;\n/**\n * The portal: \"Your access token has a validity of 1 week\". Used when the\n * answer states no `expires_in` (the answer's shape beyond `access_token` is\n * not shown: ESTIMATED).\n */\nconst DEFAULT_TOKEN_SECONDS = 7 * 24 * 60 * 60;\n\n/** A base URL with its trailing slashes cut, by a loop: a `/\\/+$/` regex backtracks polynomially on many slashes. */\nfunction trimmed(base: string): string {\n let end = base.length;\n while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;\n return base.slice(0, end);\n}\n\nconst tokenKey = (ctx: AdapterCallContext): string => `${RAPPI_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** The token answer, read defensively: `access_token`, and `expires_in` when present. */\nfunction tokenOf(body: string): { token: string; expiresInSeconds: number } | null {\n try {\n const parsed = JSON.parse(body) as { access_token?: unknown; expires_in?: unknown };\n if (typeof parsed.access_token !== \"string\" || parsed.access_token === \"\") return null;\n const expires =\n typeof parsed.expires_in === \"number\" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;\n return { token: parsed.access_token, expiresInSeconds: expires };\n } catch {\n return null;\n }\n}\n\n/**\n * A token from the per-process cache, or a fresh one from the token endpoint\n * (the M2M client credentials). Keyed by environment and client id; memory\n * only, written to no row or log.\n */\nasync function bearer(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n): Promise<{ token: string } | Exclude<OutboundResult, { kind: \"accepted\" }>> {\n const cached = ctx.tokens.get(tokenKey(ctx));\n if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };\n const response = await ctx.http({\n method: \"POST\",\n url: hosts.token[ctx.environment],\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ client_id: ctx.credentials.clientId, client_secret: ctx.credentials.clientSecret }),\n });\n if (response.status < 200 || response.status >= 300) {\n const result = outboundResultOf(response);\n return result.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected token answer\" } : result;\n }\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: \"Rappi answered the token request without a token\" };\n ctx.tokens.set(tokenKey(ctx), { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });\n return { token: token.token };\n}\n\n/** One authenticated PUT to an order's resource: the raw answer, or the result that ends it. */\nasync function putOrder(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n request: { externalOrderId: string; action: string; body?: unknown },\n): Promise<MarketplaceHttpResponse | Exclude<OutboundResult, { kind: \"accepted\" }>> {\n const auth = await bearer(ctx, hosts);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"PUT\",\n url: `${trimmed(hosts.api[ctx.environment])}/orders/${encodeURIComponent(request.externalOrderId)}/${request.action}`,\n headers: {\n \"x-authorization\": `Bearer ${auth.token}`,\n ...(request.body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),\n });\n // A 401 is a token that went stale under us: forget it, and the retry fetches another.\n if (response.status !== 401) return response;\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"Rappi refused the token\" };\n}\n\n/**\n * Take the order: `PUT …/orders/{orderId}/take/{cookingTime}`, the store's\n * preparation minutes as the cooking time, or `…/take/` to keep the order's\n * own (the portal: outside the order's range, Rappi uses the nearest bound).\n * The empty segment is how the portal's guide spells it\n * (`PUT /orders/{orderId}/take/`); ESTIMATED that Rappi's router serves it\n * (a 404 there would read as a refusal and show the portal link).\n * Every refused answer (400 \"Invalid state transition\", 404) is a refusal: the\n * store sees \"não confirmou\" and the app link.\n */\nexport function rappiTake(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n): Promise<OutboundResult> {\n const minutes = input.preparationMinutes === null ? \"\" : String(Math.round(input.preparationMinutes));\n return answered(async () => {\n const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: `take/${minutes}` });\n return \"kind\" in response ? response : outboundResultOf(response);\n });\n}\n\n/**\n * Reject the order: `PUT …/orders/{orderId}/reject` with `reason` (required\n * free text: the store's, else the reason's label), `cancel_type` (one of the\n * portal's six) and `items_skus` (the offending SKUs, required by the three\n * item reasons). The answer IS the outcome: 200 rejected (the engine stamps\n * CONFIRMED), any refusal FAILED with the app link.\n *\n * `items_skus` carries the engine's SKUs, which are the store's own `sku`\n * where the order states one. A line Rappi sent with no `sku` keys on Rappi's\n * item id, which the portal wants under `items_ids` instead; it is sent under\n * `items_skus` all the same (ESTIMATED: Rappi may refuse it, which reads as a\n * refusal and puts the app link in front of a person).\n */\nexport function rappiReject(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n): Promise<OutboundResult> {\n const body = {\n reason: input.text === \"\" ? input.reason.label : input.text,\n cancel_type: input.reason.code,\n ...(input.offendingSkus.length > 0 ? { items_skus: [...input.offendingSkus] } : {}),\n };\n return answered(async () => {\n const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: \"reject\", body });\n return \"kind\" in response ? response : outboundResultOf(response);\n });\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport { RAPPI_ITEM_REASON_CODES, RAPPI_REASON_CODES, type RappiAdapterCopy, type RappiReasonCode } from \"./copy\";\nimport {\n RAPPI_PROVIDER,\n RAPPI_SIGNATURE_HEADER,\n normalizeRappiEvent,\n verifyRappiSignature,\n type RappiAmountUnit,\n} from \"./normalize\";\nimport { rappiReject, rappiTake, type RappiBaseUrls } from \"./outbound\";\n\n/**\n * `@12-apps/marketplace/rappi` — Rappi, as one adapter on the engine.\n *\n * Built from Rappi's public developer portal (dev-portal.rappi.com), owner's\n * decision 2026-11-11: the NEW_ORDER webhook, take, reject and the M2M client\n * credentials. Everything Rappi is under this folder; the engine reaches it\n * only through the {@link MarketplaceAdapter} port, and registering it is the\n * whole cost:\n *\n * ```ts\n * import { createRappiAdapter } from \"@12-apps/marketplace/rappi\";\n * import { RAPPI_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/rappi/pt-BR\";\n *\n * createMarketplaceEngine({\n * …ports,\n * adapters: [\n * createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR }),\n * createRappiAdapter({ copy: RAPPI_ADAPTER_COPY_PT_BR, apiBaseUrl, tokenUrl, portalUrl, amountUnit }),\n * ],\n * });\n * ```\n *\n * Its webhooks (NEW_ORDER and ORDER_EVENT_CANCEL, each registered with Rappi\n * as its own subscription, all pointing at the same URL) are the engine's one\n * route, `POST /webhooks/marketplace/:tenantSlug/RAPPI`.\n *\n * What Rappi CANNOT do through its public API is stated, never inferred: a\n * reject is only accepted while the order is SENT (before it is taken), and\n * there is no public endpoint to cancel a taken order. So\n * `cancelAfterAccept` is false — the store's cancel of a taken Rappi order is\n * FAILED at once and opens Rappi's portal (the app link) — and the reject's\n * answer is the outcome (`asyncCancellationOutcome: false`).\n */\n\nexport { RAPPI_PROVIDER, RAPPI_SIGNATURE_HEADER } from \"./normalize\";\n\n/**\n * How long a reject may wait to be delivered. From the portal: an order in\n * SENT has \"a time limit of 6 minutes to take or reject the order, otherwise\n * it will transition to TIMEOUT status\", so a reject that has not reached Rappi\n * six minutes after it was asked can no longer be one. The request is failed\n * as TIMEOUT and a person finishes it on Rappi.\n *\n * ESTIMATED: Rappi counts its 6 minutes from the order's arrival, the engine\n * counts this window from the request. A reject asked late in Rappi's window\n * may still be sent after Rappi's TIMEOUT; Rappi then answers 400, which reads\n * as a refusal (FAILED, the portal link): slower than needed, never wrong.\n */\nexport const RAPPI_CANCELLATION_ANSWER_WINDOW_MS = 6 * 60_000;\n\n/** The one reason that means \"an item is unavailable\". */\nconst ITEM_UNAVAILABLE: RappiReasonCode = \"ITEM_OUT_OF_STOCK\";\n\nconst AMOUNT_UNITS: readonly RappiAmountUnit[] = [\"MINOR_UNITS\", \"MAJOR_UNITS\"];\n\nexport interface RappiAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: RappiAdapterCopy;\n /**\n * The orders API's base per environment, https: the portal's\n * `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api` (its\n * samples use the `https://microservices.dev.rappi.com` domain). The adapter\n * appends `/orders/{orderId}/take/…` and `/orders/{orderId}/reject`.\n * Required and defaultless: Rappi's account manager confirms the partner's\n * country domain.\n */\n apiBaseUrl: RappiBaseUrls;\n /**\n * The token endpoint per environment, https, whole: the portal's\n * `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`\n * (\"for integrations services\"). Required and defaultless.\n */\n tokenUrl: RappiBaseUrls;\n /** Where \"open it on Rappi\" goes: the partner portal (Rappi names no per-order link). Required; https only. */\n portalUrl: string;\n /** How Rappi states money for this host's country (see {@link RappiAmountUnit}). Required: ESTIMATED for Brazil. */\n amountUnit: RappiAmountUnit;\n}\n\nfunction assertHttps(name: string, url: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`@12-apps/marketplace/rappi: ${name} is not a URL.`);\n }\n if (parsed.protocol !== \"https:\") throw new Error(`@12-apps/marketplace/rappi: ${name} must be https.`);\n}\n\nfunction assertConfig(config: RappiAdapterConfig): void {\n for (const env of [\"SANDBOX\", \"PRODUCTION\"] as const) {\n assertHttps(`apiBaseUrl.${env}`, config.apiBaseUrl[env]);\n assertHttps(`tokenUrl.${env}`, config.tokenUrl[env]);\n }\n assertHttps(\"portalUrl\", config.portalUrl);\n if (!AMOUNT_UNITS.includes(config.amountUnit)) {\n throw new Error(`@12-apps/marketplace/rappi: amountUnit must be one of ${AMOUNT_UNITS.join(\", \")}.`);\n }\n}\n\n/** Build the Rappi adapter. Its reasons are static: a dialog never waits on Rappi. */\nexport function createRappiAdapter(config: RappiAdapterConfig): MarketplaceAdapter {\n assertConfig(config);\n const hosts = { api: { ...config.apiBaseUrl }, token: { ...config.tokenUrl } };\n const reasons: readonly CancellationReason[] = RAPPI_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === ITEM_UNAVAILABLE,\n needsItems: RAPPI_ITEM_REASON_CODES.includes(code),\n }));\n const normalizeOptions = { amountUnit: config.amountUnit, missingStreetNumber: config.copy.missingStreetNumber };\n return {\n provider: RAPPI_PROVIDER,\n // No `catalogue` (FUT-4768). Rappi's public menu write, `POST …/menu`,\n // replaces the store's WHOLE menu, goes to an approval, and ignores every\n // further menu while one is in approval: a per-product switch on it would\n // wipe what the store keeps on Rappi's portal and report \"in the catalogue\"\n // for a menu Rappi may have dropped. Its availability endpoints only turn\n // items Rappi already has on and off. See the README, \"Catalogue publishing\".\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n // Reject only from SENT; no public endpoint cancels a TAKEN order.\n cancelAfterAccept: false,\n // 200 is \"Order successfully rejected\": the answer is the outcome.\n asyncCancellationOutcome: false,\n perOrderAppLink: false,\n // `take/{cookingTime}`, in minutes.\n confirmTakesPreparationTime: true,\n cancellationAnswerWindowMs: RAPPI_CANCELLATION_ANSWER_WINDOW_MS,\n },\n normalize: (payload) => normalizeRappiEvent(payload, normalizeOptions),\n readSignature: (header) => header(RAPPI_SIGNATURE_HEADER),\n verifySignature: verifyRappiSignature,\n cancellationReasons: () => reasons,\n confirm: (ctx, order, input) => rappiTake(ctx, hosts, order, input),\n requestCancellation: (ctx, order, input) => rappiReject(ctx, hosts, order, input),\n appLink: () => config.portalUrl,\n };\n}\n\nexport { RAPPI_ITEM_REASON_CODES, RAPPI_REASON_CODES, type RappiAdapterCopy, type RappiReasonCode } from \"./copy\";\nexport {\n normalizeRappiEvent,\n normalizeRappiOrder,\n verifyRappiSignature,\n type RappiAmountUnit,\n type RappiNormalizeOptions,\n} from \"./normalize\";\nexport type { RappiBaseUrls, RappiHosts } from \"./outbound\";\n"],"mappings":";;;;;;;;;;;;;;;;AAcO,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAUO,IAAM,0BAAsD,CAAC,qBAAqB,kBAAkB,kBAAkB;;;ACctH,IAAM,iBAAiB;AAGvB,IAAM,yBAAyB;AA8B/B,SAAS,qBAAqB,SAAiB,QAAuB,eAAuC;AAClH,MAAI,CAAC,iBAAiB,CAAC,OAAQ,QAAO;AACtC,QAAM,QAAQ,eAAe,MAAM;AACnC,MAAI,MAAM,MAAM,QAAQ,MAAM,SAAS,KAAM,QAAO;AACpD,SAAO,oBAAoB,GAAG,MAAM,CAAC,IAAI,OAAO,IAAI,MAAM,MAAM,aAAa;AAC/E;AALgB;AAQhB,SAAS,eAAe,QAA2D;AACjF,QAAM,QAAmD,EAAE,GAAG,MAAM,MAAM,KAAK;AAC/E,aAAW,WAAW,OAAO,MAAM,GAAG,GAAG;AACvC,UAAM,KAAK,QAAQ,QAAQ,GAAG;AAC9B,QAAI,KAAK,EAAG;AACZ,UAAM,MAAM,QAAQ,MAAM,GAAG,EAAE,EAAE,KAAK,EAAE,YAAY;AACpD,UAAM,QAAQ,QAAQ,MAAM,KAAK,CAAC,EAAE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