@12-apps/marketplace 1.2.0 → 1.4.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 (69) hide show
  1. package/ADOPTING.md +76 -4
  2. package/README.md +163 -3
  3. package/dist/99food/index.d.ts +79 -2
  4. package/dist/99food/index.js +117 -2
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/adapter-B8QtQ2RA.d.ts +612 -0
  7. package/dist/{chunk-CRYFYDQ2.js → chunk-DPCZVN2C.js} +69 -5
  8. package/dist/chunk-DPCZVN2C.js.map +1 -0
  9. package/dist/{chunk-D2X7TOR6.js → chunk-EBAIZQPB.js} +841 -86
  10. package/dist/chunk-EBAIZQPB.js.map +1 -0
  11. package/dist/chunk-M2V4RFMA.js +23 -0
  12. package/dist/chunk-M2V4RFMA.js.map +1 -0
  13. package/dist/{chunk-24RQZPSV.js → chunk-SZRZTLVU.js} +1 -1
  14. package/dist/chunk-SZRZTLVU.js.map +1 -0
  15. package/dist/{engine-D-a4mttc.d.ts → engine-o5cm54vC.d.ts} +462 -2
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +2 -2
  18. package/dist/ifood/index.d.ts +22 -2
  19. package/dist/ifood/index.js +396 -56
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +30 -4
  22. package/dist/index.js +445 -9
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/server.d.ts +5 -2
  25. package/dist/manifest/server.js +2 -2
  26. package/dist/rappi/index.d.ts +15 -2
  27. package/dist/rappi/index.js +62 -2
  28. package/dist/rappi/index.js.map +1 -1
  29. package/dist/server/index.d.ts +25 -10
  30. package/dist/server/index.js +4 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +158 -1
  33. package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
  34. package/prisma/migrations/20261113230000_marketplace_store_pause/migration.sql +70 -0
  35. package/src/99food/catalogue.ts +117 -0
  36. package/src/99food/index.ts +14 -0
  37. package/src/99food/outbound.ts +3 -3
  38. package/src/99food/pause.ts +56 -0
  39. package/src/core/adapter.ts +20 -1
  40. package/src/core/catalogue-category.ts +119 -0
  41. package/src/core/catalogue-ids.ts +23 -0
  42. package/src/core/catalogue-job.ts +332 -0
  43. package/src/core/catalogue-port.ts +173 -0
  44. package/src/core/catalogue-store.ts +172 -0
  45. package/src/core/catalogue-sweep.ts +43 -0
  46. package/src/core/catalogue.ts +226 -0
  47. package/src/core/engine.ts +83 -0
  48. package/src/core/outbound-sweep.ts +7 -2
  49. package/src/core/pause-job.ts +381 -0
  50. package/src/core/pause-port.ts +110 -0
  51. package/src/core/pause-retired.ts +139 -0
  52. package/src/core/pause-store.ts +151 -0
  53. package/src/core/pause-sweep.ts +148 -0
  54. package/src/core/pause.ts +316 -0
  55. package/src/core/ports.ts +47 -0
  56. package/src/ifood/catalogue.ts +273 -0
  57. package/src/ifood/index.ts +8 -0
  58. package/src/ifood/outbound.ts +9 -6
  59. package/src/ifood/pause.ts +257 -0
  60. package/src/index.ts +64 -0
  61. package/src/rappi/index.ts +17 -0
  62. package/src/rappi/outbound.ts +2 -2
  63. package/src/rappi/pause.ts +98 -0
  64. package/src/server/index.ts +1 -0
  65. package/src/server/jobs.ts +100 -10
  66. package/dist/adapter-_iuSxvVD.d.ts +0 -319
  67. package/dist/chunk-24RQZPSV.js.map +0 -1
  68. package/dist/chunk-CRYFYDQ2.js.map +0 -1
  69. package/dist/chunk-D2X7TOR6.js.map +0 -1
