@12-apps/marketplace 1.4.0 → 1.5.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 (37) hide show
  1. package/README.md +51 -1
  2. package/dist/99food/index.d.ts +1 -1
  3. package/dist/99food/index.js +1 -1
  4. package/dist/{adapter-B8QtQ2RA.d.ts → adapter-CCWMqt2g.d.ts} +150 -1
  5. package/dist/{chunk-EBAIZQPB.js → chunk-FKUEFVVA.js} +2 -1
  6. package/dist/{chunk-SZRZTLVU.js → chunk-RGMSD7S7.js} +1 -1
  7. package/dist/chunk-RGMSD7S7.js.map +1 -0
  8. package/dist/{chunk-DPCZVN2C.js → chunk-UONWZIBO.js} +2 -2
  9. package/dist/chunk-WN2EK4KX.js +15 -0
  10. package/dist/chunk-WN2EK4KX.js.map +1 -0
  11. package/dist/{engine-o5cm54vC.d.ts → engine-C3uq_BJd.d.ts} +11 -1
  12. package/dist/hono/index.d.ts +2 -2
  13. package/dist/hono/index.js +2 -2
  14. package/dist/ifood/index.d.ts +32 -2
  15. package/dist/ifood/index.js +286 -9
  16. package/dist/ifood/index.js.map +1 -1
  17. package/dist/index.d.ts +3 -3
  18. package/dist/index.js +44 -2
  19. package/dist/index.js.map +1 -1
  20. package/dist/manifest/server.d.ts +2 -2
  21. package/dist/manifest/server.js +2 -2
  22. package/dist/rappi/index.d.ts +1 -1
  23. package/dist/rappi/index.js +1 -1
  24. package/dist/server/index.d.ts +2 -2
  25. package/dist/server/index.js +2 -2
  26. package/package.json +1 -1
  27. package/src/core/adapter.ts +7 -0
  28. package/src/core/catalogue-read-port.ts +151 -0
  29. package/src/core/catalogue-read.ts +51 -0
  30. package/src/core/engine.ts +9 -0
  31. package/src/ifood/catalogue-read.ts +187 -0
  32. package/src/ifood/catalogue-snapshot.ts +246 -0
  33. package/src/ifood/index.ts +5 -0
  34. package/src/index.ts +15 -0
  35. package/dist/chunk-SZRZTLVU.js.map +0 -1
  36. /package/dist/{chunk-EBAIZQPB.js.map → chunk-FKUEFVVA.js.map} +0 -0
  37. /package/dist/{chunk-DPCZVN2C.js.map → chunk-UONWZIBO.js.map} +0 -0
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  MARKETPLACE_JOBS,
3
3
  createApiMarketplace
4
- } from "../chunk-DPCZVN2C.js";
4
+ } from "../chunk-UONWZIBO.js";
5
5
  import "../chunk-UYFYGGCS.js";
6
- import "../chunk-EBAIZQPB.js";
6
+ import "../chunk-FKUEFVVA.js";
7
7
  import "../chunk-7QVYU63E.js";
8
8
 
9
9
  // src/manifest/server.ts
@@ -1,4 +1,4 @@
1
- import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-B8QtQ2RA.js';
1
+ import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CCWMqt2g.js';
2
2
 
3
3
  /**
4
4
  * The words the Rappi adapter needs from its host, and nothing else.
@@ -8,7 +8,7 @@ import {
8
8
  import {
9
9
  answered,
10
10
  outboundResultOf
11
- } from "../chunk-SZRZTLVU.js";
11
+ } from "../chunk-RGMSD7S7.js";
12
12
  import {
13
13
  __name
14
14
  } from "../chunk-7QVYU63E.js";
@@ -1,7 +1,7 @@
1
- import { y as DecisionProblemCode, f as BulkProblemCode, Z as MarketplaceEngine, a1 as MarketplaceLogger, ae as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-o5cm54vC.js';
1
+ import { y as DecisionProblemCode, f as BulkProblemCode, Z as MarketplaceEngine, a1 as MarketplaceLogger, ae as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-C3uq_BJd.js';
2
2
  import { WireRoute, WireJobBlueprint } from '@12-apps/wiring';
3
3
  import { z } from 'zod';
4
- import '../adapter-B8QtQ2RA.js';
4
+ import '../adapter-CCWMqt2g.js';
5
5
 
6
6
  /** Every problem code a route can answer, decisions and bulk writes alike. */
