@12-apps/marketplace 1.18.0 → 1.19.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.
@@ -1,4 +1,4 @@
1
- import { aI as OutboundJobPayload, V as FetchOrderJobPayload, b as AcknowledgeJobPayload, l as CancellationReasonsJobPayload, u as CatalogueJobPayload, f as AvailabilityJobPayload, N as DisputeAnswerJobPayload } from '../engine-DRRhAjZK.js';
1
+ import { aK as OutboundJobPayload, V as FetchOrderJobPayload, b as AcknowledgeJobPayload, l as CancellationReasonsJobPayload, u as CatalogueJobPayload, f as AvailabilityJobPayload, N as DisputeAnswerJobPayload } from '../engine-CaiVufoP.js';
2
2
  import * as _12_apps_wiring from '@12-apps/wiring';
3
3
  import { createApiMarketplace, MarketplaceJobDeps } from '../server/index.js';
4
4
  import '../adapter-ZpAWKoCk.js';
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  MARKETPLACE_JOBS,
3
3
  createApiMarketplace
4
- } from "../chunk-BLHZ3MRB.js";
4
+ } from "../chunk-RS2QKQ6S.js";
5
5
  import "../chunk-LO7OKO6V.js";
6
- import "../chunk-MDEIRGNL.js";
6
+ import "../chunk-S2ISELNJ.js";
7
7
  import "../chunk-Q5RMVNU5.js";
8
8
  import "../chunk-7QVYU63E.js";
9
9
 
@@ -1,4 +1,4 @@
1
- import { J as DecisionProblemCode, j as BulkProblemCode, a4 as LinkRefusalCode, ap as MarketplaceEngine, av as MarketplaceLogger, aI as OutboundJobPayload, V as FetchOrderJobPayload, b as AcknowledgeJobPayload, l as CancellationReasonsJobPayload, u as CatalogueJobPayload, f as AvailabilityJobPayload, N as DisputeAnswerJobPayload } from '../engine-DRRhAjZK.js';
1
+ import { J as DecisionProblemCode, j as BulkProblemCode, a4 as LinkRefusalCode, aq as MarketplaceEngine, ax as MarketplaceLogger, aK as OutboundJobPayload, V as FetchOrderJobPayload, b as AcknowledgeJobPayload, l as CancellationReasonsJobPayload, u as CatalogueJobPayload, f as AvailabilityJobPayload, N as DisputeAnswerJobPayload } from '../engine-CaiVufoP.js';
2
2
  import { WireRoute, WireJobBlueprint } from '@12-apps/wiring';
3
3
  import { z } from 'zod';
4
4
  import '../adapter-ZpAWKoCk.js';
@@ -6,7 +6,7 @@ import {
6
6
  MARKETPLACE_SWEEP_QUEUE,
7
7
  ORDER_NOT_PENDING_CODE,
8
8
  createApiMarketplace
9
- } from "../chunk-BLHZ3MRB.js";
9
+ } from "../chunk-RS2QKQ6S.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-LO7OKO6V.js";
23
- import "../chunk-MDEIRGNL.js";
23
+ import "../chunk-S2ISELNJ.js";
24
24
  import "../chunk-Q5RMVNU5.js";
25
25
  import "../chunk-7QVYU63E.js";