@@ -0,0 +1,273 @@
1
+ import {
2
+ answered,
3
+ outboundResultOf,
4
+ type MarketplaceHttpResponse,
5
+ type OutboundResult,
6
+ } from "../core/adapter";
7
+ import { stableUuid } from "../core/catalogue-ids";
8
+ import type {
9
+ CatalogueCallContext,
10
+ CatalogueImage,
11
+ CatalogueItemOut,
12
+ CatalogueItemRef,
13
+ CataloguePublishResult,
14
+ CatalogueStoredImage,
15
+ CatalogueWarningCode,
16
+ PushCatalogue,
17
+ } from "../core/catalogue-port";
18
+ import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
19
+
20
+ /**
21
+ * The iFood adapter's CATALOGUE half: iFood's Catalog API v2.0, push (FUT-4768).
22
+ *
23
+ * Read 2026-11-13 from iFood's developer portal (the Catalog module's
24
+ * Introduction, Fundamentals, Endpoints and Errors pages, and the rate-limit
25
+ * page); the package README's "Catalogue publishing" table marks each fact
26
+ * CONFIRMED with its URL or ESTIMATED. What is ESTIMATED here is said beside
27
+ * it, and lives in this file only, so the homologation run corrects one file.
28
+ *
29
+ * One publish is, in order:
30
+ * 1. the category, by name: `GET /categories`, else `POST /categories`
31
+ * (`template: "DEFAULT"`);
32
+ * 2. the photo, when the item has one: the `imagePath` iFood already holds
33
+ * for the same photo URL, else `POST /image/upload` with a base64 data URL
34
+ * of the bytes the host's loader reads, which answers `imagePath`;
35
+ * 3. the item: `PUT /items` with `item`, `products`, `optionGroups`,
36
+ * `options` — idempotent, it replaces the whole item, and the item appears
37
+ * at once (synchronous).
38
+ *
39
+ * iFood wants item and product ids the software generates, UUID v4 (any other
40
+ * shape answers 404), so they are derived from the engine's publication
41
+ * reference: a retried publish names the same item. The item's `externalCode`
42
+ * is the host's product id (unique per merchant).
43
+ *
44
+ * A withdraw pauses the item, `PATCH /items/status` with `UNAVAILABLE`: the
45
+ * Endpoints page lists no item delete, and a paused item is not shown in the
46
+ * app (ESTIMATED that this is what "off" should mean; a re-publish puts it
47
+ * back AVAILABLE with the same id).
48
+ */
49
+
50
+ const catalogUrl = (merchantId: string, path: string): string =>
51
+ `${IFOOD_API}/catalog/v2.0/merchants/${encodeURIComponent(merchantId)}/${path}`;
52
+
53
+ /** The item's and its product's ids, stable per publication. */
54
+ export const ifoodItemId = (ref: string): string => stableUuid(`${ref}:item`);
55
+ export const ifoodProductId = (ref: string): string => stableUuid(`${ref}:product`);
56
+
57
+ type Failure = Exclude<OutboundResult, { kind: "accepted" }>;
58
+
59
+ /** iFood's price object: a decimal of the currency's major unit. */
60
+ const priceOf = (cents: number): { value: number } => ({ value: Math.round(cents) / 100 });
61
+
62
+ /** One authenticated call to the catalogue: the raw answer, or the failure that ends it. */
63
+ async function call(
64
+ ctx: CatalogueCallContext,
65
+ method: "GET" | "POST" | "PUT" | "PATCH",
66
+ path: string,
67
+ body?: unknown,
68
+ ): Promise<MarketplaceHttpResponse | Failure> {
69
+ const auth = await bearer(ctx);
70
+ if (!("token" in auth)) return auth.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : auth;
71
+ const response = await ctx.http({
72
+ method,
73
+ url: catalogUrl(ctx.externalMerchantId, path),
74
+ headers: {
75
+ Authorization: `Bearer ${auth.token}`,
76
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
77
+ },
78
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
79
+ });
80
+ if (response.status !== 401) return response;
81
+ ctx.tokens.delete(ifoodTokenKey(ctx));
82
+ return { kind: "retry", reason: "iFood refused the token" };
83
+ }
84
+
85
+ /** A non-2xx answer as the failure it is (never `accepted`). */
86
+ function failureOf(response: MarketplaceHttpResponse): Failure {
87
+ const result = outboundResultOf(response);
88
+ return result.kind === "accepted" ? { kind: "retry", reason: "unexpected answer" } : result;
89
+ }
90
+
91
+ const ok = (response: MarketplaceHttpResponse): boolean => response.status >= 200 && response.status < 300;
92
+
93
+ function parse(body: string): unknown {
94
+ try {
95
+ return JSON.parse(body) as unknown;
96
+ } catch {
97
+ return null;
98
+ }
99
+ }
100
+
101
+ /** The id of the category named `name`, from a category list. ESTIMATED: the list answers an array of `{ id, name }`. */
102
+ function categoryIdIn(body: string, name: string): string | null {
103
+ const parsed = parse(body);
104
+ if (!Array.isArray(parsed)) return null;
105
+ const wanted = name.trim().toLowerCase();
106
+ const found = parsed.find(
107
+ (entry: unknown) =>
108
+ typeof entry === "object" && entry !== null && String((entry as { name?: unknown }).name ?? "").trim().toLowerCase() === wanted,
109
+ ) as { id?: unknown } | undefined;
110
+ return typeof found?.id === "string" ? found.id : null;
111
+ }
112
+
113
+ /** The category named `name` on iFood, or null; the failure that ended the read otherwise. */
114
+ async function findCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string | null } | Failure> {
115
+ const listed = await call(ctx, "GET", "categories");
116
+ if ("kind" in listed) return listed;
117
+ if (!ok(listed)) return failureOf(listed);
118
+ return { id: categoryIdIn(listed.body, name) };
119
+ }
120
+
121
+ /**
122
+ * Find the category by name, else create it, then read the list again and
123
+ * adopt the first of that name: a POST whose answer was lost and was retried
124
+ * is found rather than created twice. The engine runs this once per
125
+ * (connection, name) at a time and stores the id (`ctx.category`).
126
+ */
127
+ async function findOrCreateCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string } | Failure> {
128
+ const found = await findCategory(ctx, name);
129
+ if ("kind" in found) return found;
130
+ if (found.id) return { id: found.id };
131
+ const created = await call(ctx, "POST", "categories", { name, status: "AVAILABLE", template: "DEFAULT" });
132
+ if ("kind" in created) return created;
133
+ if (!ok(created)) return failureOf(created);
134
+ const id = (parse(created.body) as { id?: unknown } | null)?.id;
135
+ if (typeof id !== "string") return { kind: "retry", reason: "iFood created the category without an id" };
136
+ // ESTIMATED: the list answers categories in creation order, so the first match is the oldest.
137
+ const again = await findCategory(ctx, name);
138
+ return "id" in again && again.id ? { id: again.id } : { id };
139
+ }
140
+
141
+ const categoryId = (ctx: CatalogueCallContext, name: string): Promise<{ id: string } | Failure> =>
142
+ ctx.category(name, () => findOrCreateCategory(ctx, name));
143
+
144
+ /** The photo the item goes out with, and what the publish could not do about it. */
145
+ interface PhotoOutcome {
146
+ image: CatalogueStoredImage | null;
147
+ warning?: CatalogueWarningCode;
148
+ }
149
+
150
+ /**
151
+ * The photo for this publish, uploading only when it must:
152
+ * - no `imageUrl`: no photo;
153
+ * - the photo iFood already holds was made from this same URL: reuse it;
154
+ * - else upload the bytes the host's loader reads; when it reads nothing,
155
+ * keep the photo iFood holds, if any (PUT replaces the whole item, so
156
+ * sending none would drop it);
157
+ * - an upload iFood refuses (413 over 5 MB, another final 4xx) publishes
158
+ * without a photo and says why as a warning, rather than failing the item.
159
+ */
160
+ async function photoFor(ctx: CatalogueCallContext, item: CatalogueItemOut): Promise<PhotoOutcome | Failure> {
161
+ const stored = item.storedImage;
162
+ if (item.imageUrl === null) return { image: null };
163
+ if (stored && stored.sourceUrl === item.imageUrl) return { image: stored };
164
+ const bytes = await ctx.loadImage(item.imageUrl);
165
+ return bytes ? upload(ctx, bytes, item.imageUrl) : { image: stored };
166
+ }
167
+
168
+ /** `POST /image/upload`: the new photo, a warning for a refused one, or the failure to retry. */
169
+ async function upload(ctx: CatalogueCallContext, bytes: CatalogueImage, sourceUrl: string): Promise<PhotoOutcome | Failure> {
170
+ const uploaded = await call(ctx, "POST", "image/upload", { image: `data:${bytes.contentType};base64,${bytes.base64}` });
171
+ if ("kind" in uploaded) return uploaded;
172
+ if (!ok(uploaded)) {
173
+ const failure = failureOf(uploaded);
174
+ if (failure.kind === "retry") return failure;
175
+ return { image: null, warning: uploaded.status === 413 ? "IMAGE_TOO_LARGE" : "IMAGE_REFUSED" };
176
+ }
177
+ const path = (parse(uploaded.body) as { imagePath?: unknown } | null)?.imagePath;
178
+ if (typeof path !== "string") return { kind: "retry", reason: "iFood answered the upload without an imagePath" };
179
+ return { image: { ref: path, sourceUrl } };
180
+ }
181
+
182
+ /** The `PUT /items` body for one simple item with no add-ons. */
183
+ export function ifoodItemBody(item: CatalogueItemOut, category: string, image: string | null): unknown {
184
+ const itemId = ifoodItemId(item.ref);
185
+ const productId = ifoodProductId(item.ref);
186
+ return {
187
+ item: {
188
+ id: itemId,
189
+ type: "DEFAULT",
190
+ categoryId: category,
191
+ status: "AVAILABLE",
192
+ price: priceOf(item.priceCents),
193
+ externalCode: item.productId,
194
+ // ESTIMATED: the guide's examples link item and product implicitly; the
195
+ // field naming the product is not shown on the pages read.
196
+ productId,
197
+ },
198
+ products: [
199
+ {
200
+ id: productId,
201
+ name: item.name,
202
+ description: item.description ?? "",
203
+ externalCode: `${item.productId}-product`,
204
+ // ESTIMATED field name: the Errors page names `imagePath` as what the upload returns and the item carries.
205
+ ...(image === null ? {} : { imagePath: image }),
206
+ },
207
+ ],
208
+ optionGroups: [],
209
+ options: [],
210
+ };
211
+ }
212
+
213
+ /**
214
+ * Whether a refused PUT was refused because the stored category is gone (the
215
+ * store deleted it on iFood's portal): iFood's 400 and 404 do not say which id
216
+ * was unknown, so the list is read again, and a category of that name with
217
+ * another id, or none at all, means the stored one is stale. ESTIMATED that a
218
+ * deleted category answers 400 or 404.
219
+ */
220
+ async function categoryWentStale(ctx: CatalogueCallContext, put: MarketplaceHttpResponse, name: string, used: string): Promise<boolean> {
221
+ if (put.status !== 400 && put.status !== 404) return false;
222
+ const found = await findCategory(ctx, name);
223
+ return !("kind" in found) && found.id !== used;
224
+ }
225
+
226
+ /** `PUT /items`, once more with the category found or created again when the stored one went stale. */
227
+ async function putItem(ctx: CatalogueCallContext, item: CatalogueItemOut, image: string | null): Promise<MarketplaceHttpResponse | Failure> {
228
+ const category = await categoryId(ctx, item.categoryName);
229
+ if ("kind" in category) return category;
230
+ const put = await call(ctx, "PUT", "items", ifoodItemBody(item, category.id, image));
231
+ if ("kind" in put || ok(put) || !(await categoryWentStale(ctx, put, item.categoryName, category.id))) return put;
232
+ await ctx.forgetCategory(item.categoryName);
233
+ const again = await categoryId(ctx, item.categoryName);
234
+ if ("kind" in again) return again;
235
+ return call(ctx, "PUT", "items", ifoodItemBody(item, again.id, image));
236
+ }
237
+
238
+ async function publish(ctx: CatalogueCallContext, item: CatalogueItemOut): Promise<CataloguePublishResult> {
239
+ const photo = await photoFor(ctx, item);
240
+ if ("kind" in photo) return photo;
241
+ const put = await putItem(ctx, item, photo.image?.ref ?? null);
242
+ if ("kind" in put) return put;
243
+ if (!ok(put)) return failureOf(put);
244
+ // iFood's orders carry the item's `externalCode` as the line's SKU (the order normalizer reads it).
245
+ const published = { kind: "published" as const, externalId: ifoodItemId(item.ref), sku: item.productId, image: photo.image };
246
+ return photo.warning ? { ...published, warning: photo.warning } : published;
247
+ }
248
+
249
+ async function withdraw(ctx: CatalogueCallContext, item: CatalogueItemRef): Promise<OutboundResult> {
250
+ const itemId = item.externalId ?? ifoodItemId(item.ref);
251
+ const patched = await call(ctx, "PATCH", "items/status", { itemId, status: "UNAVAILABLE" });
252
+ if ("kind" in patched) return patched;
253
+ // ESTIMATED: a 404 means iFood does not have the item, so it is already out
254
+ // of its catalogue (the Errors page says 404 is "the resource does not exist").
255
+ if (patched.status === 404) return { kind: "accepted" };
256
+ return outboundResultOf(patched);
257
+ }
258
+
259
+ /** A call that never got an answer is a retry. */
260
+ async function publishedOrRetry(run: () => Promise<CataloguePublishResult>): Promise<CataloguePublishResult> {
261
+ try {
262
+ return await run();
263
+ } catch (error) {
264
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
265
+ }
266
+ }
267
+
268
+ /** iFood's catalogue capability. */
269
+ export const IFOOD_CATALOGUE: PushCatalogue = {
270
+ mode: "push",
271
+ publishItem: (ctx, item) => publishedOrRetry(() => publish(ctx, item)),
272
+ withdrawItem: (ctx, item) => answered(() => withdraw(ctx, item)),
273
+ };
@@ -1,7 +1,9 @@
1
1
  import type { CancellationReason, MarketplaceAdapter } from "../core/adapter";