7
7
  type MarketplaceProblemCode = DecisionProblemCode | BulkProblemCode;
@@ -6,7 +6,7 @@ import {
6
6
  MARKETPLACE_SWEEP_QUEUE,
7
7
  ORDER_NOT_PENDING_CODE,
8
8
  createApiMarketplace
9
- } from "../chunk-DPCZVN2C.js";
9
+ } from "../chunk-UONWZIBO.js";
10
10
  import {
11
11
  MARKETPLACE_DECIDE,
12
12
  MARKETPLACE_MANAGE,
@@ -20,7 +20,7 @@ import {
20
20
  upsertMarketplaceIntegrationsBody,
21
21
  upsertMarketplaceMenuLinksBody
22
22
  } from "../chunk-UYFYGGCS.js";
23
- import "../chunk-EBAIZQPB.js";
23
+ import "../chunk-FKUEFVVA.js";
24
24
  import "../chunk-7QVYU63E.js";
25
25
  export {
26
26
  MARKETPLACE_AVAILABILITY_ATTEMPTS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/marketplace",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "One marketplace integration engine for every marketplace: the durable inbox, the ingest pipeline, the acceptance clock and its sweep, the SKU map, the integration settings with sealed credentials, and the outbound engine (confirm, cancellation request, retries), behind an adapter port. Each marketplace is an adapter at its own subpath (./ifood, ./99food on Open Delivery, ./rappi). Framework-neutral wiring route descriptors (./server) with a Hono adapter (./hono), dep-free job blueprints, MCP tools and the package-owned Prisma partial + migrations.",
@@ -1,4 +1,5 @@
1
1
  import type { MarketplaceCatalogue } from "./catalogue-port";
2
+ import type { CatalogueReader } from "./catalogue-read-port";
2
3
  import type { MarketplaceAvailability } from "./pause-port";
3
4
  import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
4
5
 
@@ -184,6 +185,12 @@ export interface MarketplaceAdapter {
184
185
  * marketplace cannot be published to, and the host says so.
185
186
  */
186
187
  readonly catalogue?: MarketplaceCatalogue;
188
+ /**
189
+ * OPTIONAL. Reading the menu the store already keeps on this marketplace,
190
+ * through its own connection, for the host to import (FUT-951). Absent: the
191
+ * menu cannot be read through an API, and the host says so.
192
+ */
193
+ readonly catalogueReader?: CatalogueReader;
187
194
  /**
188
195
  * OPTIONAL. Closing the store on this marketplace for a while, and opening
189
196
  * it again (FUT-4851). Absent: the marketplace cannot be paused through an
@@ -0,0 +1,151 @@
1
+ import type { AdapterCallContext } from "./adapter";
2
+
3
+ /**
4
+ * The catalogue READ half of the adapter port (FUT-951): the menu a store
5
+ * already keeps on a marketplace, read through the store's own connection, so
6
+ * the host can import it (onboarding: "bring my menu over").
7
+ *
8
+ * The opposite direction of `catalogue-port.ts` and independent of it: an
9
+ * adapter may read a menu it cannot publish to, or publish to one it cannot
10
+ * read. Nothing here names a marketplace; each adapter maps its own catalogue
11
+ * into the {@link CatalogueSnapshot} below.
12
+ *
13
+ * Money is integer cents of the menu's currency ({@link centsFromMajor}).
14
+ * Nothing the adapter cannot map is dropped silently: a field it could not read
15
+ * is a {@link CatalogueReadWarning} on the item, and an item or category it
16
+ * could not read at all is a {@link CatalogueReadNotice} on the snapshot.
17
+ */
18
+
19
+ /** Why part of an item could not be mapped. Vocabulary, not copy: the host words it. */
20
+ export type CatalogueReadWarningCode =
21
+ /** The item carries no readable price: `priceCents` is null. */
22
+ | "PRICE_MISSING"
23
+ /** An option carries no readable price: its `priceDeltaCents` is null. */
24
+ | "OPTION_PRICE_MISSING"
25
+ /** A group of choices could not be read (no name, no options, bounds that make no sense): left out. */
26
+ | "OPTION_GROUP_UNREADABLE"
27
+ /** One choice of a group could not be read (no name): left out of its group. */
28
+ | "OPTION_UNREADABLE"
29
+ /** The photo reference is there but is not a path or URL the adapter can resolve: `photoUrl` is null. */
30
+ | "PHOTO_UNREADABLE"
31
+ /** The item is of a kind this reader maps only partly (a combo, a pizza by halves): read as a plain item. */
32
+ | "ITEM_TYPE_UNSUPPORTED";
33
+
34
+ /** One thing about an item the read could not map. */
35
+ export interface CatalogueReadWarning {
36
+ code: CatalogueReadWarningCode;
37
+ /** The marketplace's id of the group or option concerned, or null when it is the item itself. */
38
+ subject: string | null;
39
+ /** What the marketplace sent, for a developer (never shown as copy). */
40
+ detail: string | null;
41
+ }
42
+
43
+ /** One choice of a group: a size, a flavour, an add-on. */
44
+ export interface CatalogueSnapshotOption {
45
+ externalId: string;
46
+ /** The store's own code for it on the marketplace, when it set one. */
47
+ externalCode: string | null;
48
+ name: string;
49
+ description: string | null;
50
+ /** What choosing it adds to the item's price, in cents (0 = free); null when the marketplace sent none. */
51
+ priceDeltaCents: number | null;
52
+ photoUrl: string | null;
53
+ available: boolean;
54
+ }
55
+
56
+ /** A group of choices on an item: "Size" (min 1, max 1), "Extras" (min 0, max 3). */
57
+ export interface CatalogueSnapshotOptionGroup {
58
+ externalId: string;
59
+ externalCode: string | null;
60
+ name: string;
61
+ /** At least this many choices (0 = optional). */
62
+ min: number;
63
+ /** At most this many choices (always >= `min` and >= 1). */
64
+ max: number;
65
+ available: boolean;
66
+ options: CatalogueSnapshotOption[];
67
+ }
68
+
69
+ /** One item as the marketplace sells it. */
70
+ export interface CatalogueSnapshotItem {
71
+ externalId: string;
72
+ externalCode: string | null;
73
+ name: string;
74
+ description: string | null;
75
+ /** The item's own price in cents; null when the marketplace sent none (with a PRICE_MISSING warning). */
76
+ priceCents: number | null;
77
+ /** An absolute https URL of the photo, or null when the item has none. */
78
+ photoUrl: string | null;
79
+ /** Whether the marketplace sells it now (a paused item is still read). */
80
+ available: boolean;
81
+ optionGroups: CatalogueSnapshotOptionGroup[];
82
+ warnings: CatalogueReadWarning[];
83
+ }
84
+
85
+ /** One category, its items in the marketplace's order. */
86
+ export interface CatalogueSnapshotCategory {
87
+ externalId: string;
88
+ externalCode: string | null;
89
+ name: string;
90
+ available: boolean;
91
+ items: CatalogueSnapshotItem[];
92
+ }
93
+
94
+ /** An item or a category the read could not map at all, said rather than dropped. */
95
+ export interface CatalogueReadNotice {
96
+ code: "ITEM_UNREADABLE" | "CATEGORY_UNREADABLE";
97
+ /** The category it was found in (the category itself for CATEGORY_UNREADABLE), or null when it had no id. */
98
+ categoryExternalId: string | null;
99
+ /** The item's id, when it had one; null for a category. */
100
+ externalId: string | null;
101
+ detail: string;
102
+ }
103
+
104
+ /** The store's menu on a marketplace, as read. */
105
+ export interface CatalogueSnapshot {
106
+ categories: CatalogueSnapshotCategory[];
107
+ notices: CatalogueReadNotice[];
108
+ }
109
+
110
+ /**
111
+ * Why a read failed for good. Vocabulary, not copy.
112
+ * - `UNSUPPORTED`: the marketplace's adapter states no catalogue read.
113
+ * - `NOT_CONNECTED`: no live connection with a merchant id for that marketplace.
114
+ * - `CREDENTIALS`: no credentials on file, they do not open, or the marketplace refused them.
115
+ * - `NOT_AUTHORIZED`: the marketplace refused this merchant to this app (not
116
+ * authorized, the catalogue module not enabled, an unknown merchant id).
117
+ * - `REFUSED`: any other final refusal.
118
+ */
119
+ export type CatalogueReadRefusalCode = "UNSUPPORTED" | "NOT_CONNECTED" | "CREDENTIALS" | "NOT_AUTHORIZED" | "REFUSED";
120
+
121
+ /** What a read answers: the snapshot, a final refusal, or a failure worth asking again later (429, 5xx, a timeout). */
122
+ export type CatalogueReadResult =
123
+ | { kind: "snapshot"; snapshot: CatalogueSnapshot }
124
+ /** `status` and `message` are the marketplace's answer; null when the engine refused before calling. */
125
+ | { kind: "refused"; code: CatalogueReadRefusalCode; status: number | null; message: string | null }
126
+ | { kind: "retry"; reason: string };
127
+
128
+ /** What one catalogue read is handed: the outbound context plus the connection's merchant id. */
129
+ export interface CatalogueReadContext extends AdapterCallContext {
130
+ externalMerchantId: string;
131
+ }
132
+
133
+ /** A marketplace whose menu can be read. */
134
+ export interface CatalogueReader {
135
+ /** Read the whole menu. Never throws: a call with no answer is a `retry`. */
136
+ read(ctx: CatalogueReadContext): Promise<CatalogueReadResult>;
137
+ }
138
+
139
+ /**
140
+ * A price in the currency's MAJOR unit (`25.9`) as integer cents (`2590`), or
141
+ * null when it is not a finite, non-negative number.
142
+ *
143
+ * Rounding is explicit: the product is first cut to 12 significant digits,
144
+ * which removes binary floating-point error (`1.005 * 100` is
145
+ * `100.49999999999999`), and then rounded half up to the cent (`1.005` →
146
+ * `101`, `0.125` → `13`).
147
+ */
148
+ export function centsFromMajor(value: unknown): number | null {
149
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return null;
150
+ return Math.round(Number((value * 100).toPrecision(12)));
151
+ }
@@ -0,0 +1,51 @@
1
+ import type { CatalogueReadResult } from "./catalogue-read-port";
2
+ import { connectionMerchantId, readOutboundConnection } from "./integration";
3
+ import type { EngineContext } from "./ports";
4
+ import type { MarketplaceProvider } from "./types";
5
+
6
+ /**
7
+ * Reading the menu a store keeps on a marketplace, as a host calls it
8
+ * (FUT-951): through the store's OWN connection (its merchant id and its
9
+ * sealed credentials), with the adapter's `catalogueReader`. Nothing is
10
+ * stamped or queued: the read is a question the host asks while the store
11
+ * waits, and it answers the snapshot or why there is none.
12
+ */
13
+ export async function readMarketplaceCatalogue(
14
+ ctx: EngineContext,
15
+ input: { clientId: string; provider: MarketplaceProvider; now?: Date },
16
+ ): Promise<CatalogueReadResult> {
17
+ const reader = ctx.registry.get(input.provider)?.catalogueReader;
18
+ if (!reader) return engineRefusal("UNSUPPORTED");
19
+ const merchantId = await connectionMerchantId(ctx, input.clientId, input.provider);
20
+ if (merchantId === null) return engineRefusal("NOT_CONNECTED");
21
+ let connection: Awaited<ReturnType<typeof readOutboundConnection>>;
22
+ try {
23
+ connection = await readOutboundConnection(ctx, input.clientId, input.provider);
24
+ } catch (error) {
25
+ ctx.ports.logger.error(
26
+ `marketplace.catalogue-read: ${input.provider} credentials of ${input.clientId} do not open: ` +
27
+ (error instanceof Error ? error.message : String(error)),
28
+ );
29
+ return engineRefusal("CREDENTIALS");
30
+ }
31
+ if (!connection) return engineRefusal("CREDENTIALS");
32
+ try {
33
+ return await reader.read({
34
+ ...connection,
35
+ http: ctx.ports.http,
36
+ tokens: ctx.tokens,
37
+ now: input.now ?? ctx.ports.clock.now(),
38
+ externalMerchantId: merchantId,
39
+ });
40
+ } catch (error) {
41
+ // The port says an adapter never throws; one that does is asked again later, not crashed on.
42
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
43
+ }
44
+ }
45
+
46
+ const engineRefusal = (code: "UNSUPPORTED" | "NOT_CONNECTED" | "CREDENTIALS"): CatalogueReadResult => ({
47
+ kind: "refused",
48
+ code,
49
+ status: null,
50
+ message: null,
51
+ });
@@ -32,6 +32,8 @@ import {
32
32
  } from "./catalogue";
33
33
  import { runCatalogue, type CatalogueJobPayload, type CatalogueOutcome } from "./catalogue-job";
34
34
  import type { CatalogueMenuOptions } from "./catalogue-port";
35
+ import { readMarketplaceCatalogue } from "./catalogue-read";
36
+ import type { CatalogueReadResult } from "./catalogue-read-port";
35
37
  import type { CataloguePublicationView } from "./catalogue-store";
36
38
  import {
37
39
  runFetchOrder,
@@ -218,6 +220,12 @@ export interface MarketplaceEngine {
218
220
  provider: MarketplaceProvider;
219
221
  options: CatalogueMenuOptions;
220
222
  }): Promise<CatalogueDocumentResult>;
223
+ /**
224
+ * Read the menu the store keeps on a marketplace, through its own
225
+ * connection (FUT-951): the snapshot, a final refusal, or a `retry` (429,
226
+ * 5xx, a timeout). Calls the marketplace at once; nothing is queued.
227
+ */
228
+ readCatalogue(input: { clientId: string; provider: MarketplaceProvider; now?: Date }): Promise<CatalogueReadResult>;
221
229
  /** Run one queued publish or withdraw (the `marketplace.catalogue` job's body). */
222
230
  runCatalogue(payload: CatalogueJobPayload, attempt: OutboundAttempt): Promise<CatalogueOutcome>;
223
231
 
@@ -310,6 +318,7 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
310
318
  catalogueState: (input) => readCatalogueState(ctx, input),
311
319
  catalogueDocument: (input) => readCatalogueDocument(ctx, input),
312
320
  runCatalogue: (payload, attempt) => runCatalogue(ctx, payload, attempt),
321
+ readCatalogue: (input) => readMarketplaceCatalogue(ctx, input),
313
322
 
314
323
  pauseStore: (input) => pauseStore(ctx, input),
315
324
  resumeStore: (input) => resumeStore(ctx, input),
@@ -0,0 +1,187 @@
1
+ import { outboundResultOf, type MarketplaceHttpResponse, type OutboundResult } from "../core/adapter";
2
+ import type {
3
+ CatalogueReadContext,
4
+ CatalogueReader,
5
+ CatalogueReadNotice,
6
+ CatalogueReadResult,
7
+ CatalogueSnapshotCategory,
8
+ CatalogueSnapshotItem,
9
+ } from "../core/catalogue-read-port";
10
+ import { availableOf, entriesOf, indexOf, itemOf, record, text } from "./catalogue-snapshot";
11
+ import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
12
+
13
+ /**
14
+ * The iFood adapter's catalogue READ (FUT-951): the menu a store already keeps
15
+ * on iFood, read through the store's OWN connection (its merchant id, and the
16
+ * client-credentials token of its app, `bearer`), for the host to import.
17
+ *
18
+ * One read is, in order:
19
+ * 1. `GET /categories` — the merchant's categories (CONFIRMED, the Endpoints
20
+ * page as read 2026-11-13; ESTIMATED that it answers an array of
21
+ * `{ id, name, status, externalCode }`, the same estimate the push makes);
22
+ * 2. `GET /categories/{categoryId}/items` for each, in the list's order
23
+ * (CONFIRMED, the Introduction's step 5, read 2026-11-16), mapped by
24
+ * `./catalogue-snapshot.ts`.
25
+ *
26
+ * Pagination: none. The pages read show no page, size or cursor parameter on
27
+ * either call (ESTIMATED that there is none), so the menu is read one category
28
+ * per call, which bounds each answer by a category's size.
29
+ *
30
+ * Failures:
31
+ * - a 401 drops the cached token and asks once more with a fresh one (as the
32
+ * push's `call` does); a second 401 is a `retry`;
33
+ * - the token grant refused (400, 401, 403) is `CREDENTIALS`;
34
+ * - 403 (the Errors page: the app is not allowed this merchant, or the
35
+ * catalogue module is not enabled for it) and 404 on the category list (no
36
+ * such merchant for this app, ESTIMATED) are `NOT_AUTHORIZED`;
37
+ * - 429, 408, 425, 5xx and a call with no answer are `retry`;
38
+ * - any other 4xx is `REFUSED`, with iFood's words.
39
+ * A category whose own items answer 404 (deleted between the two calls), or
40
+ * answer in a shape other than `{ items: [...] }`, is left out with a
41
+ * CATEGORY_UNREADABLE notice rather than failing the read; an entry of a list
42
+ * that is not an object is a notice too. Only a category LIST that is not a
43
+ * list refuses the read (REFUSED): without it there is no menu to keep.
44
+ */
45
+
46
+ const catalogUrl = (merchantId: string, path: string): string =>
47
+ `${IFOOD_API}/catalog/v2.0/merchants/${encodeURIComponent(merchantId)}/${path}`;
48
+
49
+ type Failure = Exclude<CatalogueReadResult, { kind: "snapshot" }>;
50
+
51
+ /** The token grant's failure: a refusal is the store's credentials, anything else is asked again. */
52
+ function tokenFailure(result: OutboundResult): Failure {
53
+ if (result.kind === "refused") return { kind: "refused", code: "CREDENTIALS", status: result.status, message: result.message };
54
+ return { kind: "retry", reason: result.kind === "retry" ? result.reason : "unexpected token answer" };
55
+ }
56
+
57
+ /** A non-2xx catalogue answer as the failure it is. */
58
+ function failureOf(response: MarketplaceHttpResponse): Failure {
59
+ const result = outboundResultOf(response);
60
+ if (result.kind !== "refused") return { kind: "retry", reason: result.kind === "retry" ? result.reason : "unexpected answer" };
61
+ const code = response.status === 403 || response.status === 404 ? "NOT_AUTHORIZED" : "REFUSED";
62
+ return { kind: "refused", code, status: result.status, message: result.message };
63
+ }
64
+
65
+ /** One authenticated GET: iFood's answer (any status but 401), or the failure that ends the read. */
66
+ async function get(ctx: CatalogueReadContext, path: string): Promise<MarketplaceHttpResponse | Failure> {
67
+ for (let attempt = 0; attempt < 2; attempt += 1) {
68
+ const auth = await bearer(ctx);
69
+ if (!("token" in auth)) return tokenFailure(auth);
70
+ const response = await ctx.http({
71
+ method: "GET",
72
+ url: catalogUrl(ctx.externalMerchantId, path),
73
+ headers: { Authorization: `Bearer ${auth.token}`, Accept: "application/json" },
74
+ });
75
+ if (response.status !== 401) return response;
76
+ // A token that went stale under us: forget it, and the next turn grants another.
77
+ ctx.tokens.delete(ifoodTokenKey(ctx));
78
+ }
79
+ return { kind: "retry", reason: "iFood refused a fresh token" };
80
+ }
81
+
82
+ const ok = (response: MarketplaceHttpResponse): boolean => response.status >= 200 && response.status < 300;
83
+
84
+ function parse(body: string): unknown {
85
+ try {
86
+ return JSON.parse(body) as unknown;
87
+ } catch {
88
+ return null;
89
+ }
90
+ }
91
+
92
+ const unexpected = (what: string, body: string): Failure => ({
93
+ kind: "refused",
94
+ code: "REFUSED",
95
+ status: 200,
96
+ message: `unexpected ${what} answer: ${body.slice(0, 200)}`,
97
+ });
98
+
99
+ /** One category's items, or the notice that leaves the category out, or the failure that ends the read. */
100
+ async function categoryOf(
101
+ ctx: CatalogueReadContext,
102
+ raw: Record<string, unknown>,
103
+ notices: CatalogueReadNotice[],
104
+ ): Promise<CatalogueSnapshotCategory | null | Failure> {
105
+ const id = text(raw.id);
106
+ const name = text(raw.name);
107
+ if (id === null || name === null) {
108
+ notices.push(unreadableCategory(id, raw));
109
+ return null;
110
+ }
111
+ const answered = await get(ctx, `categories/${encodeURIComponent(id)}/items`);
112
+ if ("kind" in answered) return answered;
113
+ if (answered.status === 404) {
114
+ notices.push(unreadableCategory(id, "its items answered 404"));
115
+ return null;
116
+ }
117
+ if (!ok(answered)) return failureOf(answered);
118
+ const items = itemsOf(answered.body, id, notices);
119
+ return items && { externalId: id, externalCode: text(raw.externalCode), name, available: availableOf(raw.status), items };
120
+ }
121
+
122
+ const unreadableCategory = (categoryExternalId: string | null, detail: unknown): CatalogueReadNotice => ({
123
+ code: "CATEGORY_UNREADABLE",
124
+ categoryExternalId,
125
+ externalId: null,
126
+ detail: (typeof detail === "string" ? detail : JSON.stringify(detail) ?? String(detail)).slice(0, 300),
127
+ });
128
+
129
+ /**
130
+ * One category's items, each one it cannot read an ITEM_UNREADABLE notice; or
131
+ * null, with a CATEGORY_UNREADABLE notice, when the answer is not the expected
132
+ * `{ items: [...] }` (ESTIMATED: the PUT's four lists, `items` plural). A
133
+ * notice rather than refusing the whole read: one category answered in an odd
134
+ * shape keeps the rest of the menu importable, and the host shows which
135
+ * category did not come over; a shape iFood changed everywhere leaves a notice
136
+ * on every category, never a silent empty menu.
137
+ */
138
+ function itemsOf(rawBody: string, categoryId: string, notices: CatalogueReadNotice[]): CatalogueSnapshotItem[] | null {
139
+ const body = record(parse(rawBody));
140
+ if (!body || !Array.isArray(body.items)) {
141
+ notices.push(unreadableCategory(categoryId, `unexpected items answer: ${rawBody}`));
142
+ return null;
143
+ }
144
+ const index = indexOf(body);
145
+ const { entries, others } = entriesOf(body.items);
146
+ for (const other of others) {
147
+ notices.push({ code: "ITEM_UNREADABLE", categoryExternalId: categoryId, externalId: null, detail: String(JSON.stringify(other)).slice(0, 300) });
148
+ }
149
+ const items: CatalogueSnapshotItem[] = [];
150
+ for (const entry of entries) {
151
+ const mapped = itemOf(entry, index, categoryId);
152
+ if ("code" in mapped) notices.push(mapped);
153
+ else items.push(mapped);
154
+ }
155
+ return items;
156
+ }
157
+
158
+ async function read(ctx: CatalogueReadContext): Promise<CatalogueReadResult> {
159
+ const listed = await get(ctx, "categories");
160
+ if ("kind" in listed) return listed;
161
+ if (!ok(listed)) return failureOf(listed);
162
+ const parsed = parse(listed.body);
163
+ if (!Array.isArray(parsed)) return unexpected("category list", listed.body);
164
+ const categories: CatalogueSnapshotCategory[] = [];
165
+ const notices: CatalogueReadNotice[] = [];
166
+ const { entries, others } = entriesOf(parsed);
167
+ // A category entry that is not an object is said, never skipped.
168
+ for (const other of others) notices.push(unreadableCategory(null, other));
169
+ for (const raw of entries) {
170
+ const category = await categoryOf(ctx, raw, notices);
171
+ if (category === null) continue;
172
+ if ("kind" in category) return category;
173
+ categories.push(category);
174
+ }
175
+ return { kind: "snapshot", snapshot: { categories, notices } };
176
+ }
177
+
178
+ /** iFood's catalogue read. */
179
+ export const IFOOD_CATALOGUE_READER: CatalogueReader = {
180
+ read: async (ctx) => {
181
+ try {
182
+ return await read(ctx);
183
+ } catch (error) {
184
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
185
+ }
186
+ },
187
+ };