@12-apps/marketplace 1.18.1 → 1.19.1

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.1",
3
+ "version": "1.19.1",
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,
@@ -7,13 +7,18 @@
7
7
  * "no Route matched with those values").
8
8
  *
9
9
  * The catalog is the one whose `context` holds `DEFAULT` (delivery), as the
10
- * Fundamentals page names the contexts (DEFAULT, WHITELABEL, INDOOR).
10
+ * Fundamentals page names the contexts (DEFAULT, WHITELABEL, INDOOR). When
11
+ * more than one does, the first with `status: "AVAILABLE"` wins, else the
12
+ * first of them (FUT-6257; no answer with two has been seen, this is hardening).
11
13
  * Reproduced live against iFood's sandbox on 2026-12-03 (FUT-6146): the list
12
14
  * answered `[{ catalogId, context: ["DEFAULT"], status: "AVAILABLE", … }]`
13
15
  * and `…/catalogs/{catalogId}/categories` answered the categories.
14
16
  */
15
17
 
16
- /** The DEFAULT catalog's id in a `GET /catalogs` answer, or null when the answer names none. */
18
+ /**
19
+ * The DEFAULT catalog's id in a `GET /catalogs` answer: the first AVAILABLE
20
+ * one, else the first one; null when the answer names none.
21
+ */
17
22
  export function defaultCatalogIdIn(body: string): string | null {
18
23
  let parsed: unknown;
19
24
  try {
@@ -22,12 +27,16 @@ export function defaultCatalogIdIn(body: string): string | null {
22
27
  return null;
23
28
  }
24
29
  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;
30
+ const defaults = (parsed as unknown[]).map(defaultEntryOf).filter((entry) => entry !== null);
31
+ return (defaults.find((entry) => entry.available) ?? defaults[0])?.catalogId ?? null;
32
+ }
33
+
34
+ /** A `GET /catalogs` entry whose `context` holds DEFAULT, with whether iFood answers it AVAILABLE; null otherwise. */
35
+ function defaultEntryOf(entry: unknown): { catalogId: string; available: boolean } | null {
36
+ if (typeof entry !== "object" || entry === null) return null;
37
+ const { catalogId, context, status } = entry as { catalogId?: unknown; context?: unknown; status?: unknown };
38
+ if (typeof catalogId !== "string" || catalogId === "" || !Array.isArray(context) || !context.includes("DEFAULT")) return null;
39
+ return { catalogId, available: status === "AVAILABLE" };
31
40
  }
32
41
 
33
42
  /** The categories path of a catalog, relative to the merchant's base. */
@@ -135,36 +135,35 @@ async function findCategoryIn(ctx: CatalogueCallContext, catalogId: string, name
135
135
  return { id: categoryIdIn(listed.body, name) };
136
136
  }
137
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
-
144
138
  /**
145
139
  * Find the category by name, else create it, then read the list again and
146
140
  * adopt the first of that name: a POST whose answer was lost and was retried
147
141
  * is found rather than created twice. The engine runs this once per
148
- * (connection, name) at a time and stores the id (`ctx.category`).
142
+ * (connection, name) at a time and stores the id (`ctx.category`). A
143
+ * `catalogId` this publish already read is reused rather than read again.
149
144
  */
150
- async function findOrCreateCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string } | Failure> {
151
- const catalog = await catalogOf(ctx);
145
+ async function findOrCreateCategory(ctx: CatalogueCallContext, name: string, catalogId?: string): Promise<{ id: string } | Failure> {
146
+ const catalog = catalogId === undefined ? await catalogOf(ctx) : { catalogId };
152
147
  if ("kind" in catalog) return catalog;
153
148
  const found = await findCategoryIn(ctx, catalog.catalogId, name);
154
149
  if ("kind" in found) return found;
155
- if (found.id) return { id: found.id };
156
- const created = await call(ctx, "POST", categoriesPath(catalog.catalogId), { name, status: "AVAILABLE", template: "DEFAULT" });
150
+ return found.id ? { id: found.id } : createCategoryIn(ctx, catalog.catalogId, name);
151
+ }
152
+
153
+ /** Create the category in the catalog, then adopt the first of that name the list answers. */
154
+ async function createCategoryIn(ctx: CatalogueCallContext, catalogId: string, name: string): Promise<{ id: string } | Failure> {
155
+ const created = await call(ctx, "POST", categoriesPath(catalogId), { name, status: "AVAILABLE", template: "DEFAULT" });
157
156
  if ("kind" in created) return created;
158
157
  if (!ok(created)) return failureOf(created);
159
158
  const id = (parse(created.body) as { id?: unknown } | null)?.id;
160
159
  if (typeof id !== "string") return { kind: "retry", reason: "iFood created the category without an id" };
161
160
  // ESTIMATED: the list answers categories in creation order, so the first match is the oldest.
162
- const again = await findCategoryIn(ctx, catalog.catalogId, name);
161
+ const again = await findCategoryIn(ctx, catalogId, name);
163
162
  return "id" in again && again.id ? { id: again.id } : { id };
164
163
  }
165
164
 
166
- const categoryId = (ctx: CatalogueCallContext, name: string): Promise<{ id: string } | Failure> =>
167
- ctx.category(name, () => findOrCreateCategory(ctx, name));
165
+ const categoryId = (ctx: CatalogueCallContext, name: string, catalogId?: string): Promise<{ id: string } | Failure> =>
166
+ ctx.category(name, () => findOrCreateCategory(ctx, name, catalogId));
168
167
 
169
168
  /** The photo the item goes out with, and what the publish could not do about it. */
170
169
  interface PhotoOutcome {
@@ -239,13 +238,21 @@ export function ifoodItemBody(item: CatalogueItemOut, category: string, image: s
239
238
  * Whether a refused PUT was refused because the stored category is gone (the
240
239
  * store deleted it on iFood's portal): iFood's 400 and 404 do not say which id
241
240
  * was unknown, so the list is read again, and a category of that name with
242
- * another id, or none at all, means the stored one is stale. ESTIMATED that a
243
- * deleted category answers 400 or 404.
241
+ * another id, or none at all, means the stored one is stale. Answers the
242
+ * catalog it read when it is, so the find again reads no second `/catalogs`
243
+ * (FUT-6257); null otherwise. ESTIMATED that a deleted category answers 400 or 404.
244
244
  */
245
- async function categoryWentStale(ctx: CatalogueCallContext, put: MarketplaceHttpResponse, name: string, used: string): Promise<boolean> {
246
- if (put.status !== 400 && put.status !== 404) return false;
247
- const found = await findCategory(ctx, name);
248
- return !("kind" in found) && found.id !== used;
245
+ async function categoryWentStale(
246
+ ctx: CatalogueCallContext,
247
+ put: MarketplaceHttpResponse,
248
+ name: string,
249
+ used: string,
250
+ ): Promise<{ catalogId: string } | null> {
251
+ if (put.status !== 400 && put.status !== 404) return null;
252
+ const catalog = await catalogOf(ctx);
253
+ if ("kind" in catalog) return null;
254
+ const found = await findCategoryIn(ctx, catalog.catalogId, name);
255
+ return !("kind" in found) && found.id !== used ? catalog : null;
249
256
  }
250
257
 
251
258
  /** `PUT /items`, once more with the category found or created again when the stored one went stale. */
@@ -253,9 +260,11 @@ async function putItem(ctx: CatalogueCallContext, item: CatalogueItemOut, image:
253
260
  const category = await categoryId(ctx, item.categoryName);
254
261
  if ("kind" in category) return category;
255
262
  const put = await call(ctx, "PUT", "items", ifoodItemBody(item, category.id, image));
256
- if ("kind" in put || ok(put) || !(await categoryWentStale(ctx, put, item.categoryName, category.id))) return put;
263
+ if ("kind" in put || ok(put)) return put;
264
+ const stale = await categoryWentStale(ctx, put, item.categoryName, category.id);
265
+ if (stale === null) return put;
257
266
  await ctx.forgetCategory(item.categoryName);
258
- const again = await categoryId(ctx, item.categoryName);
267
+ const again = await categoryId(ctx, item.categoryName, stale.catalogId);
259
268
  if ("kind" in again) return again;
260
269
  return call(ctx, "PUT", "items", ifoodItemBody(item, again.id, image));
261
270
  }
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,