2
2
  import { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from "./copy";
3
+ import { IFOOD_CATALOGUE } from "./catalogue";
3
4
  import { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
4
5
  import { IFOOD_PORTAL_URL, ifoodConfirm, ifoodRequestCancellation } from "./outbound";
6
+ import { IFOOD_AVAILABILITY } from "./pause";
5
7
 
6
8
  /**
7
9
  * `@12-apps/marketplace/ifood` — iFood, as one adapter on the engine.
@@ -62,8 +64,12 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
62
64
  readSignature: (header) => header("x-ifood-signature") ?? header("x-signature"),
63
65
  verifySignature: verifyIfoodSignature,
64
66
  cancellationReasons: () => reasons,
67
+ // The Catalog API v2.0: each item is written and paused through the API (FUT-4768).
68
+ catalogue: IFOOD_CATALOGUE,
65
69
  confirm: (ctx, order) => ifoodConfirm(ctx, order),
66
70
  requestCancellation: ifoodRequestCancellation,
71
+ // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
72
+ availability: IFOOD_AVAILABILITY,
67
73
  // No per-order deep link is known, so the portal, where a live order is
68
74
  // on the first screen.
69
75
  appLink: () => IFOOD_PORTAL_URL,
@@ -72,3 +78,5 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
72
78
 
73
79
  export { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from "./copy";
74
80
  export { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
81
+ export { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from "./catalogue";
82
+ export { IFOOD_AVAILABILITY, ifoodLocalTime, ifoodPause, ifoodResume } from "./pause";
@@ -21,10 +21,10 @@ import {
21
21
  */
22
22
 
23
23
  /** iFood's merchant API. Sandbox and production share the host; the credentials differ. */
24
- const API = "https://merchant-api.ifood.com.br";
25
- const TOKEN_URL = `${API}/authentication/v1.0/oauth/token`;
24
+ export const IFOOD_API = "https://merchant-api.ifood.com.br";
25
+ const TOKEN_URL = `${IFOOD_API}/authentication/v1.0/oauth/token`;
26
26
  const orderUrl = (externalOrderId: string, action: string): string =>
27
- `${API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}/${action}`;
27
+ `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}/${action}`;
28
28
 
29
29
  /**
30
30
  * iFood's order-manager portal. No per-order deep link was found in the
@@ -36,6 +36,9 @@ export const IFOOD_PORTAL_URL = "https://portal.ifood.com.br/";
36
36
  /** A token is renewed this long before iFood says it expires. */
37
37
  const TOKEN_MARGIN_MS = 60_000;
38
38
 
39
+ /** The token cache key: per environment and merchant app. */
40
+ export const ifoodTokenKey = (ctx: AdapterCallContext): string => `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`;
41
+
39
42
  /** iFood's OAuth answer, read defensively: a missing field is "no token". */
40
43
  function tokenOf(body: string): { token: string; expiresInSeconds: number } | null {
41
44
  try {
@@ -53,8 +56,8 @@ function tokenOf(body: string): { token: string; expiresInSeconds: number } | nu
53
56
  * client-credentials grant. Keyed by the app's client id, so two stores with
54
57
  * two apps never share one. The token lives in memory only.
55
58
  */
56
- async function bearer(ctx: AdapterCallContext): Promise<{ token: string } | OutboundResult> {
57
- const key = `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`;
59
+ export async function bearer(ctx: AdapterCallContext): Promise<{ token: string } | OutboundResult> {
60
+ const key = ifoodTokenKey(ctx);
58
61
  const cached = ctx.tokens.get(key);
59
62
  if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
60
63
  const response = await ctx.http({
@@ -89,7 +92,7 @@ function postOrder(ctx: AdapterCallContext, externalOrderId: string, action: str
89
92
  ...(body === undefined ? {} : { body: JSON.stringify(body) }),
90
93
  });
91
94
  // A 401 is a token that went stale under us: forget it, and the retry fetches another.
92
- if (response.status === 401) ctx.tokens.delete(`IFOOD:${ctx.environment}:${ctx.credentials.clientId}`);
95
+ if (response.status === 401) ctx.tokens.delete(ifoodTokenKey(ctx));
93
96
  return response.status === 401 ? { kind: "retry", reason: "iFood refused the token" } : outboundResultOf(response);
94
97
  });
95
98
  }
@@ -0,0 +1,257 @@
1
+ import {
2
+ answered,
3
+ outboundResultOf,
4
+ type AdapterCallContext,
5
+ type MarketplaceHttpRequest,
6
+ type MarketplaceHttpResponse,
7
+ type OutboundResult,
8
+ } from "../core/adapter";
9
+ import type { MarketplaceAvailability, StorePauseRef, StorePauseRequest, StorePauseResult } from "../core/pause-port";
10
+ import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
11
+
12
+ /**
13
+ * iFood's half of the store pause (FUT-4851): the Merchant API's
14
+ * INTERRUPTIONS, a closure with its own id, a start and an end, that does not
15
+ * touch the store's opening hours.
16
+ *
17
+ * - List: `GET /merchant/v1.0/merchants/{merchantId}/interruptions`
18
+ * (active and future interruptions).
19
+ * - Create: `POST …/interruptions` with `{ id, description, start, end }`,
20
+ * 201 with the interruption.
21
+ * - Delete: `DELETE …/interruptions/{interruptionId}`, 204.
22
+ *
23
+ * iFood's developer portal refuses our reader (403), so the paths, verbs and
24
+ * the body's `description`/`start`/`end` come from two public third-party
25
+ * clients of the API (README, "Pausing a store"): ESTIMATED until the
26
+ * homologation run. Also ESTIMATED: that iFood takes the client's own `id`.
27
+ * It is sent, but the adapter does not rely on it: every create is preceded
28
+ * by a list, and an interruption is ours when it carries our id OR, where
29
+ * iFood assigned its own, exactly the end and the description the create
30
+ * sent, so a retry after a lost answer never makes a second one and a resume
31
+ * by key deletes the one that landed. An interruption the owner made by hand
32
+ * is neither. ESTIMATED too: that there is no call to move an interruption's
33
+ * end (so no `extend`: the engine creates the new one, then deletes the old);
34
+ * that iFood ACCEPTS the two overlapping for that moment (if it refuses an
35
+ * overlap, the renewal is FAILED with iFood's words and the old interruption
36
+ * still holds to its own end); and how iFood reads a
37
+ * time: one client says the offset is discarded and the time read as the
38
+ * store's own clock, so the time goes out as the store's wall clock WITH its
39
+ * offset, which reads the same either way. A 404 on delete is "already gone".
40
+ */
41
+
42
+ const interruptionsUrl = (merchantId: string): string =>
43
+ `${IFOOD_API}/merchant/v1.0/merchants/${encodeURIComponent(merchantId)}/interruptions`;
44
+
45
+ type Settled = Exclude<OutboundResult, { kind: "accepted" }>;
46
+
47
+ /** One authenticated call: the raw answer, or the result that ends it. */
48
+ async function call(
49
+ ctx: AdapterCallContext,
50
+ request: Omit<MarketplaceHttpRequest, "headers"> & { json?: unknown },
51
+ ): Promise<MarketplaceHttpResponse | Settled> {
52
+ const auth = await bearer(ctx);
53
+ if (!("token" in auth)) return auth.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : auth;
54
+ const response = await ctx.http({
55
+ method: request.method,
56
+ url: request.url,
57
+ headers: {
58
+ Authorization: `Bearer ${auth.token}`,
59
+ ...(request.json === undefined ? {} : { "Content-Type": "application/json" }),
60
+ },
61
+ ...(request.json === undefined ? {} : { body: JSON.stringify(request.json) }),
62
+ });
63
+ // A 401 is a token that went stale under us: forget it, and the retry fetches another.
64
+ if (response.status !== 401) return response;
65
+ ctx.tokens.delete(ifoodTokenKey(ctx));
66
+ return { kind: "retry", reason: "iFood refused the token" };
67
+ }
68
+
69
+ const settled = (value: MarketplaceHttpResponse | Settled): value is Settled => "kind" in value;
70
+
71
+ /** The answer as anything but 2xx, read the engine's way. */
72
+ function notOk(response: MarketplaceHttpResponse): Settled | null {
73
+ const result = outboundResultOf(response);
74
+ return result.kind === "accepted" ? null : result;
75
+ }
76
+
77
+ /** One interruption as the list answers it, read defensively. */
78
+ interface Interruption {
79
+ id: string;
80
+ end: string | null;
81
+ description: string | null;
82
+ }
83
+
84
+ /** The interruptions on the merchant, or the result that ends the call. */
85
+ async function listInterruptions(ctx: AdapterCallContext, merchantId: string): Promise<Interruption[] | Settled> {
86
+ const response = await call(ctx, { method: "GET", url: interruptionsUrl(merchantId) });
87
+ if (settled(response)) return response;
88
+ const failure = notOk(response);
89
+ if (failure) return failure;
90
+ try {
91
+ const parsed = JSON.parse(response.body === "" ? "[]" : response.body) as unknown;
92
+ if (!Array.isArray(parsed)) return [];
93
+ return parsed.flatMap((entry: unknown) => {
94
+ const value = (entry ?? {}) as { id?: unknown; end?: unknown; description?: unknown };
95
+ if (typeof value.id !== "string") return [];
96
+ return [
97
+ {
98
+ id: value.id,
99
+ end: typeof value.end === "string" ? value.end : null,
100
+ description: typeof value.description === "string" ? value.description : null,
101
+ },
102
+ ];
103
+ });
104
+ } catch {
105
+ return { kind: "retry", reason: "iFood answered the interruption list with something that is not JSON" };
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Whether iFood's `end` is the instant the create sent. An `end` that states
111
+ * its zone (`Z` or an offset) is compared as an instant, and only as one: an
112
+ * owner's interruption at another instant is never claimed because its digits
113
+ * look like ours. Only an `end` with no zone (iFood echoing the store's own
114
+ * clock) is compared as the store's wall clock.
115
+ */
116
+ function sameEnd(end: string, until: Date, timeZone: string): boolean {
117
+ const sent = ifoodLocalTime(until, timeZone);
118
+ if (end === sent) return true;
119
+ if (/(?:[zZ]|[+-]\d{2}:?\d{2})$/u.test(end)) {
120
+ const parsed = Date.parse(end);
121
+ return !Number.isNaN(parsed) && Math.floor(parsed / 1000) === Math.floor(until.getTime() / 1000);
122
+ }
123
+ return end.slice(0, 19) === sent.slice(0, 19);
124
+ }
125
+
126
+ /**
127
+ * The interruption the create under `key` made: by our id, or by the end and
128
+ * description it carried, never one the engine already holds (`keep`).
129
+ */
130
+ function ours(
131
+ list: readonly Interruption[],
132
+ key: string,
133
+ sent: { until: Date; reason: string; timeZone: string } | null,
134
+ keep: readonly string[] = [],
135
+ ): Interruption | undefined {
136
+ const candidates = list.filter((entry) => !keep.includes(entry.id));
137
+ const byKey = candidates.find((entry) => entry.id === key);
138
+ if (byKey || !sent) return byKey;
139
+ return candidates.find(
140
+ (entry) => entry.description === sent.reason && entry.end !== null && sameEnd(entry.end, sent.until, sent.timeZone),
141
+ );
142
+ }
143
+
144
+ interface WallClock {
145
+ year: number;
146
+ month: number;
147
+ day: number;
148
+ hour: number;
149
+ minute: number;
150
+ second: number;
151
+ }
152
+
153
+ /** The wall clock of `date` in `timeZone`. */
154
+ function wallClock(date: Date, timeZone: string): WallClock {
155
+ const format = new Intl.DateTimeFormat("en-US", {
156
+ timeZone,
157
+ hourCycle: "h23",
158
+ year: "numeric",
159
+ month: "2-digit",
160
+ day: "2-digit",
161
+ hour: "2-digit",
162
+ minute: "2-digit",
163
+ second: "2-digit",
164
+ });
165
+ const clock: WallClock = { year: 0, month: 1, day: 1, hour: 0, minute: 0, second: 0 };
166
+ for (const part of format.formatToParts(date)) {
167
+ if (part.type in clock) clock[part.type as keyof WallClock] = Number(part.value);
168
+ }
169
+ return clock;
170
+ }
171
+
172
+ const pad = (value: number, width = 2): string => String(value).padStart(width, "0");
173
+
174
+ /**
175
+ * `date` as the store's wall clock with its offset: `2026-11-13T15:30:00-03:00`.
176
+ * Read the same whether iFood honours the offset or reads the store's clock.
177
+ */
178
+ export function ifoodLocalTime(date: Date, timeZone: string): string {
179
+ const local = wallClock(date, timeZone);
180
+ const asUtc = Date.UTC(local.year, local.month - 1, local.day, local.hour, local.minute, local.second);
181
+ const offset = Math.round((asUtc - Math.floor(date.getTime() / 1000) * 1000) / 60_000);
182
+ const abs = Math.abs(offset);
183
+ return (
184
+ `${pad(local.year, 4)}-${pad(local.month)}-${pad(local.day)}` +
185
+ `T${pad(local.hour)}:${pad(local.minute)}:${pad(local.second)}` +
186
+ `${offset < 0 ? "-" : "+"}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`
187
+ );
188
+ }
189
+
190
+ /** The created interruption's id: iFood's answer, else the one the engine sent. */
191
+ function createdId(body: string, sent: string): string {
192
+ try {
193
+ const id = (JSON.parse(body) as { id?: unknown }).id;
194
+ return typeof id === "string" && id !== "" ? id : sent;
195
+ } catch {
196
+ return sent;
197
+ }
198
+ }
199
+
200
+ /** Close the store until `request.until`: find one a lost answer created under the key, else create it. */
201
+ export function ifoodPause(ctx: AdapterCallContext, request: StorePauseRequest): Promise<StorePauseResult> {
202
+ return answeredPause(async () => {
203
+ const list = await listInterruptions(ctx, request.merchantId);
204
+ if (!Array.isArray(list)) return list;
205
+ const landed = ours(list, request.key, { until: request.until, reason: request.reason, timeZone: request.timeZone }, request.keep);
206
+ if (landed) return { kind: "paused", externalId: landed.id, until: request.until };
207
+ const response = await call(ctx, {
208
+ method: "POST",
209
+ url: interruptionsUrl(request.merchantId),
210
+ json: {
211
+ id: request.key,
212
+ description: request.reason,
213
+ start: ifoodLocalTime(ctx.now, request.timeZone),
214
+ end: ifoodLocalTime(request.until, request.timeZone),
215
+ },
216
+ });
217
+ if (settled(response)) return response;
218
+ const failure = notOk(response);
219
+ if (failure) return failure;
220
+ return { kind: "paused", externalId: createdId(response.body, request.key), until: request.until };
221
+ });
222
+ }
223
+
224
+ /** Delete THIS interruption: by its id, or the one a lost answer created under the key (by id, or by its end and description). */
225
+ export function ifoodResume(ctx: AdapterCallContext, ref: StorePauseRef): Promise<OutboundResult> {
226
+ return answered(async () => {
227
+ let id = ref.externalId;
228
+ if (id === null && ref.key !== null) {
229
+ const list = await listInterruptions(ctx, ref.merchantId);
230
+ if (!Array.isArray(list)) return list;
231
+ id = ours(list, ref.key, ref.sent, ref.keep)?.id ?? null;
232
+ }
233
+ // Nothing of ours stands: there is nothing to delete.
234
+ if (id === null) return { kind: "accepted" };
235
+ const response = await call(ctx, { method: "DELETE", url: `${interruptionsUrl(ref.merchantId)}/${encodeURIComponent(id)}` });
236
+ if (settled(response)) return response;
237
+ // Already gone: it ended, or a person removed it.
238
+ if (response.status === 404) return { kind: "accepted" };
239
+ return outboundResultOf(response);
240
+ });
241
+ }
242
+
243
+ /** {@link answered} for a pause: a call that never got an answer is a retry. */
244
+ async function answeredPause(run: () => Promise<StorePauseResult>): Promise<StorePauseResult> {
245
+ try {
246
+ return await run();
247
+ } catch (error) {
248
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
249
+ }
250
+ }
251
+
252
+ /** iFood's availability capability: interruptions, no extend. */
253
+ export const IFOOD_AVAILABILITY: MarketplaceAvailability = {
254
+ kind: "interruption",
255
+ pause: ifoodPause,
256
+ resume: ifoodResume,
257
+ };
package/src/index.ts CHANGED
@@ -21,6 +21,7 @@
21
21
  */
22
22
 
23
23
  export { createMarketplaceEngine, type MarketplaceEngine } from "./core/engine";
24
+ export { stableUuid } from "./core/catalogue-ids";
24
25
  export {
25
26
  answered,
26
27
  outboundResultOf,
@@ -52,6 +53,7 @@ export type {
52
53
  CancellationFailureReason,
53
54
  MarketplaceAuditEntry,
54
55
  MarketplaceAuditPort,
56
+ MarketplaceCataloguePort,
55
57
  MarketplaceClockPort,
56
58
  MarketplaceDb,
57
59
  MarketplaceEngineConfig,
@@ -129,3 +131,65 @@ export {
129
131
  type FetchOrderOutcome,
130
132
  } from "./core/fetch-order";
131
133
  export type { MarketplaceOrderState } from "./core/state";
134
+ export {
135
+ CatalogueRetryError,
136
+ catalogueDedupeKey,
137
+ MARKETPLACE_CATALOGUE_JOB,
138
+ type CatalogueAction,
139
+ type CatalogueJobPayload,
140
+ type CatalogueOutcome,
141
+ } from "./core/catalogue-job";
142
+ export type {
143
+ CatalogueActionResult,
144
+ CatalogueDocumentResult,
145
+ CataloguePublishInput,
146
+ CatalogueRefusalCode,
147
+ CatalogueTarget,
148
+ } from "./core/catalogue";
149
+ export type {
150
+ CatalogueCallContext,
151
+ CatalogueFailure,
152
+ CatalogueImage,
153
+ CatalogueItem,
154
+ CatalogueItemOut,
155
+ CatalogueItemRef,
156
+ CatalogueMenuEntry,
157
+ CatalogueMenuOptions,
158
+ CatalogueStoredImage,
159
+ CatalogueWarningCode,
160
+ CataloguePublishResult,
161
+ MarketplaceCatalogue,
162
+ PullCatalogue,
163
+ PushCatalogue,
164
+ } from "./core/catalogue-port";
165
+ export type {
166
+ CatalogueFailedAction,
167
+ CatalogueFailureCode,
168
+ CataloguePublicationView,
169
+ CatalogueStatus,
170
+ } from "./core/catalogue-store";
171
+ export { CATALOGUE_GIVE_UP_MS, CATALOGUE_STALE_MS } from "./core/catalogue-sweep";
172
+ export type {
173
+ MarketplaceAvailability,
174
+ StorePauseRef,
175
+ StorePauseRequest,
176
+ StorePauseResult,
177
+ } from "./core/pause-port";
178
+ export type {
179
+ PauseOutcome,
180
+ PauseStoreInput,
181
+ PauseStoreResult,
182
+ ResumeOutcome,
183
+ StoreAvailabilityView,
184
+ } from "./core/pause";
185
+ export { AvailabilityRetryError, type AvailabilityOutcome } from "./core/pause-job";
186
+ export {
187
+ MARKETPLACE_AVAILABILITY_JOB,
188
+ STORE_PAUSE_LEASE_MS,
189
+ availabilityDedupeKey,
190
+ type AvailabilityJobPayload,
191
+ type StorePauseFailureCode,
192
+ type StorePauseState,
193
+ type StorePauseWanted,
194
+ } from "./core/pause-store";
195
+ export type { AvailabilitySweepResult } from "./core/pause-sweep";