@12-apps/marketplace 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/ADOPTING.md +44 -9
  2. package/README.md +149 -4
  3. package/dist/99food/en-US.d.ts +19 -0
  4. package/dist/99food/en-US.js +23 -0
  5. package/dist/99food/en-US.js.map +1 -0
  6. package/dist/99food/index.d.ts +116 -0
  7. package/dist/99food/index.js +361 -0
  8. package/dist/99food/index.js.map +1 -0
  9. package/dist/99food/pt-BR.d.ts +23 -0
  10. package/dist/99food/pt-BR.js +23 -0
  11. package/dist/99food/pt-BR.js.map +1 -0
  12. package/dist/{adapter-CgCAYBSJ.d.ts → adapter-_iuSxvVD.d.ts} +41 -1
  13. package/dist/{chunk-OEKTWUQH.js → chunk-24RQZPSV.js} +1 -1
  14. package/dist/chunk-24RQZPSV.js.map +1 -0
  15. package/dist/chunk-BD7DS3XM.js +78 -0
  16. package/dist/chunk-BD7DS3XM.js.map +1 -0
  17. package/dist/{chunk-BEMTRJYM.js → chunk-CRYFYDQ2.js} +28 -4
  18. package/dist/{chunk-BEMTRJYM.js.map → chunk-CRYFYDQ2.js.map} +1 -1
  19. package/dist/chunk-D2X7TOR6.js +1240 -0
  20. package/dist/chunk-D2X7TOR6.js.map +1 -0
  21. package/dist/{engine-DDE0mnTu.d.ts → engine-D-a4mttc.d.ts} +117 -17
  22. package/dist/hono/index.d.ts +2 -2
  23. package/dist/hono/index.js +2 -2
  24. package/dist/ifood/index.d.ts +10 -12
  25. package/dist/ifood/index.js +19 -61
  26. package/dist/ifood/index.js.map +1 -1
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.js +113 -497
  29. package/dist/index.js.map +1 -1
  30. package/dist/manifest/server.d.ts +3 -2
  31. package/dist/manifest/server.js +2 -2
  32. package/dist/rappi/en-US.d.ts +14 -0
  33. package/dist/rappi/en-US.js +18 -0
  34. package/dist/rappi/en-US.js.map +1 -0
  35. package/dist/rappi/index.d.ts +190 -0
  36. package/dist/rappi/index.js +353 -0
  37. package/dist/rappi/index.js.map +1 -0
  38. package/dist/rappi/pt-BR.d.ts +18 -0
  39. package/dist/rappi/pt-BR.js +18 -0
  40. package/dist/rappi/pt-BR.js.map +1 -0
  41. package/dist/server/index.d.ts +12 -5
  42. package/dist/server/index.js +4 -2
  43. package/package.json +26 -2
  44. package/prisma/marketplace.prisma +12 -1
  45. package/prisma/migrations/20261112120000_marketplace_cancellation_failure/migration.sql +21 -0
  46. package/src/99food/copy.ts +36 -0
  47. package/src/99food/en-US.ts +19 -0
  48. package/src/99food/index.ts +121 -0
  49. package/src/99food/normalize.ts +263 -0
  50. package/src/99food/outbound.ts +220 -0
  51. package/src/99food/pt-BR.ts +23 -0
  52. package/src/core/acceptance.ts +30 -14
  53. package/src/core/adapter.ts +23 -1
  54. package/src/core/cancellation-outcome.ts +92 -0
  55. package/src/core/cancellation.ts +46 -15
  56. package/src/core/decisions.ts +94 -19
  57. package/src/core/engine.ts +8 -0
  58. package/src/core/fetch-order.ts +253 -0
  59. package/src/core/inbox.ts +8 -2
  60. package/src/core/ingest.ts +10 -2
  61. package/src/core/integration.ts +30 -1
  62. package/src/core/order-fetch-marks.ts +63 -0
  63. package/src/core/outbound-sweep.ts +87 -8
  64. package/src/core/outbound.ts +103 -7
  65. package/src/core/payload-read.ts +101 -0
  66. package/src/core/pipeline.ts +64 -15
  67. package/src/core/ports.ts +32 -0
  68. package/src/core/state.ts +6 -1
  69. package/src/core/types.ts +14 -0
  70. package/src/ifood/index.ts +9 -0
  71. package/src/ifood/normalize.ts +15 -88
  72. package/src/index.ts +10 -1
  73. package/src/rappi/copy.ts +39 -0
  74. package/src/rappi/en-US.ts +14 -0
  75. package/src/rappi/index.ts +155 -0
  76. package/src/rappi/normalize.ts +314 -0
  77. package/src/rappi/outbound.ts +182 -0
  78. package/src/rappi/pt-BR.ts +18 -0
  79. package/src/server/index.ts +1 -0
  80. package/src/server/jobs.ts +38 -4
  81. package/dist/chunk-6OODIO3E.js +0 -395
  82. package/dist/chunk-6OODIO3E.js.map +0 -1
  83. package/dist/chunk-OEKTWUQH.js.map +0 -1
