@12-apps/marketplace 1.7.0 → 1.9.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 (96) hide show
  1. package/ADOPTING.md +17 -0
  2. package/README.md +153 -3
  3. package/dist/99food/index.d.ts +30 -52
  4. package/dist/99food/index.js +62 -391
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-DOjTak1H.d.ts → adapter-CYJzu1c9.d.ts} +45 -1
  7. package/dist/{chunk-YVUZHXUF.js → chunk-6N2HEV3U.js} +4 -4
  8. package/dist/chunk-6N2HEV3U.js.map +1 -0
  9. package/dist/{chunk-SJUKBCVO.js → chunk-BMCERPQX.js} +198 -12
  10. package/dist/chunk-BMCERPQX.js.map +1 -0
  11. package/dist/{chunk-L3DCOZUU.js → chunk-HEXLCTOG.js} +1 -1
  12. package/dist/chunk-HEXLCTOG.js.map +1 -0
  13. package/dist/{chunk-UYFYGGCS.js → chunk-NP4EYKPO.js} +3 -1
  14. package/dist/chunk-NP4EYKPO.js.map +1 -0
  15. package/dist/chunk-PYHNM47K.js +478 -0
  16. package/dist/chunk-PYHNM47K.js.map +1 -0
  17. package/dist/client-B4EQCRD_.d.ts +20 -0
  18. package/dist/{engine-DG1fg43Y.d.ts → engine-wmW-VuBL.d.ts} +107 -4
  19. package/dist/hono/index.d.ts +2 -2
  20. package/dist/hono/index.js +3 -3
  21. package/dist/ifood/index.d.ts +1 -1
  22. package/dist/ifood/index.js +29 -3
  23. package/dist/ifood/index.js.map +1 -1
  24. package/dist/index.d.ts +3 -3
  25. package/dist/index.js +104 -7
  26. package/dist/index.js.map +1 -1
  27. package/dist/keeta/en-US.d.ts +19 -0
  28. package/dist/keeta/en-US.js +23 -0
  29. package/dist/keeta/en-US.js.map +1 -0
  30. package/dist/keeta/index.d.ts +253 -0
  31. package/dist/keeta/index.js +388 -0
  32. package/dist/keeta/index.js.map +1 -0
  33. package/dist/keeta/pt-BR.d.ts +23 -0
  34. package/dist/keeta/pt-BR.js +23 -0
  35. package/dist/keeta/pt-BR.js.map +1 -0
  36. package/dist/manifest/index.d.ts +3 -0
  37. package/dist/manifest/index.js +1 -1
  38. package/dist/manifest/server.d.ts +2 -2
  39. package/dist/manifest/server.js +3 -3
  40. package/dist/rappi/index.d.ts +7 -1
  41. package/dist/rappi/index.js +20 -3
  42. package/dist/rappi/index.js.map +1 -1
  43. package/dist/server/index.d.ts +6 -2
  44. package/dist/server/index.js +3 -3
  45. package/package.json +14 -2
  46. package/prisma/marketplace.prisma +45 -1
  47. package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
  48. package/src/99food/catalogue.ts +19 -89
  49. package/src/99food/copy.ts +4 -19
  50. package/src/99food/index.ts +29 -28
  51. package/src/99food/normalize.ts +11 -247
  52. package/src/99food/outbound.ts +29 -215
  53. package/src/99food/pause.ts +7 -22
  54. package/src/core/adapter.ts +41 -1
  55. package/src/core/bulk.ts +1 -1
  56. package/src/core/engine.ts +9 -0
  57. package/src/core/ingest.ts +6 -0
  58. package/src/core/integration.ts +17 -0
  59. package/src/core/lifecycle-port.ts +16 -0
  60. package/src/core/lifecycle.ts +133 -0
  61. package/src/core/outbound-queue.ts +24 -4
  62. package/src/core/outbound-sweep.ts +49 -5
  63. package/src/core/outbound.ts +11 -0
  64. package/src/core/pipeline.ts +22 -2
  65. package/src/core/ports.ts +39 -3
  66. package/src/core/status-inform.ts +51 -0
  67. package/src/core/status-job.ts +207 -0
  68. package/src/core/status-store.ts +85 -0
  69. package/src/core/types.ts +14 -0
  70. package/src/ifood/index.ts +7 -1
  71. package/src/ifood/normalize.ts +17 -0
  72. package/src/ifood/outbound.ts +35 -0
  73. package/src/index.ts +8 -1
  74. package/src/keeta/authorization.ts +226 -0
  75. package/src/keeta/copy.ts +27 -0
  76. package/src/keeta/en-US.ts +19 -0
  77. package/src/keeta/index.ts +162 -0
  78. package/src/keeta/merchant.ts +70 -0
  79. package/src/keeta/normalize.ts +131 -0
  80. package/src/keeta/outbound.ts +55 -0
  81. package/src/keeta/pt-BR.ts +23 -0
  82. package/src/keeta/signature.ts +85 -0
  83. package/src/open-delivery/client.ts +185 -0
  84. package/src/open-delivery/merchant.ts +126 -0
  85. package/src/open-delivery/normalize.ts +269 -0
  86. package/src/open-delivery/orders.ts +241 -0
  87. package/src/open-delivery/reasons.ts +26 -0
  88. package/src/rappi/index.ts +6 -1
  89. package/src/rappi/normalize.ts +6 -0
  90. package/src/rappi/outbound.ts +31 -2
  91. package/src/server/mcp.ts +2 -0
  92. package/src/server/webhook.ts +3 -1
  93. package/dist/chunk-L3DCOZUU.js.map +0 -1
  94. package/dist/chunk-SJUKBCVO.js.map +0 -1
  95. package/dist/chunk-UYFYGGCS.js.map +0 -1
  96. package/dist/chunk-YVUZHXUF.js.map +0 -1