26
26
  export {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/marketplace",
3
- "version": "1.18.0",
3
+ "version": "1.19.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 and ./keeta 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.",
package/src/core/bulk.ts CHANGED
@@ -5,7 +5,7 @@ import {
5
5
  type SaveMarketplaceIntegrationInput,
6
6
  } from "./integration";
7
7
  import { MarketplaceMerchantTakenError, isUniqueViolation, merchantHeldElsewhere } from "./merchant-claim";
8
- import { upsertLink, type MarketplaceMenuLinkView } from "./menu-links";
8
+ import { resolveLinkTargets, upsertLink, type MarketplaceMenuLinkView } from "./menu-links";
9
9
  import type { EngineContext, MarketplaceAuditEntry, MarketplaceDb } from "./ports";
10
10
 
11
11
  /**
@@ -243,7 +243,11 @@ async function linkRowProblems(
243
243
  return belongs ? [] : [{ path: variationPath, code: "CATALOG_ITEM_NOT_FOUND" }];
244
244
  }
245
245
 
246
- /** Map or unmap many SKUs at once; every catalog id (and variation) must be the store's. */
246
+ /**
247
+ * Map or unmap many SKUs at once; every catalog id (and variation) must be the store's.
248
+ * A row naming an id with no variation is first pointed where the host says
249
+ * that id really is (`order.resolveLinkTarget`), and the pair is checked.
250
+ */
247
251
  export async function upsertMenuLinks(
248
252
  ctx: EngineContext,
249
253
  input: { clientId: string; rows: readonly MenuLinkRowInput[]; validateOnly?: boolean },
@@ -252,13 +256,14 @@ export async function upsertMenuLinks(
252
256
  ...duplicates(input.rows, (row) => `${row.provider}\u0000${row.externalSku}`, "links", "externalSku"),
253
257
  ...unknownProviders(ctx, input.rows, "links"),
254
258
  ];
255
- for (const [index, row] of input.rows.entries()) problems.push(...(await linkRowProblems(ctx, input.clientId, row, index)));
259
+ const targets = await resolveLinkTargets(ctx, input.clientId, input.rows);
260
+ for (const [index, row] of targets.entries()) problems.push(...(await linkRowProblems(ctx, input.clientId, row, index)));
256
261
  if (problems.length > 0) return { kind: "refused", problems };
257
262
 
258
263
  const validateOnly = input.validateOnly === true;
259
264
  const written = await inTransaction(ctx, validateOnly, async (db) => {
260
265
  const rows: MarketplaceMenuLinkView[] = [];
261
- for (const row of input.rows) rows.push(await upsertLink(db, { clientId: input.clientId, ...row }));
266
+ for (const row of targets) rows.push(await upsertLink(db, { clientId: input.clientId, ...row }));
262
267
  return rows;
263
268
  });
264
269
  return { kind: "saved", validateOnly, rows: written ?? [] };
@@ -10,6 +10,7 @@ import {
10
10
  type CatalogueRow,
11
11
  type CatalogueTable,
12
12
  } from "./catalogue-store";
13
+ import { resolveLinkTargets } from "./menu-links";
13
14
  import type { EngineContext } from "./ports";
14
15
 
15
16
  /**
@@ -155,7 +156,8 @@ async function publishLateLanding(ctx: EngineContext, table: CatalogueTable, row
155
156
  * host's product, so those orders arrive mapped instead of on the attention
156
157
  * list — only when the SKU has no link yet, or an unmapped one: a store that
157
158
  * mapped it to another product on purpose keeps its own mapping. Kept on a
158
- * withdraw: an order placed before it still maps.
159
+ * withdraw: an order placed before it still maps. A product the host says is
160
+ * a variation of another (`order.resolveLinkTarget`) is linked as that pair.
159
161
  */
160
162
  async function mapPublishedSku(ctx: EngineContext, row: CatalogueRow, result: RunResult, name: string | undefined): Promise<void> {
161
163
  const sku = (result.kind === "published" ? result.sku : undefined) ?? row.productId;
@@ -165,10 +167,12 @@ async function mapPublishedSku(ctx: EngineContext, row: CatalogueRow, result: Ru
165
167
  menuItemId: string | null;
166
168
  }[];
167
169
  if (existing[0]?.menuItemId) return;
170
+ const [target] = await resolveLinkTargets(ctx, row.clientId, [{ menuItemId: row.productId, variationId: null }]);
171
+ const link = target?.variationId ? { menuItemId: target.menuItemId, variationId: target.variationId } : { menuItemId: row.productId };
168
172
  await db.marketplaceMenuLink.upsert({
169
173
  where: { clientId_provider_externalSku: key },
170
- create: { ...key, externalName: name ?? null, menuItemId: row.productId, lastSeenAt: ctx.ports.clock.now() },
171
- update: { menuItemId: row.productId },
174
+ create: { ...key, externalName: name ?? null, ...link, lastSeenAt: ctx.ports.clock.now() },
175
+ update: link,
172
176
  });
173
177
  }
174
178
 
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Where a menu link really points (FUT-6258). A host whose catalog lets one
3
+ * item be a variation of another can be handed an id that is the variation
4
+ * itself, with no variation named: a link stored that way names neither the
5
+ * item nor the variation the SKU means. The host answers where such an id
6
+ * points, and the engine stores that pair.
7
+ */
8
+
9
+ /** A link's stored target: the catalog item, and the variation of it the SKU names. */
10
+ export interface MarketplaceLinkTarget {
11
+ menuItemId: string;
12
+ variationId: string;
13
+ }
14
+
15
+ /** The order port's optional half for link targets. */
16
+ export interface LinkTargetOrderPort {
17
+ /**
18
+ * OPTIONAL. Where a link naming these catalog ids with no variation really
19
+ * points: for each id that is a variation of another item, that item and the
20
+ * variation; an id left out is stored as named. Asked ONCE per write, in
21
+ * bulk, before every menu-link write the engine makes (`upsertMenuLinks`,
22
+ * `setMenuLink`, the publish auto-link); the answer is then checked as any
23
+ * named pair is (`catalogHas`, `catalogHasVariation`). Absent: every link is
24
+ * stored exactly as named.
25
+ */
26
+ resolveLinkTarget?(clientId: string, subjectRefs: readonly string[]): Promise<ReadonlyMap<string, MarketplaceLinkTarget>>;
27
+ }
@@ -101,6 +101,27 @@ export async function listMarketplaceMenuLinks(
101
101
  return rows.map(toView);
102
102
  }
103
103
 
104
+ /**
105
+ * Rewrite the rows that name a catalog id with no variation to where the host
106
+ * says that id really points (`order.resolveLinkTarget`, FUT-6258): one bulk
107
+ * question for the whole write. Rows that name a variation, unmaps, ids the
108
+ * host leaves out, and every row of a host without the port pass unchanged.
109
+ */
110
+ export async function resolveLinkTargets<Row extends { menuItemId: string | null; variationId?: string | null }>(
111
+ ctx: EngineContext,
112
+ clientId: string,
113
+ rows: readonly Row[],
114
+ ): Promise<Row[]> {
115
+ const resolve = ctx.ports.order.resolveLinkTarget;
116
+ const asked = [...new Set(rows.flatMap((row) => (row.menuItemId !== null && (row.variationId ?? null) === null ? [row.menuItemId] : [])))];
117
+ if (!resolve || asked.length === 0) return [...rows];
118
+ const targets = await resolve.call(ctx.ports.order, clientId, asked);
119
+ return rows.map((row) => {
120
+ const target = row.menuItemId !== null && (row.variationId ?? null) === null ? targets.get(row.menuItemId) : undefined;
121
+ return target ? { ...row, menuItemId: target.menuItemId, variationId: target.variationId } : row;
122
+ });
123
+ }
124
+
104
125
  /**
105
126
  * Point an external SKU at a catalog id, or unmap it, inside the caller's
106
127
  * transaction. The caller has already checked the id is this tenant's
package/src/core/ports.ts CHANGED
@@ -5,6 +5,7 @@ import type { MarketplaceCourierAnswer, MarketplaceCourierFacts, PickupCodeValid
5
5
  import type { MarketplaceDisputeChange, MarketplaceDisputeDelegate } from "./dispute-port";
6
6
  import type { MarketplaceLifecycleAnswer, MarketplaceLifecycleFacts } from "./lifecycle-port";
7
7
  import type { MarketplaceAppCredentialsPort, MarketplaceLinkAttemptDelegate } from "./linking-port";
8
+ import type { LinkTargetOrderPort } from "./link-target-port";
8
9
  import type { LogisticsOrderPort, LogisticsPorts } from "./logistics";
9
10
  import type {
10
11
  CancellationFailureReason,
@@ -145,7 +146,7 @@ export interface MarketplaceAdmissionRequest {
145
146
  * transition has already been claimed and committed when they are called, and
146
147
  * a host that fails its half must not un-decide the acceptance.
147
148
  */
148
- export interface MarketplaceOrderPort extends LogisticsOrderPort {
149
+ export interface MarketplaceOrderPort extends LogisticsOrderPort, LinkTargetOrderPort {
149
150
  /**
150
151
  * Judge a decision BEFORE its claim commits, inside the claim's
151
152
  * transaction: the stock check (and the draw) of an accept, anything the
@@ -158,8 +159,7 @@ export interface MarketplaceOrderPort extends LogisticsOrderPort {
158
159
  /**
159
160
  * Turn a normalized order into whatever this host sells; hand back its id.
160
161
  * `db` is the ingest's transaction client (the host's `transaction` port):
161
- * write the order through it, so the order and the engine's acceptance row
162
- * commit together or not at all.
162
+ * write the order through it: the order and the engine's acceptance row commit together or not at all.
163
163
  */
164
164
  create(
165
165
  clientId: string,
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Which of a merchant's catalogs the catalogue read and push work in
3
+ * (FUT-6146). iFood's Catalog API v2.0 keeps categories UNDER a catalog:
4
+ * `GET /merchants/{merchantId}/catalogs` lists them, and the category list and
5
+ * create are `/merchants/{merchantId}/catalogs/{catalogId}/categories`; there
6
+ * is no merchant-level `/categories` route (iFood's gateway answers it 404,
7
+ * "no Route matched with those values").
8
+ *
9
+ * The catalog is the one whose `context` holds `DEFAULT` (delivery), as the
10
+ * Fundamentals page names the contexts (DEFAULT, WHITELABEL, INDOOR).
11
+ * Reproduced live against iFood's sandbox on 2026-12-03 (FUT-6146): the list
12
+ * answered `[{ catalogId, context: ["DEFAULT"], status: "AVAILABLE", … }]`
13
+ * and `…/catalogs/{catalogId}/categories` answered the categories.
14
+ */
15
+
16
+ /** The DEFAULT catalog's id in a `GET /catalogs` answer, or null when the answer names none. */
17
+ export function defaultCatalogIdIn(body: string): string | null {
18
+ let parsed: unknown;
19
+ try {
20
+ parsed = JSON.parse(body) as unknown;
21
+ } catch {
22
+ return null;
23
+ }
24
+ if (!Array.isArray(parsed)) return null;
25
+ for (const entry of parsed as unknown[]) {
26
+ if (typeof entry !== "object" || entry === null) continue;
27
+ const { catalogId, context } = entry as { catalogId?: unknown; context?: unknown };
28
+ if (typeof catalogId === "string" && catalogId !== "" && Array.isArray(context) && context.includes("DEFAULT")) return catalogId;
29
+ }
30
+ return null;
31
+ }
32
+
33
+ /** The categories path of a catalog, relative to the merchant's base. */
34
+ export const categoriesPath = (catalogId: string): string => `catalogs/${encodeURIComponent(catalogId)}/categories`;
@@ -7,6 +7,7 @@ import type {
7
7
  CatalogueSnapshotCategory,
8
8
  CatalogueSnapshotItem,
9
9
  } from "../core/catalogue-read-port";
10
+ import { categoriesPath, defaultCatalogIdIn } from "./catalogs";
10
11
  import { availableOf, entriesOf, indexOf, itemOf, record, text } from "./catalogue-snapshot";
11
12
  import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
12
13
 
@@ -16,12 +17,16 @@ import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
16
17
  * client-credentials token of its app, `bearer`), for the host to import.
17
18
  *
18
19
  * 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`.
20
+ * 1. `GET /catalogs` — the merchant's catalogs, of which the DEFAULT one is
21
+ * read (`./catalogs.ts`; CONFIRMED live against iFood's sandbox,
22
+ * 2026-12-03, FUT-6146);
23
+ * 2. `GET /catalogs/{catalogId}/categories` — its categories (CONFIRMED live,
24
+ * same run: the merchant-level `GET /categories` does not exist and
25
+ * answers 404; ESTIMATED that each entry is `{ id, name, status,
26
+ * externalCode }`, the same estimate the push makes);
27
+ * 3. `GET /categories/{categoryId}/items` for each, in the list's order
28
+ * (CONFIRMED, the Introduction's step 5, read 2026-11-16; merchant-level,
29
+ * not under the catalog), mapped by `./catalogue-snapshot.ts`.
25
30
  *
26
31
  * Pagination: none. The pages read show no page, size or cursor parameter on
27
32
  * either call (ESTIMATED that there is none), so the menu is read one category
@@ -32,8 +37,11 @@ import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
32
37
  * push's `call` does); a second 401 is a `retry`;
33
38
  * - the token grant refused (400, 401, 403) is `CREDENTIALS`;
34
39
  * - 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`;
40
+ * catalogue module is not enabled for it) is `NOT_AUTHORIZED`;
41
+ * - 404 on the catalog or category list is `REFUSED` with iFood's status and
42
+ * words: a path iFood does not have, or a resource it does not hold, is not
43
+ * a permission problem (FUT-6146: a wrong route read as "not authorized");
44
+ * - a catalog list naming no DEFAULT catalog is `REFUSED`;
37
45
  * - 429, 408, 425, 5xx and a call with no answer are `retry`;
38
46
  * - any other 4xx is `REFUSED`, with iFood's words.
39
47
  * A category whose own items answer 404 (deleted between the two calls), or
@@ -58,7 +66,8 @@ function tokenFailure(result: OutboundResult): Failure {
58
66
  function failureOf(response: MarketplaceHttpResponse): Failure {
59
67
  const result = outboundResultOf(response);
60
68
  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";
69
+ // Only a 403 is the merchant refusing this app; a 404 is a path or resource iFood does not have (FUT-6146).
70
+ const code = response.status === 403 ? "NOT_AUTHORIZED" : "REFUSED";
62
71
  return { kind: "refused", code, status: result.status, message: result.message };
63
72
  }
64
73
 
@@ -155,8 +164,19 @@ function itemsOf(rawBody: string, categoryId: string, notices: CatalogueReadNoti
155
164
  return items;
156
165
  }
157
166
 
167
+ /** The merchant's DEFAULT catalog id, or the failure that ends the read. */
168
+ async function catalogOf(ctx: CatalogueReadContext): Promise<{ catalogId: string } | Failure> {
169
+ const listed = await get(ctx, "catalogs");
170
+ if ("kind" in listed) return listed;
171
+ if (!ok(listed)) return failureOf(listed);
172
+ const catalogId = defaultCatalogIdIn(listed.body);
173
+ return catalogId === null ? unexpected("catalog list (no DEFAULT catalog)", listed.body) : { catalogId };
174
+ }
175
+
158
176
  async function read(ctx: CatalogueReadContext): Promise<CatalogueReadResult> {
159
- const listed = await get(ctx, "categories");
177
+ const catalog = await catalogOf(ctx);
178
+ if ("kind" in catalog) return catalog;
179
+ const listed = await get(ctx, categoriesPath(catalog.catalogId));
160
180
  if ("kind" in listed) return listed;
161
181
  if (!ok(listed)) return failureOf(listed);
162
182
  const parsed = parse(listed.body);
@@ -15,6 +15,7 @@ import type {
15
15
  CatalogueWarningCode,
16
16
  PushCatalogue,
17
17
  } from "../core/catalogue-port";
18
+ import { categoriesPath, defaultCatalogIdIn } from "./catalogs";
18
19
  import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
19
20
 
20
21
  /**
@@ -27,12 +28,17 @@ import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
27
28
  * it, and lives in this file only, so the homologation run corrects one file.
28
29
  *
29
30
  * One publish is, in order:
30
- * 1. the category, by name: `GET /categories`, else `POST /categories`
31
- * (`template: "DEFAULT"`);
31
+ * 1. the category, by name, in the merchant's DEFAULT catalog: `GET
32
+ * /catalogs` for its id (`./catalogs.ts`), then `GET
33
+ * /catalogs/{catalogId}/categories`, else `POST
34
+ * /catalogs/{catalogId}/categories` (`template: "DEFAULT"`). Categories
35
+ * live under a catalog: the merchant-level `/categories` route does not
36
+ * exist and answers 404 (CONFIRMED live against iFood's sandbox,
37
+ * 2026-12-03, FUT-6146);
32
38
  * 2. the photo, when the item has one: the `imagePath` iFood already holds
33
39
  * for the same photo URL, else `POST /image/upload` with a base64 data URL
34
40
  * of the bytes the host's loader reads, which answers `imagePath`;
35
- * 3. the item: `PUT /items` with `item`, `products`, `optionGroups`,
41
+ * 3. the item: `PUT /items` (merchant-level, like the photo and the status) with `item`, `products`, `optionGroups`,
36
42
  * `options` — idempotent, it replaces the whole item, and the item appears
37
43
  * at once (synchronous).
38
44
  *
@@ -110,14 +116,31 @@ function categoryIdIn(body: string, name: string): string | null {
110
116
  return typeof found?.id === "string" ? found.id : null;
111
117
  }
112
118
 
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");
119
+ /** The merchant's DEFAULT catalog id, or the failure that ends the publish. */
120
+ async function catalogOf(ctx: CatalogueCallContext): Promise<{ catalogId: string } | Failure> {
121
+ const listed = await call(ctx, "GET", "catalogs");
122
+ if ("kind" in listed) return listed;
123
+ if (!ok(listed)) return failureOf(listed);
124
+ const catalogId = defaultCatalogIdIn(listed.body);
125
+ return catalogId === null
126
+ ? { kind: "refused", status: listed.status, message: `no DEFAULT catalog: ${listed.body.slice(0, 200)}` }
127
+ : { catalogId };
128
+ }
129
+
130
+ /** The category named `name` in the catalog, or null; the failure that ended the read otherwise. */
131
+ async function findCategoryIn(ctx: CatalogueCallContext, catalogId: string, name: string): Promise<{ id: string | null } | Failure> {
132
+ const listed = await call(ctx, "GET", categoriesPath(catalogId));
116
133
  if ("kind" in listed) return listed;
117
134
  if (!ok(listed)) return failureOf(listed);
118
135
  return { id: categoryIdIn(listed.body, name) };
119
136
  }
120
137
 
138
+ /** The category named `name` in the merchant's DEFAULT catalog, or null; the failure otherwise. */
139
+ async function findCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string | null } | Failure> {
140
+ const catalog = await catalogOf(ctx);
141
+ return "kind" in catalog ? catalog : findCategoryIn(ctx, catalog.catalogId, name);
142
+ }
143
+
121
144
  /**
122
145
  * Find the category by name, else create it, then read the list again and
123
146
  * adopt the first of that name: a POST whose answer was lost and was retried
@@ -125,16 +148,18 @@ async function findCategory(ctx: CatalogueCallContext, name: string): Promise<{
125
148
  * (connection, name) at a time and stores the id (`ctx.category`).
126
149
  */
127
150
  async function findOrCreateCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string } | Failure> {
128
- const found = await findCategory(ctx, name);
151
+ const catalog = await catalogOf(ctx);
152
+ if ("kind" in catalog) return catalog;
153
+ const found = await findCategoryIn(ctx, catalog.catalogId, name);
129
154
  if ("kind" in found) return found;
130
155
  if (found.id) return { id: found.id };
131
- const created = await call(ctx, "POST", "categories", { name, status: "AVAILABLE", template: "DEFAULT" });
156
+ const created = await call(ctx, "POST", categoriesPath(catalog.catalogId), { name, status: "AVAILABLE", template: "DEFAULT" });
132
157
  if ("kind" in created) return created;
133
158
  if (!ok(created)) return failureOf(created);
134
159
  const id = (parse(created.body) as { id?: unknown } | null)?.id;
135
160
  if (typeof id !== "string") return { kind: "retry", reason: "iFood created the category without an id" };
136
161
  // ESTIMATED: the list answers categories in creation order, so the first match is the oldest.
137
- const again = await findCategory(ctx, name);
162
+ const again = await findCategoryIn(ctx, catalog.catalogId, name);
138
163
  return "id" in again && again.id ? { id: again.id } : { id };
139
164
  }
140
165
 
package/src/index.ts CHANGED
@@ -178,6 +178,7 @@ export type {
178
178
  NormalizedDisputeOpened,
179
179
  NormalizedDisputeSettled,
180
180
  } from "./core/dispute-port";
181
+ export type { LinkTargetOrderPort, MarketplaceLinkTarget } from "./core/link-target-port";
181
182
  export {
182
183
  MARKETPLACE_DISPUTE_ANSWER_JOB,
183
184
  disputeView,