@@ -1,5 +1,3 @@
1
- import { createHmac, timingSafeEqual } from "node:crypto";
2
-
3
1
  import type {
4
2
  MarketplaceDeliveredBy,
5
3
  MarketplaceOrderType,
@@ -9,6 +7,14 @@ import type {
9
7
  NormalizedMarketplaceOrder,
10
8
  NormalizedOrderLine,
11
9
  } from "../core/types";
10
+ import {
11
+ asString,
12
+ firstCents,
13
+ firstDate,
14
+ firstString,
15
+ pick,
16
+ verifyHmacSha256Hex,
17
+ } from "../core/payload-read";
12
18
 
13
19
  /**
14
20
  * The iFood adapter's INBOUND half: one delivery → a {@link NormalizedEvent}.
@@ -30,99 +36,20 @@ const ORDER_CANCELLED = new Set(["CAN", "CANCELLED", "ORDER_CANCELLED"]);
30
36
  /** iFood refused the store's own cancellation request. */
31
37
  const CANCELLATION_REQUEST_FAILED = new Set(["CARF", "CANCELLATION_REQUEST_FAILED"]);
32
38
 
33
- /** Read a nested value without asserting the shape of anything on the way. */
34
- function pick(source: unknown, ...path: string[]): unknown {
35
- let cursor: unknown = source;
36
- for (const key of path) {
37
- if (typeof cursor !== "object" || cursor === null) return undefined;
38
- cursor = (cursor as Record<string, unknown>)[key];
39
- }
40
- return cursor;
41
- }
42
-
43
- function asString(value: unknown): string | null {
44
- if (typeof value === "string" && value.trim() !== "") return value.trim();
45
- if (typeof value === "number" && Number.isFinite(value)) return String(value);
46
- return null;
47
- }
48
-
49
- /**
50
- * The first of several candidate paths that yields a string.
51
- *
52
- * iFood states the same fact under different keys depending on which API
53
- * version delivered the order, so nearly every read here is a fallback chain.
54
- * Expressed as data rather than as `??` so a chain can grow by one entry
55
- * instead of by one branch.
56
- */
57
- function firstString(source: unknown, paths: string[][]): string | null {
58
- for (const path of paths) {
59
- const found = asString(pick(source, ...path));
60
- if (found !== null) return found;
61
- }
62
- return null;
63
- }
64
-
65
- /** {@link firstString} for money. Same reason, same shape. */
66
- function firstCents(source: unknown, paths: string[][]): number | null {
67
- for (const path of paths) {
68
- const found = toCents(pick(source, ...path));
69
- if (found !== null) return found;
70
- }
71
- return null;
72
- }
73
-
74
39
  /**
75
- * iFood states money in DECIMAL reais (`12.9`), this app in integer cents.
76
- *
77
- * Rounded rather than truncated: `Math.trunc(12.9 * 100)` is 1289 on IEEE-754,
78
- * so truncation loses a cent on ordinary prices — per line, on every order,
79
- * always in the store's disfavour.
80
- */
81
- function toCents(value: unknown): number | null {
82
- const numeric = typeof value === "string" ? Number(value) : value;
83
- if (typeof numeric !== "number" || !Number.isFinite(numeric)) return null;
84
- return Math.round(numeric * 100);
85
- }
86
-
87
- function toDate(value: unknown): Date | null {
88
- const raw = asString(value);
89
- if (!raw) return null;
90
- const parsed = new Date(raw);
91
- return Number.isNaN(parsed.getTime()) ? null : parsed;
92
- }
93
-
94
- /** {@link firstString} for timestamps. */
95
- function firstDate(source: unknown, paths: string[][]): Date | null {
96
- for (const path of paths) {
97
- const found = toDate(pick(source, ...path));
98
- if (found !== null) return found;
99
- }
100
- return null;
101
- }
102
-
103
- /**
104
- * Verify a delivery against the merchant's webhook secret.
105
- *
106
- * Unsigned deliveries are refused whenever a secret is CONFIGURED. A store that
107
- * has not set one yet is accepted — iFood's own onboarding issues the secret
108
- * after the merchant is certified, so refusing before then would make the
109
- * connection untestable — and that state is visible on the integration screen
110
- * rather than silent.
111
- *
112
- * Compared in constant time over bytes: an early-exit `===` on a hex digest
113
- * leaks the prefix a forger already got right, one request at a time.
40
+ * Verify a delivery against the merchant's webhook secret: iFood signs the raw
41
+ * body with HMAC-SHA256, hex. The rule (an unset secret accepts; a set one
42
+ * refuses an unsigned delivery; constant-time compare) is the engine's
43
+ * {@link verifyHmacSha256Hex}. iFood's own onboarding issues the secret after
44
+ * the merchant is certified, so refusing before then would make the
45
+ * connection untestable.
114
46
  */
115
47
  export function verifyIfoodSignature(
116
48
  rawBody: string,
117
49
  signature: string | null,
118
50
  webhookSecret: string | null,
119
51
  ): boolean {
120
- if (!webhookSecret) return true;
121
- if (!signature) return false;
122
- const expected = createHmac("sha256", webhookSecret).update(rawBody, "utf8").digest("hex");
123
- const given = Buffer.from(signature.trim().toLowerCase().replace(/^sha256=/u, ""), "utf8");
124
- const mine = Buffer.from(expected, "utf8");
125
- return given.length === mine.length && timingSafeEqual(given, mine);
52
+ return verifyHmacSha256Hex(rawBody, signature, webhookSecret);
126
53
  }
127
54
 
128
55
  /** The buyer, as much of them as iFood discloses on the order. */
package/src/index.ts CHANGED
@@ -12,7 +12,8 @@
12
12
  * So: the engine (this entry) holds the inbox, the pipeline, ingest, the
13
13
  * acceptance clock and its sweep, the SKU map, the integration settings and
14
14
  * the outbound engine, and knows no marketplace by name. Each marketplace is
15
- * an adapter at its own subpath (`@12-apps/marketplace/ifood`), registered at
15
+ * an adapter at its own subpath (`@12-apps/marketplace/ifood`,
16
+ * `@12-apps/marketplace/99food`, `@12-apps/marketplace/rappi`), registered at
16
17
  * mount. The wiring manifests are at `./manifest` and `./manifest/server`.
17
18
  *
18
19
  * Everything the engine needs from its host is a required port with no
@@ -27,6 +28,7 @@ export {
27
28
  type AdapterTokenCache,
28
29
  type CancellationReason,
29
30
  type CancellationRequestInput,
31
+ type FetchOrderResult,
30
32
  type MarketplaceAdapter,
31
33
  type MarketplaceCapabilities,
32
34
  type MarketplaceCredentials,
@@ -47,6 +49,7 @@ export type {
47
49
  MarketplaceAdmission,
48
50
  MarketplaceAdmissionRequest,
49
51
  MarketplaceAdmissionResult,
52
+ CancellationFailureReason,
50
53
  MarketplaceAuditEntry,
51
54
  MarketplaceAuditPort,
52
55
  MarketplaceClockPort,
@@ -119,4 +122,10 @@ export {
119
122
  type OutboundJobPayload,
120
123
  } from "./core/outbound-queue";
121
124
  export type { DeliveryOutcome } from "./core/pipeline";
125
+ export {
126
+ FetchOrderRetryError,
127
+ MARKETPLACE_FETCH_ORDER_JOB,
128
+ type FetchOrderJobPayload,
129
+ type FetchOrderOutcome,
130
+ } from "./core/fetch-order";
122
131
  export type { MarketplaceOrderState } from "./core/state";
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The words the Rappi adapter needs from its host, and nothing else.
3
+ *
4
+ * Required and defaultless, like every copy port in this repo: the adapter
5
+ * ships no language of its own. Two packs sit beside it (`./pt-BR`,
6
+ * `./en-US`); a host passes one by hand, or its own.
7
+ */
8
+
9
+ /**
10
+ * The `cancel_type` values a store may send with `PUT orders/{orderId}/reject`,
11
+ * verbatim from Rappi's public API reference (dev-portal.rappi.com,
12
+ * api-reference/orders, "PUT orders/{orderId}/reject"). Pinned by the portal,
13
+ * not estimated.
14
+ */
15
+ export const RAPPI_REASON_CODES = [
16
+ "ITEM_OUT_OF_STOCK",
17
+ "ITEM_NOT_FOUND",
18
+ "ITEM_WRONG_PRICE",
19
+ "ORDER_MISSING_INFORMATION",
20
+ "ORDER_MISSING_ADDRESS_INFORMATION",
21
+ "ORDER_TOTAL_INCORRECT",
22
+ ] as const;
23
+
24
+ export type RappiReasonCode = (typeof RAPPI_REASON_CODES)[number];
25
+
26
+ /**
27
+ * The codes with which the portal REQUIRES the offending items ("If the value
28
+ * informed for cancel_type is one of the following: ITEM_WRONG_PRICE,
29
+ * ITEM_NOT_FOUND, ITEM_OUT_OF_STOCK. It would be required to include the
30
+ * offending items").
31
+ */
32
+ export const RAPPI_ITEM_REASON_CODES: readonly RappiReasonCode[] = ["ITEM_OUT_OF_STOCK", "ITEM_NOT_FOUND", "ITEM_WRONG_PRICE"];
33
+
34
+ export interface RappiAdapterCopy {
35
+ /** One label per reason code. Sent as the reject's required `reason` text. */
36
+ reasonLabels: Readonly<Record<RappiReasonCode, string>>;
37
+ /** What an address with no street number says instead. */
38
+ missingStreetNumber: string;
39
+ }
@@ -0,0 +1,14 @@
1
+ import type { RappiAdapterCopy } from "./copy";
2
+
3
+ /** The Rappi adapter's en-US pack: the same reasons, in English. */
4
+ export const RAPPI_ADAPTER_COPY_EN_US = {
5
+ reasonLabels: {
6
+ ITEM_OUT_OF_STOCK: "Item unavailable",
7
+ ITEM_NOT_FOUND: "Item not found",
8
+ ITEM_WRONG_PRICE: "Wrong item price",
9
+ ORDER_MISSING_INFORMATION: "Order information missing",
10
+ ORDER_MISSING_ADDRESS_INFORMATION: "Address information missing",
11
+ ORDER_TOTAL_INCORRECT: "Order total incorrect",
12
+ },
13
+ missingStreetNumber: "no number",
14
+ } as const satisfies RappiAdapterCopy;
@@ -0,0 +1,155 @@
1
+ import type { CancellationReason, MarketplaceAdapter } from "../core/adapter";
2
+ import { RAPPI_ITEM_REASON_CODES, RAPPI_REASON_CODES, type RappiAdapterCopy, type RappiReasonCode } from "./copy";
3
+ import {
4
+ RAPPI_PROVIDER,
5
+ RAPPI_SIGNATURE_HEADER,
6
+ normalizeRappiEvent,
7
+ verifyRappiSignature,
8
+ type RappiAmountUnit,
9
+ } from "./normalize";
10
+ import { rappiReject, rappiTake, type RappiBaseUrls } from "./outbound";
11
+
12
+ /**
13
+ * `@12-apps/marketplace/rappi` — Rappi, as one adapter on the engine.
14
+ *
15
+ * Built from Rappi's public developer portal (dev-portal.rappi.com), owner's
16
+ * decision 2026-11-11: the NEW_ORDER webhook, take, reject and the M2M client
17
+ * credentials. Everything Rappi is under this folder; the engine reaches it
18
+ * only through the {@link MarketplaceAdapter} port, and registering it is the
19
+ * whole cost:
20
+ *
21
+ * ```ts
22
+ * import { createRappiAdapter } from "@12-apps/marketplace/rappi";
23
+ * import { RAPPI_ADAPTER_COPY_PT_BR } from "@12-apps/marketplace/rappi/pt-BR";
24
+ *
25
+ * createMarketplaceEngine({
26
+ * …ports,
27
+ * adapters: [
28
+ * createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR }),
29
+ * createRappiAdapter({ copy: RAPPI_ADAPTER_COPY_PT_BR, apiBaseUrl, tokenUrl, portalUrl, amountUnit }),
30
+ * ],
31
+ * });
32
+ * ```
33
+ *
34
+ * Its webhooks (NEW_ORDER and ORDER_EVENT_CANCEL, each registered with Rappi
35
+ * as its own subscription, all pointing at the same URL) are the engine's one
36
+ * route, `POST /webhooks/marketplace/:tenantSlug/RAPPI`.
37
+ *
38
+ * What Rappi CANNOT do through its public API is stated, never inferred: a
39
+ * reject is only accepted while the order is SENT (before it is taken), and
40
+ * there is no public endpoint to cancel a taken order. So
41
+ * `cancelAfterAccept` is false — the store's cancel of a taken Rappi order is
42
+ * FAILED at once and opens Rappi's portal (the app link) — and the reject's
43
+ * answer is the outcome (`asyncCancellationOutcome: false`).
44
+ */
45
+
46
+ export { RAPPI_PROVIDER, RAPPI_SIGNATURE_HEADER } from "./normalize";
47
+
48
+ /**
49
+ * How long a reject may wait to be delivered. From the portal: an order in
50
+ * SENT has "a time limit of 6 minutes to take or reject the order, otherwise
51
+ * it will transition to TIMEOUT status", so a reject that has not reached Rappi
52
+ * six minutes after it was asked can no longer be one. The request is failed
53
+ * as TIMEOUT and a person finishes it on Rappi.
54
+ *
55
+ * ESTIMATED: Rappi counts its 6 minutes from the order's arrival, the engine
56
+ * counts this window from the request. A reject asked late in Rappi's window
57
+ * may still be sent after Rappi's TIMEOUT; Rappi then answers 400, which reads
58
+ * as a refusal (FAILED, the portal link): slower than needed, never wrong.
59
+ */
60
+ export const RAPPI_CANCELLATION_ANSWER_WINDOW_MS = 6 * 60_000;
61
+
62
+ /** The one reason that means "an item is unavailable". */
63
+ const ITEM_UNAVAILABLE: RappiReasonCode = "ITEM_OUT_OF_STOCK";
64
+
65
+ const AMOUNT_UNITS: readonly RappiAmountUnit[] = ["MINOR_UNITS", "MAJOR_UNITS"];
66
+
67
+ export interface RappiAdapterConfig {
68
+ /** The words the adapter needs: reason labels and the missing-number text. Required. */
69
+ copy: RappiAdapterCopy;
70
+ /**
71
+ * The orders API's base per environment, https: the portal's
72
+ * `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api` (its
73
+ * samples use the `https://microservices.dev.rappi.com` domain). The adapter
74
+ * appends `/orders/{orderId}/take/…` and `/orders/{orderId}/reject`.
75
+ * Required and defaultless: Rappi's account manager confirms the partner's
76
+ * country domain.
77
+ */
78
+ apiBaseUrl: RappiBaseUrls;
79
+ /**
80
+ * The token endpoint per environment, https, whole: the portal's
81
+ * `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`
82
+ * ("for integrations services"). Required and defaultless.
83
+ */
84
+ tokenUrl: RappiBaseUrls;
85
+ /** Where "open it on Rappi" goes: the partner portal (Rappi names no per-order link). Required; https only. */
86
+ portalUrl: string;
87
+ /** How Rappi states money for this host's country (see {@link RappiAmountUnit}). Required: ESTIMATED for Brazil. */
88
+ amountUnit: RappiAmountUnit;
89
+ }
90
+
91
+ function assertHttps(name: string, url: string): void {
92
+ let parsed: URL;
93
+ try {
94
+ parsed = new URL(url);
95
+ } catch {
96
+ throw new Error(`@12-apps/marketplace/rappi: ${name} is not a URL.`);
97
+ }
98
+ if (parsed.protocol !== "https:") throw new Error(`@12-apps/marketplace/rappi: ${name} must be https.`);
99
+ }
100
+
101
+ function assertConfig(config: RappiAdapterConfig): void {
102
+ for (const env of ["SANDBOX", "PRODUCTION"] as const) {
103
+ assertHttps(`apiBaseUrl.${env}`, config.apiBaseUrl[env]);
104
+ assertHttps(`tokenUrl.${env}`, config.tokenUrl[env]);
105
+ }
106
+ assertHttps("portalUrl", config.portalUrl);
107
+ if (!AMOUNT_UNITS.includes(config.amountUnit)) {
108
+ throw new Error(`@12-apps/marketplace/rappi: amountUnit must be one of ${AMOUNT_UNITS.join(", ")}.`);
109
+ }
110
+ }
111
+
112
+ /** Build the Rappi adapter. Its reasons are static: a dialog never waits on Rappi. */
113
+ export function createRappiAdapter(config: RappiAdapterConfig): MarketplaceAdapter {
114
+ assertConfig(config);
115
+ const hosts = { api: { ...config.apiBaseUrl }, token: { ...config.tokenUrl } };
116
+ const reasons: readonly CancellationReason[] = RAPPI_REASON_CODES.map((code) => ({
117
+ code,
118
+ label: config.copy.reasonLabels[code],
119
+ itemUnavailable: code === ITEM_UNAVAILABLE,
120
+ needsItems: RAPPI_ITEM_REASON_CODES.includes(code),
121
+ }));
122
+ const normalizeOptions = { amountUnit: config.amountUnit, missingStreetNumber: config.copy.missingStreetNumber };
123
+ return {
124
+ provider: RAPPI_PROVIDER,
125
+ capabilities: {
126
+ apiConfirm: true,
127
+ apiCancel: true,
128
+ // Reject only from SENT; no public endpoint cancels a TAKEN order.
129
+ cancelAfterAccept: false,
130
+ // 200 is "Order successfully rejected": the answer is the outcome.
131
+ asyncCancellationOutcome: false,
132
+ perOrderAppLink: false,
133
+ // `take/{cookingTime}`, in minutes.
134
+ confirmTakesPreparationTime: true,
135
+ cancellationAnswerWindowMs: RAPPI_CANCELLATION_ANSWER_WINDOW_MS,
136
+ },
137
+ normalize: (payload) => normalizeRappiEvent(payload, normalizeOptions),
138
+ readSignature: (header) => header(RAPPI_SIGNATURE_HEADER),
139
+ verifySignature: verifyRappiSignature,
140
+ cancellationReasons: () => reasons,
141
+ confirm: (ctx, order, input) => rappiTake(ctx, hosts, order, input),
142
+ requestCancellation: (ctx, order, input) => rappiReject(ctx, hosts, order, input),
143
+ appLink: () => config.portalUrl,
144
+ };
145
+ }
146
+
147
+ export { RAPPI_ITEM_REASON_CODES, RAPPI_REASON_CODES, type RappiAdapterCopy, type RappiReasonCode } from "./copy";
148
+ export {
149
+ normalizeRappiEvent,
150
+ normalizeRappiOrder,
151
+ verifyRappiSignature,
152
+ type RappiAmountUnit,
153
+ type RappiNormalizeOptions,
154
+ } from "./normalize";
155
+ export type { RappiBaseUrls, RappiHosts } from "./outbound";