package/src/core/types.ts CHANGED
@@ -136,6 +136,14 @@ export interface NormalizedMarketplaceOrder {
136
136
  */
137
137
  export type CancellationOutcome = "CONFIRMED" | "FAILED";
138
138
 
139
+ /**
140
+ * A step of the order's life a marketplace announces about an order it
141
+ * already has (FUT-4653): the courier left (`DISPATCHED`) or the order is
142
+ * finished (`CONCLUDED`). An event that names one moves nothing by itself; the
143
+ * engine asks the host to move the order forward (`onLifecycle`).
144
+ */
145
+ export type MarketplaceLifecycle = "DISPATCHED" | "CONCLUDED";
146
+
139
147
  /** What an adapter makes of one inbound delivery. */
140
148
  export interface NormalizedEvent {
141
149
  provider: MarketplaceProvider;
@@ -167,4 +175,10 @@ export interface NormalizedEvent {
167
175
  * the event. Ignored when `order` is present.
168
176
  */
169
177
  orderToFetch?: boolean;
178
+ /**
179
+ * OPTIONAL. The lifecycle step this event announces about an order the
180
+ * engine already has. Absent or null: the event names none. An event that
181
+ * names one carries no order body.
182
+ */
183
+ lifecycle?: MarketplaceLifecycle | null;
170
184
  }
@@ -3,7 +3,7 @@ import { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from
3
3
  import { IFOOD_CATALOGUE } from "./catalogue";
4
4
  import { IFOOD_CATALOGUE_READER } from "./catalogue-read";
5
5
  import { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
6
- import { IFOOD_PORTAL_URL, ifoodConfirm, ifoodRequestCancellation } from "./outbound";
6
+ import { IFOOD_PORTAL_URL, ifoodConfirm, ifoodInformStatus, ifoodRequestCancellation, ifoodStatusSupported } from "./outbound";
7
7
  import { IFOOD_AVAILABILITY } from "./pause";
8
8
 
9
9
  /**
@@ -60,6 +60,10 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
60
60
  // request in seconds when it answers at all, so 5 minutes is generous.
61
61
  // A host overrides it with the engine's `cancellationWindowMs`.
62
62
  cancellationAnswerWindowMs: IFOOD_CANCELLATION_ANSWER_WINDOW_MS,
63
+ // Told what iFood has an endpoint for (ESTIMATED, see `./outbound.ts`): ready for
64
+ // pickup, and dispatched for a merchant bag. Never "handed over": iFood's own
65
+ // CONCLUDED is that.
66
+ statusSteps: ["READY", "DISPATCHED"],
63
67
  },
64
68
  normalize: (payload) => normalizeIfoodEvent(payload, normalizeOptions),
65
69
  readSignature: (header) => header("x-ifood-signature") ?? header("x-signature"),
@@ -71,6 +75,8 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
71
75
  catalogueReader: IFOOD_CATALOGUE_READER,
72
76
  confirm: (ctx, order) => ifoodConfirm(ctx, order),
73
77
  requestCancellation: ifoodRequestCancellation,
78
+ statusSupported: ifoodStatusSupported,
79
+ informStatus: ifoodInformStatus,
74
80
  // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
75
81
  availability: IFOOD_AVAILABILITY,
76
82
  // No per-order deep link is known, so the portal, where a live order is
@@ -1,4 +1,5 @@
1
1
  import type {
2
+ MarketplaceLifecycle,
2
3
  MarketplaceDeliveredBy,
3
4
  MarketplaceDiscountSponsor,
4
5
  MarketplaceOrderType,
@@ -39,6 +40,21 @@ const ORDER_CANCELLED = new Set(["CAN", "CANCELLED", "ORDER_CANCELLED"]);
39
40
  /** iFood refused the store's own cancellation request. */
40
41
  const CANCELLATION_REQUEST_FAILED = new Set(["CARF", "CANCELLATION_REQUEST_FAILED"]);
41
42
 
43
+ /**
44
+ * The lifecycle events (FUT-4653): the order left (`DSP`) and the order is
45
+ * finished (`CON`). ESTIMATED: iFood's portal refused our reader (Cloudflare
46
+ * 403, https://developer.ifood.com.br, 2026-11-25), so these codes and their
47
+ * long forms are the ones iFood's event stream is commonly documented with,
48
+ * not read off a page. They sit here beside the sets above so homologation
49
+ * corrects one place.
50
+ */
51
+ const LIFECYCLE_OF: Readonly<Record<string, MarketplaceLifecycle>> = {
52
+ DSP: "DISPATCHED",
53
+ DISPATCHED: "DISPATCHED",
54
+ CON: "CONCLUDED",
55
+ CONCLUDED: "CONCLUDED",
56
+ };
57
+
42
58
  /**
43
59
  * Verify a delivery against the merchant's webhook secret: iFood signs the raw
44
60
  * body with HMAC-SHA256, hex. The rule (an unset secret accepts; a set one
@@ -257,5 +273,6 @@ export function normalizeIfoodEvent(
257
273
  order: placed ? readOrder(payload, externalOrderId, options.missingStreetNumber) : null,
258
274
  cancelled,
259
275
  cancellationOutcome: cancelled ? "CONFIRMED" : refusedRequest ? "FAILED" : null,
276
+ ...(LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}),
260
277
  };
261
278
  }
@@ -6,6 +6,7 @@ import {
6
6
  type CancellationRequestInput,
7
7
  type OutboundOrderRef,
8
8
  type OutboundResult,
9
+ type StatusFacts,
9
10
  } from "../core/adapter";
10
11
 
11
12
  /**
@@ -114,3 +115,37 @@ export function ifoodRequestCancellation(
114
115
  cancellationCode: input.reason.code,
115
116
  });
116
117
  }
118
+
119
+ /**
120
+ * What iFood is told, per step (FUT-4653). ESTIMATED, every row: iFood's
121
+ * developer portal answered 403 behind Cloudflare to our reader
122
+ * (https://developer.ifood.com.br, 2026-11-25), so the endpoint names below are
123
+ * the Merchant API's commonly documented ones (`order/v1.0`), not read off a
124
+ * page.
125
+ *
126
+ * - READY: `POST /orders/{id}/readyToPickup`, for a take-out, and ESTIMATED
127
+ * whether iFood takes it for its own fleet; not for a bag the merchant
128
+ * delivers, which is dispatched, not made ready for pickup.
129
+ * - DISPATCHED: `POST /orders/{id}/dispatch`, only for `deliveredBy: MERCHANT`.
130
+ * - HANDED_OVER: none. iFood has no conclude endpoint for a merchant;
131
+ * CONCLUDED is iFood's own event.
132
+ */
133
+ const STATUS_ACTION: Readonly<Record<string, (facts: StatusFacts) => string | null>> = {
134
+ READY: (facts) => (facts.deliveredBy === "MERCHANT" ? null : "readyToPickup"),
135
+ DISPATCHED: (facts) => (facts.deliveredBy === "MERCHANT" ? "dispatch" : null),
136
+ };
137
+
138
+ /** Whether iFood takes this step for this kind of order: answered offline. */
139
+ export function ifoodStatusSupported(facts: StatusFacts): boolean {
140
+ return STATUS_ACTION[facts.step]?.(facts) != null;
141
+ }
142
+
143
+ /** Tell iFood a step happened. `unsupported` when it has no endpoint for it. */
144
+ export async function ifoodInformStatus(
145
+ ctx: AdapterCallContext,
146
+ order: OutboundOrderRef,
147
+ facts: StatusFacts,
148
+ ): Promise<OutboundResult | { kind: "unsupported" }> {
149
+ const action = STATUS_ACTION[facts.step]?.(facts) ?? null;
150
+ return action === null ? { kind: "unsupported" } : postOrder(ctx, order.externalOrderId, action);
151
+ }
package/src/index.ts CHANGED
@@ -13,7 +13,8 @@
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
15
  * an adapter at its own subpath (`@12-apps/marketplace/ifood`,
16
- * `@12-apps/marketplace/99food`, `@12-apps/marketplace/rappi`), registered at
16
+ * `@12-apps/marketplace/99food`, `@12-apps/marketplace/keeta`,
17
+ * `@12-apps/marketplace/rappi`), registered at
17
18
  * mount. The wiring manifests are at `./manifest` and `./manifest/server`.
18
19
  *
19
20
  * Everything the engine needs from its host is a required port with no
@@ -38,6 +39,8 @@ export {
38
39
  type MarketplaceHttpRequest,
39
40
  type MarketplaceHttpResponse,
40
41
  type OutboundOrderRef,
42
+ type StatusFacts,
43
+ type StatusStep,
41
44
  type OutboundResult,
42
45
  } from "./core/adapter";
43
46
  export {
@@ -59,6 +62,8 @@ export type {
59
62
  MarketplaceDb,
60
63
  MarketplaceEngineConfig,
61
64
  MarketplaceEnqueuePort,
65
+ MarketplaceLifecycleAnswer,
66
+ MarketplaceLifecycleFacts,
62
67
  MarketplaceLogger,
63
68
  MarketplaceOrderPort,
64
69
  MarketplaceOrderSummary,
@@ -76,6 +81,7 @@ export {
76
81
  type MarketplaceProvider,
77
82
  type NormalizedAddress,
78
83
  type NormalizedBuyer,
84
+ type MarketplaceLifecycle,
79
85
  type NormalizedEvent,
80
86
  type NormalizedMarketplaceOrder,
81
87
  type NormalizedOrderDiscount,
@@ -127,6 +133,7 @@ export {
127
133
  type OutboundJobPayload,
128
134
  } from "./core/outbound-queue";
129
135
  export type { DeliveryOutcome } from "./core/pipeline";
136
+ export type { InformStatusInput } from "./core/status-inform";
130
137
  export {
131
138
  FetchOrderRetryError,
132
139
  MARKETPLACE_FETCH_ORDER_JOB,
@@ -0,0 +1,226 @@
1
+ import { outboundResultOf, type AdapterCallContext } from "../core/adapter";
2
+ import { asString, firstString, pick } from "../core/payload-read";
3
+ import { isStop, openDeliveryCall, type OpenDeliveryDialect, type OpenDeliveryStop } from "../open-delivery/client";
4
+
5
+ /**
6
+ * Keeta's MERCHANT AUTHORIZATION, automated from the software (Keeta's
7
+ * "Autorização Self-serve do Merchant", read 2026-11-26 at
8
+ * https://api-docs.mykeeta.com/apis/opendelivery/merchant-self-serve-authorization).
9
+ * Not on the adapter port: connecting a store is the host's flow, and these
10
+ * are the calls it is built from.
11
+ *
12
+ * 1. {@link KeetaAuthorization.authorizationUrl}: `GET
13
+ * /oauth/authorization/url?clientId=&redirectUri=` (no token: a token
14
+ * needs at least one authorized store), the link the merchant opens.
15
+ * 2. The merchant authorizes; Keeta redirects to `redirectUri` with `authId`
16
+ * (and `state`, `appId`, `timestamp`), and POSTs the authorization webhook
17
+ * ({@link normalizeKeetaAuthorizationEvent}: `opType` 1 added, 2 revoked).
18
+ * 3. {@link KeetaAuthorization.authorizedShops}: `GET
19
+ * /oauth/authorized/{authId}/merchantInfo?pageNum=&pageSize=` lists the
20
+ * stores of that authorization (Keeta's ids, names, addresses, time zones).
21
+ * 4. The host maps a Keeta store to its own, then
22
+ * {@link KeetaAuthorization.onboard}: `PUT /v1/merchantOnboarding?merchantId=`
23
+ * binds the SOFTWARE's merchant id (the connection's `externalMerchantId`)
24
+ * to `keetaMerchantId` and registers the `GET /v1/merchant` URL and the
25
+ * orders webhook. "Without onboarding there are no order events"; sending
26
+ * it again for the same id REPLACES the mapping. Answer 201.
27
+ *
28
+ * ESTIMATED: the JSON answer the authorization webhook wants ("200 within
29
+ * ~5 s, with JSON containing `code` and `message`": the values are not
30
+ * given, {@link KEETA_AUTHORIZATION_WEBHOOK_ANSWER} sends 0 and "success").
31
+ */
32
+
33
+ /** What the authorization webhook is answered with, 200, within ~5 s. ESTIMATED values. */
34
+ export const KEETA_AUTHORIZATION_WEBHOOK_ANSWER = { code: 0, message: "success" } as const;
35
+
36
+ /** One authorization change Keeta reported (event 1301 added, 1302 revoked). */
37
+ export interface KeetaAuthorizationEvent {
38
+ authId: string;
39
+ change: "AUTHORIZED" | "REVOKED";
40
+ /** Keeta's store id (an integer on the wire, text here). */
41
+ shopId: string;
42
+ shopName: string | null;
43
+ /** The application's id. */
44
+ clientId: string | null;
45
+ at: Date | null;
46
+ }
47
+
48
+ /** Read the authorization webhook's body (`WebhookNotification`). Null when it names no authorization or store. */
49
+ export function normalizeKeetaAuthorizationEvent(payload: unknown): KeetaAuthorizationEvent | null {
50
+ const authId = firstString(payload, [["authId"]]);
51
+ const shopId = firstString(payload, [["shopId"]]);
52
+ const opType = pick(payload, "opType");
53
+ const change = opType === 1 ? "AUTHORIZED" : opType === 2 ? "REVOKED" : null;
54
+ if (!authId || !shopId || !change) return null;
55
+ const millis = pick(payload, "createTime");
56
+ return {
57
+ authId,
58
+ change,
59
+ shopId,
60
+ shopName: firstString(payload, [["shopName"]]),
61
+ clientId: firstString(payload, [["clientId"]]),
62
+ at: typeof millis === "number" && Number.isFinite(millis) ? new Date(millis) : null,
63
+ };
64
+ }
65
+
66
+ /** One store of an authorization, as `merchantInfo` lists it. */
67
+ export interface KeetaAuthorizedShop {
68
+ /** Keeta's store id: the `keetaMerchantId` the onboarding takes. */
69
+ id: string;
70
+ name: string | null;
71
+ address: string | null;
72
+ latitude: number | null;
73
+ longitude: number | null;
74
+ timeZone: string | null;
75
+ }
76
+
77
+ /** One page of an authorization's stores. */
78
+ export interface KeetaAuthorizedShops {
79
+ brandId: string | null;
80
+ brandName: string | null;
81
+ shops: KeetaAuthorizedShop[];
82
+ page: { pageNum: number; totalPage: number; totalCount: number };
83
+ }
84
+
85
+ /** What the host registers for one store at onboarding. */
86
+ export interface KeetaOnboarding {
87
+ /** The SOFTWARE's merchant id: the connection's `externalMerchantId`, the `Merchant.id` the host serves. */
88
+ merchantId: string;
89
+ /** Keeta's store id, from `authorizedShops` or Keeta's portal. */
90
+ keetaMerchantId: number;
91
+ /** Where Keeta reads this store's `GET /v1/merchant` (one URL per store), and its key if it wants one. */
92
+ merchantDocument?: { url: string; apiKey?: string };
93
+ /** The engine's webhook for this store: `…/webhooks/marketplace/:tenantSlug/KEETA`. */
94
+ ordersWebhookUrl?: string;
95
+ }
96
+
97
+ export type KeetaAuthorizationResult<T> = { kind: "ok"; value: T } | OpenDeliveryStop;
98
+
99
+ const numberOr = (value: unknown, fallback: number | null): number | null =>
100
+ typeof value === "number" && Number.isFinite(value) ? value : fallback;
101
+
102
+ function shopOf(raw: unknown): KeetaAuthorizedShop | null {
103
+ const id = firstString(raw, [["id"]]);
104
+ if (!id) return null;
105
+ return {
106
+ id,
107
+ name: firstString(raw, [["name"]]),
108
+ address: firstString(raw, [["address"]]),
109
+ latitude: numberOr(pick(raw, "latitude"), null),
110
+ longitude: numberOr(pick(raw, "longitude"), null),
111
+ timeZone: firstString(raw, [["timeZone"]]),
112
+ };
113
+ }
114
+
115
+ function shopsOf(body: unknown): KeetaAuthorizedShops {
116
+ const raw = pick(body, "authorizedShops");
117
+ return {
118
+ brandId: asString(pick(body, "brandId")),
119
+ brandName: firstString(body, [["brandName"]]),
120
+ shops: (Array.isArray(raw) ? raw : []).map(shopOf).filter((shop): shop is KeetaAuthorizedShop => shop !== null),
121
+ page: {
122
+ pageNum: numberOr(pick(body, "page", "pageNum"), 1) ?? 1,
123
+ totalPage: numberOr(pick(body, "page", "totalPage"), 1) ?? 1,
124
+ totalCount: numberOr(pick(body, "page", "totalCount"), 0) ?? 0,
125
+ },
126
+ };
127
+ }
128
+
129
+ /** One call whose 2xx answer is read by `read`: the value, or the result that ends it. */
130
+ async function readCall<T>(
131
+ ctx: AdapterCallContext,
132
+ dialect: OpenDeliveryDialect,
133
+ call: Parameters<typeof openDeliveryCall>[2],
134
+ read: (body: unknown) => T | null,
135
+ ): Promise<KeetaAuthorizationResult<T>> {
136
+ try {
137
+ const response = await openDeliveryCall(ctx, dialect, call);
138
+ if (isStop(response)) return response;
139
+ const result = outboundResultOf(response);
140
+ if (result.kind !== "accepted") return result;
141
+ let body: unknown = null;
142
+ try {
143
+ body = response.body === "" ? null : JSON.parse(response.body);
144
+ } catch {
145
+ body = null;
146
+ }
147
+ const value = read(body);
148
+ return value === null
149
+ ? { kind: "refused", status: response.status, message: "Keeta's answer is not the documented shape" }
150
+ : { kind: "ok", value };
151
+ } catch (error) {
152
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
153
+ }
154
+ }
155
+
156
+ /** The self-serve authorization calls, bound to Keeta's dialect. */
157
+ export interface KeetaAuthorization {
158
+ authorizationUrl(ctx: AdapterCallContext, input: { redirectUri?: string }): Promise<KeetaAuthorizationResult<string>>;
159
+ authorizedShops(
160
+ ctx: AdapterCallContext,
161
+ input: { authId: string; pageNum?: number; pageSize?: number },
162
+ ): Promise<KeetaAuthorizationResult<KeetaAuthorizedShops>>;
163
+ onboard(ctx: AdapterCallContext, input: KeetaOnboarding): Promise<KeetaAuthorizationResult<true>>;
164
+ }
165
+
166
+ /** An https URL Keeta answered, or null. */
167
+ function httpsUrl(body: unknown): string | null {
168
+ const url = firstString(body, [["merchantAuthorizationUrl"]]);
169
+ if (!url) return null;
170
+ try {
171
+ return new URL(url).protocol === "https:" ? url : null;
172
+ } catch {
173
+ return null;
174
+ }
175
+ }
176
+
177
+ export function keetaAuthorization(dialect: OpenDeliveryDialect): KeetaAuthorization {
178
+ return {
179
+ authorizationUrl: (ctx, input) =>
180
+ readCall(
181
+ ctx,
182
+ dialect,
183
+ {
184
+ method: "GET",
185
+ path: "/oauth/authorization/url",
186
+ query: { clientId: ctx.credentials.clientId, ...(input.redirectUri ? { redirectUri: input.redirectUri } : {}) },
187
+ authenticated: false,
188
+ },
189
+ httpsUrl,
190
+ ),
191
+ authorizedShops: (ctx, input) =>
192
+ readCall(
193
+ ctx,
194
+ dialect,
195
+ {
196
+ method: "GET",
197
+ path: `/oauth/authorized/${encodeURIComponent(input.authId)}/merchantInfo`,
198
+ query: { pageNum: String(input.pageNum ?? 1), pageSize: String(Math.min(input.pageSize ?? 100, 100)) },
199
+ },
200
+ (body) => (body === null ? null : shopsOf(body)),
201
+ ),
202
+ onboard: (ctx, input) =>
203
+ readCall(
204
+ ctx,
205
+ dialect,
206
+ {
207
+ method: "PUT",
208
+ path: "/v1/merchantOnboarding",
209
+ query: { merchantId: input.merchantId },
210
+ body: {
211
+ keetaMerchantId: input.keetaMerchantId,
212
+ ...(input.merchantDocument
213
+ ? {
214
+ getMerchantURL: {
215
+ baseURL: input.merchantDocument.url,
216
+ ...(input.merchantDocument.apiKey ? { apiKey: input.merchantDocument.apiKey } : {}),
217
+ },
218
+ }
219
+ : {}),
220
+ ...(input.ordersWebhookUrl ? { ordersWebhookURL: input.ordersWebhookUrl } : {}),
221
+ },
222
+ },
223
+ () => true as const,
224
+ ),
225
+ };
226
+ }
@@ -0,0 +1,27 @@
1
+ import { OPEN_DELIVERY_MERCHANT_REASON_CODES } from "../open-delivery/reasons";
2
+
3
+ /**
4
+ * The words the Keeta 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
+ /**
12
+ * The cancellation codes a merchant may send: Keeta's "códigos de
13
+ * cancelamento (v1.0.7+)", the same eleven as Open Delivery's
14
+ * (`../open-delivery/reasons.ts`). Keeta still accepts its legacy codes
15
+ * (`INSUFFICIENT_DISHES`, `SUSPENSION_OF_BUSINESS`, `INSUFFICIENT_MANPOWER`,
16
+ * `OTHERS`) and recommends the new ones, so only the new ones are offered.
17
+ */
18
+ export const KEETA_REASON_CODES = OPEN_DELIVERY_MERCHANT_REASON_CODES;
19
+
20
+ export type KeetaReasonCode = (typeof KEETA_REASON_CODES)[number];
21
+
22
+ export interface KeetaAdapterCopy {
23
+ /** One label per reason code. Sent as the request's `reason` text when the store wrote none. */
24
+ reasonLabels: Readonly<Record<KeetaReasonCode, string>>;
25
+ /** What an address with no street number (or an encrypted one Keeta would not reveal) says instead. */
26
+ missingStreetNumber: string;
27
+ }
@@ -0,0 +1,19 @@
1
+ import type { KeetaAdapterCopy } from "./copy";
2
+
3
+ /** The Keeta adapter's en-US pack: the same reasons, in English. */
4
+ export const KEETA_ADAPTER_COPY_EN_US = {
5
+ reasonLabels: {
6
+ SYSTEMIC_ISSUES: "System problems",
7
+ DUPLICATE_APPLICATION: "Duplicate order",
8
+ UNAVAILABLE_ITEM: "Item unavailable",
9
+ RESTAURANT_WITHOUT_DELIVERY_PERSON: "No courier available",
10
+ OUTDATED_MENU: "Menu out of date",
11
+ ORDER_OUTSIDE_THE_DELIVERY_AREA: "Outside the delivery area",
12
+ BLOCKED_CUSTOMER: "Blocked customer",
13
+ OUTSIDE_DELIVERY_HOURS: "Outside delivery hours",
14
+ INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT: "Internal difficulties",
15
+ RISK_AREA: "Risk area",
16
+ DELIVERY_PROBLEM: "Delivery problem",
17
+ },
18
+ missingStreetNumber: "no number",
19
+ } as const satisfies KeetaAdapterCopy;
@@ -0,0 +1,162 @@
1
+ import type { AdapterCallContext, CancellationReason, MarketplaceAdapter } from "../core/adapter";
2
+ import { assertHttpsUrl } from "../open-delivery/client";
3
+ import {
4
+ openDeliveryConfirm,
5
+ openDeliveryFetchOrder,
6
+ openDeliveryRequestCancellation,
7
+ openDeliveryStatus,
8
+ } from "../open-delivery/orders";
9
+ import { OPEN_DELIVERY_ITEM_UNAVAILABLE } from "../open-delivery/reasons";
10
+ import { keetaAuthorization, type KeetaAuthorization } from "./authorization";
11
+ import { KEETA_REASON_CODES, type KeetaAdapterCopy } from "./copy";
12
+ import { keetaAvailability, keetaCatalogue } from "./merchant";
13
+ import { KEETA_PROVIDER, normalizeKeetaEvent, normalizeKeetaOrder, revealKeetaOrder } from "./normalize";
14
+ import { KEETA_DEFAULT_API_BASE_URLS, keetaDialect, type KeetaApiBaseUrls } from "./outbound";
15
+ import { verifyKeetaSignature } from "./signature";
16
+
17
+ /**
18
+ * `@12-apps/marketplace/keeta` — Keeta, as one adapter on the engine.
19
+ *
20
+ * Keeta's API is Open Delivery v1.5.0 with Keeta's own changes
21
+ * (https://api-docs.mykeeta.com/apis/opendelivery, `openapi.json` "v.1.0.7"
22
+ * with the changelog to 1.0.9, read 2026-11-26), so the adapter is built on
23
+ * the same Open Delivery module as 99Food's (`../open-delivery/`), which
24
+ * speaks v1.7.1. What Keeta does differently, and where it is handled:
25
+ *
26
+ * | Keeta | 99Food (v1.7.1) | handled in |
27
+ * |---|---|---|
28
+ * | `X-App-Signature` on EVERY request: Base64 HMAC-SHA256 of URL + sorted query + RFC 8785 body, keyed by the client secret | no request signature | `./signature.ts`, `./outbound.ts` |
29
+ * | webhook signature Base64 | lowercase hex | `./signature.ts` |
30
+ * | token: JSON `grant_type: app_level_token`, one token per APPLICATION (every authorized store) | form-encoded `client_credentials` | `./outbound.ts` |
31
+ * | merchant authorization by the software: authorization URL, authorized stores, onboarding, authorization webhook | none | `./authorization.ts` |
32
+ * | `merchantUpdate/{merchantId}` (path names the merchant) | `merchantUpdate` | `./merchant.ts` |
33
+ * | menu: full reload only (`ITEM_OFFER`/`OPTION` status excepted) | full reload | `./merchant.ts` |
34
+ * | personal data encrypted (`ENC_…`), `batchDecrypt` for a merchant's own delivery | plain | `./normalize.ts` |
35
+ * | no `CANCELLATION_REQUEST_DENIED`: a refused request is silent, so it ends TIMEOUT | the denial event | `./normalize.ts`, the answer window below |
36
+ * | `outOfStockItems` carries the PDV codes (`externalCode`) | item uuids, not sent | `../open-delivery/orders.ts` option |
37
+ * | no take-out: no `pickedUp`; `delivered` only for the merchant's bag | `pickedUp` for a take-out | `../open-delivery/orders.ts` option |
38
+ * | one public base URL and portal | given at onboarding | defaults below |
39
+ *
40
+ * ```ts
41
+ * import { createKeetaAdapter } from "@12-apps/marketplace/keeta";
42
+ * import { KEETA_ADAPTER_COPY_PT_BR } from "@12-apps/marketplace/keeta/pt-BR";
43
+ *
44
+ * createMarketplaceEngine({ …ports, adapters: [createKeetaAdapter({ copy: KEETA_ADAPTER_COPY_PT_BR })] });
45
+ * ```
46
+ *
47
+ * Its webhook is the engine's one route, `POST
48
+ * /webhooks/marketplace/:tenantSlug/KEETA`, registered per store as
49
+ * `ordersWebhookURL` at onboarding.
50
+ */
51
+
52
+ export { KEETA_PROVIDER } from "./normalize";
53
+
54
+ /**
55
+ * How long Keeta may take to answer a cancellation request. ESTIMATED: Keeta
56
+ * names none, and sends no event for a refusal, so past this the request is
57
+ * failed as TIMEOUT. Keeta's own clock is 5 minutes for the acceptance.
58
+ */
59
+ export const KEETA_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;
60
+
61
+ /** Where "open it on Keeta" goes by default: the Merchant Portal (Keeta names no per-order link). */
62
+ export const KEETA_PORTAL_URL = "https://merchant.mykeeta.com/";
63
+
64
+ /** Keeta has no take-out (`PICKED_UP` "is not sent"), so no `pickedUp`. */
65
+ const STATUS = openDeliveryStatus({ takeoutPickedUp: false });
66
+
67
+ export interface KeetaAdapterConfig {
68
+ /** The words the adapter needs: reason labels and the missing-number text. Required. */
69
+ copy: KeetaAdapterCopy;
70
+ /** OPTIONAL. Where Keeta serves Open Delivery, per environment. Default: the documented server for both. https only. */
71
+ apiBaseUrl?: KeetaApiBaseUrls;
72
+ /** OPTIONAL. Where "open it on Keeta" goes. Default: the Merchant Portal. https only. */
73
+ portalUrl?: string;
74
+ /**
75
+ * OPTIONAL, off by default. Offer the store pause (FUT-4851) through
76
+ * `merchantStatus`, a store-wide switch with no id: a store the owner also
77
+ * closed by hand on Keeta during the kitchen's pause is opened with it.
78
+ */
79
+ pauseByStoreSwitch?: boolean;
80
+ }
81
+
82
+ const assertHttps = (name: string, url: string): void => assertHttpsUrl("@12-apps/marketplace/keeta", name, url);
83
+
84
+ /** The Keeta API base URLs a config names, checked. */
85
+ function basesOf(config: Pick<KeetaAdapterConfig, "apiBaseUrl">): KeetaApiBaseUrls {
86
+ const bases = { ...(config.apiBaseUrl ?? KEETA_DEFAULT_API_BASE_URLS) };
87
+ assertHttps("apiBaseUrl.SANDBOX", bases.SANDBOX);
88
+ assertHttps("apiBaseUrl.PRODUCTION", bases.PRODUCTION);
89
+ return bases;
90
+ }
91
+
92
+ /** Build the Keeta adapter. Its reasons are static: a dialog never waits on Keeta. */
93
+ export function createKeetaAdapter(config: KeetaAdapterConfig): MarketplaceAdapter {
94
+ const dialect = keetaDialect(basesOf(config));
95
+ const portalUrl = config.portalUrl ?? KEETA_PORTAL_URL;
96
+ assertHttps("portalUrl", portalUrl);
97
+ const reasons: readonly CancellationReason[] = KEETA_REASON_CODES.map((code) => ({
98
+ code,
99
+ label: config.copy.reasonLabels[code],
100
+ itemUnavailable: code === OPEN_DELIVERY_ITEM_UNAVAILABLE,
101
+ // `outOfStockItems` is optional: sent when the store named the SKUs, never required.
102
+ needsItems: false,
103
+ }));
104
+ const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };
105
+ const fetchOptions = {
106
+ normalize: (order: unknown) => normalizeKeetaOrder(order, normalizeOptions),
107
+ prepare: (ctx: AdapterCallContext, order: unknown) => revealKeetaOrder(ctx, dialect, order),
108
+ };
109
+ // Keeta's own example sends PDV codes in `outOfStockItems` ("PDV-1002"). ESTIMATED that it reads them so.
110
+ const cancellation = { outOfStockAsSkus: true };
111
+ return {
112
+ provider: KEETA_PROVIDER,
113
+ capabilities: {
114
+ apiConfirm: true,
115
+ apiCancel: true,
116
+ // "The merchant may cancel up to 48 h after the conclusion"; the answer is Keeta's.
117
+ cancelAfterAccept: true,
118
+ // 202 ("received for analysis"), then CANCELLED, or nothing at all.
119
+ asyncCancellationOutcome: true,
120
+ perOrderAppLink: false,
121
+ // `OrderConfirmed.preparationTime`, in minutes.
122
+ confirmTakesPreparationTime: true,
123
+ cancellationAnswerWindowMs: KEETA_CANCELLATION_ANSWER_WINDOW_MS,
124
+ // readyForPickup, dispatch (merchant's bag) and delivered (merchant's bag).
125
+ statusSteps: ["READY", "DISPATCHED", "HANDED_OVER"],
126
+ },
127
+ normalize: normalizeKeetaEvent,
128
+ readSignature: (header) => header("x-app-signature"),
129
+ verifySignature: verifyKeetaSignature,
130
+ cancellationReasons: () => reasons,
131
+ // PULL: Keeta reads the menu the host serves (`GET /v1/merchant`) and is told when it changed.
132
+ catalogue: keetaCatalogue(dialect),
133
+ fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx, dialect, order, fetchOptions),
134
+ confirm: (ctx, order, input) => openDeliveryConfirm(ctx, dialect, order, input),
135
+ requestCancellation: (ctx, order, input) =>
136
+ openDeliveryRequestCancellation(ctx, dialect, order, input, cancellation),
137
+ statusSupported: STATUS.supported,
138
+ informStatus: (ctx, order, facts) => STATUS.inform(ctx, dialect, order, facts),
139
+ appLink: () => portalUrl,
140
+ ...(config.pauseByStoreSwitch ? { availability: keetaAvailability(dialect) } : {}),
141
+ };
142
+ }
143
+
144
+ /** The self-serve merchant authorization calls (`./authorization.ts`), for the same base URLs as the adapter. */
145
+ export function createKeetaAuthorization(config: Pick<KeetaAdapterConfig, "apiBaseUrl"> = {}): KeetaAuthorization {
146
+ return keetaAuthorization(keetaDialect(basesOf(config)));
147
+ }
148
+
149
+ export { KEETA_REASON_CODES, type KeetaAdapterCopy, type KeetaReasonCode } from "./copy";
150
+ export { normalizeKeetaEvent, normalizeKeetaOrder } from "./normalize";
151
+ export { canonicalJson, keetaRequestSignature, verifyKeetaSignature } from "./signature";
152
+ export { KEETA_API_BASE_URL, type KeetaApiBaseUrls } from "./outbound";
153
+ export {
154
+ KEETA_AUTHORIZATION_WEBHOOK_ANSWER,
155
+ normalizeKeetaAuthorizationEvent,
156
+ type KeetaAuthorization,
157
+ type KeetaAuthorizationEvent,
158
+ type KeetaAuthorizationResult,
159
+ type KeetaAuthorizedShop,
160
+ type KeetaAuthorizedShops,
161
+ type KeetaOnboarding,
162
+ } from "./authorization";