@12-apps/marketplace 1.2.0 → 1.3.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 (56) hide show
  1. package/ADOPTING.md +29 -4
  2. package/README.md +92 -3
  3. package/dist/99food/index.d.ts +48 -2
  4. package/dist/99food/index.js +84 -1
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-_iuSxvVD.d.ts → adapter-0l_EmuJA.d.ts} +172 -2
  7. package/dist/{chunk-CRYFYDQ2.js → chunk-AYYBRQJV.js} +28 -4
  8. package/dist/chunk-AYYBRQJV.js.map +1 -0
  9. package/dist/chunk-M2V4RFMA.js +23 -0
  10. package/dist/chunk-M2V4RFMA.js.map +1 -0
  11. package/dist/{chunk-24RQZPSV.js → chunk-RVBTARIY.js} +1 -1
  12. package/dist/chunk-RVBTARIY.js.map +1 -0
  13. package/dist/{chunk-D2X7TOR6.js → chunk-XUAFXNOH.js} +449 -85
  14. package/dist/chunk-XUAFXNOH.js.map +1 -0
  15. package/dist/{engine-D-a4mttc.d.ts → engine-CZsP8KWd.d.ts} +222 -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 +10 -2
  19. package/dist/ifood/index.js +246 -69
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +30 -4
  22. package/dist/index.js +148 -9
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/server.d.ts +3 -2
  25. package/dist/manifest/server.js +2 -2
  26. package/dist/rappi/index.d.ts +1 -1
  27. package/dist/rappi/index.js +7 -1
  28. package/dist/rappi/index.js.map +1 -1
  29. package/dist/server/index.d.ts +12 -8
  30. package/dist/server/index.js +2 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +92 -1
  33. package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
  34. package/src/99food/catalogue.ts +117 -0
  35. package/src/99food/index.ts +4 -0
  36. package/src/99food/outbound.ts +3 -3
  37. package/src/core/adapter.ts +10 -1
  38. package/src/core/catalogue-category.ts +119 -0
  39. package/src/core/catalogue-ids.ts +23 -0
  40. package/src/core/catalogue-job.ts +332 -0
  41. package/src/core/catalogue-port.ts +173 -0
  42. package/src/core/catalogue-store.ts +172 -0
  43. package/src/core/catalogue-sweep.ts +43 -0
  44. package/src/core/catalogue.ts +226 -0
  45. package/src/core/engine.ts +46 -0
  46. package/src/core/outbound-sweep.ts +7 -2
  47. package/src/core/ports.ts +36 -0
  48. package/src/ifood/catalogue.ts +273 -0
  49. package/src/ifood/index.ts +4 -0
  50. package/src/ifood/outbound.ts +9 -6
  51. package/src/index.ts +40 -0
  52. package/src/rappi/index.ts +6 -0
  53. package/src/server/jobs.ts +39 -9
  54. package/dist/chunk-24RQZPSV.js.map +0 -1
  55. package/dist/chunk-CRYFYDQ2.js.map +0 -1
  56. package/dist/chunk-D2X7TOR6.js.map +0 -1
@@ -97,87 +97,65 @@ async function enqueueOutbound(ctx, payload, provider, dedupeKey = outboundDedup
97
97
  }
98
98
  __name(enqueueOutbound, "enqueueOutbound");
99
99
 
100
- // src/core/inbox.ts
101
- async function recordInboxEvent(ctx, input) {
102
- const db = await ctx.ports.db();
103
- const key = { provider_eventId: { provider: input.event.provider, eventId: input.event.eventId } };
104
- const existing = await db.marketplaceInboxEvent.findUnique({
105
- where: key,
106
- select: { id: true }
100
+ // src/core/catalogue-category.ts
101
+ var CLAIM_STALE_MS = 3 * 6e4;
102
+ async function claim(table, key, row, now) {
103
+ if (!row) {
104
+ try {
105
+ await table.create({ data: { ...key, claimedAt: now } });
106
+ return true;
107
+ } catch (error) {
108
+ if (error.code === "P2002") return false;
109
+ throw error;
110
+ }
111
+ }
112
+ const stale = new Date(now.getTime() - CLAIM_STALE_MS);
113
+ const moved = await table.updateMany({
114
+ where: { ...key, externalId: null, OR: [{ claimedAt: null }, { claimedAt: { lt: stale } }] },
115
+ data: { claimedAt: now }
107
116
  });
108
- if (existing) return { id: existing.id, fresh: false };
117
+ return moved.count > 0;
118
+ }
119
+ __name(claim, "claim");
120
+ async function release(table, key, claimedAt, id) {
121
+ if (id !== null) {
122
+ await table.updateMany({ where: { ...key, externalId: null }, data: { externalId: id, claimedAt: null } });
123
+ return;
124
+ }
125
+ await table.updateMany({ where: { ...key, externalId: null, claimedAt }, data: { claimedAt: null } });
126
+ }
127
+ __name(release, "release");
128
+ async function resolveCategory(ctx, connection, name, resolve, state = { waited: false }) {
129
+ const table = (await ctx.ports.db()).marketplaceCatalogueCategory;
130
+ if (!table) return resolve();
131
+ const key = { clientId: connection.clientId, provider: connection.provider, name: name.trim() };
132
+ const row = await table.findFirst({ where: key, select: { externalId: true } });
133
+ if (row?.externalId) return { id: row.externalId };
134
+ const now = ctx.ports.clock.now();
135
+ if (!await claim(table, key, row, now)) {
136
+ state.waited = true;
137
+ return { kind: "retry", reason: `another publish is creating the category "${key.name}"` };
138
+ }
139
+ let result = { kind: "retry", reason: "the category was not resolved" };
109
140
  try {
110
- const row = await db.marketplaceInboxEvent.create({
111
- data: {
112
- clientId: input.clientId,
113
- provider: input.event.provider,
114
- eventId: input.event.eventId,
115
- eventType: input.event.eventType,
116
- externalOrderId: input.event.externalOrderId,
117
- payload: input.payload,
118
- // The engine's clock, not the database's: an announced order's
119
- // acceptance window counts from here (`./fetch-order.ts`).
120
- receivedAt: ctx.ports.clock.now()
121
- },
122
- select: { id: true }
123
- });
124
- return { id: row.id, fresh: true };
141
+ result = await resolve();
125
142
  } catch (error) {
126
- if (error.code !== "P2002") throw error;
127
- const raced = await db.marketplaceInboxEvent.findUnique({
128
- where: key,
129
- select: { id: true }
130
- });
131
- return { id: raced?.id ?? "", fresh: false };
143
+ result = { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
144
+ } finally {
145
+ await release(table, key, now, "id" in result ? result.id : null);
132
146
  }
133
- }
134
- __name(recordInboxEvent, "recordInboxEvent");
135
- async function settleInboxEvent(ctx, id, outcome, error) {
136
- if (!id) return;
137
- const db = await ctx.ports.db();
138
- await db.marketplaceInboxEvent.update({
139
- where: { id },
140
- data: {
141
- status: outcome,
142
- // Truncated: a provider's error body can be a page of HTML, and the
143
- // column exists to be read by a human in a list.
144
- error: error ? error.slice(0, 500) : null,
145
- processedAt: ctx.ports.clock.now(),
146
- attempts: { increment: 1 }
147
- }
148
- });
149
- }
150
- __name(settleInboxEvent, "settleInboxEvent");
151
- async function deferInboxEvent(ctx, id, reason) {
152
- if (!id) return;
153
- const db = await ctx.ports.db();
154
- await db.marketplaceInboxEvent.update({
155
- where: { id },
156
- data: { error: reason.slice(0, 500), attempts: { increment: 1 } }
157
- });
158
- }
159
- __name(deferInboxEvent, "deferInboxEvent");
160
- async function listRetryableInboxEvents(ctx) {
161
- const db = await ctx.ports.db();
162
- const rows = await db.marketplaceInboxEvent.findMany({
163
- where: {
164
- status: { in: ["PENDING", "FAILED"] },
165
- clientId: { not: null },
166
- attempts: { lt: ctx.ports.maxInboxAttempts }
167
- },
168
- orderBy: { receivedAt: "asc" },
169
- take: ctx.ports.reconcileBatchSize,
170
- select: { id: true, clientId: true, provider: true, payload: true, receivedAt: true }
147
+ return result;
148
+ }
149
+ __name(resolveCategory, "resolveCategory");
150
+ async function forgetCategory(ctx, connection, name) {
151
+ const table = (await ctx.ports.db()).marketplaceCatalogueCategory;
152
+ if (!table) return;
153
+ await table.updateMany({
154
+ where: { clientId: connection.clientId, provider: connection.provider, name: name.trim() },
155
+ data: { externalId: null, claimedAt: null }
171
156
  });
172
- return rows.map((row) => ({
173
- id: row.id,
174
- clientId: row.clientId,
175
- provider: row.provider,
176
- payload: row.payload,
177
- receivedAt: row.receivedAt
178
- }));
179
157
  }
180
- __name(listRetryableInboxEvents, "listRetryableInboxEvents");
158
+ __name(forgetCategory, "forgetCategory");
181
159
 
182
160
  // src/core/integration.ts
183
161
  var VIEW_SELECT = {
@@ -327,6 +305,352 @@ async function readOutboundConnection(ctx, clientId, provider) {
327
305
  }
328
306
  __name(readOutboundConnection, "readOutboundConnection");
329
307
 
308
+ // src/core/catalogue-store.ts
309
+ var CATALOGUE_ROW_SELECT = {
310
+ id: true,
311
+ clientId: true,
312
+ provider: true,
313
+ productId: true,
314
+ status: true,
315
+ priceCents: true,
316
+ sentPriceCents: true,
317
+ externalId: true,
318
+ imageRef: true,
319
+ imageSourceUrl: true,
320
+ warningCode: true,
321
+ failedAction: true,
322
+ failureCode: true,
323
+ failureReason: true,
324
+ requestedAt: true,
325
+ publishedAt: true,
326
+ withdrawnAt: true,
327
+ failedAt: true
328
+ };
329
+ async function catalogueTable(ctx) {
330
+ return (await ctx.ports.db()).marketplaceCataloguePublication ?? null;
331
+ }
332
+ __name(catalogueTable, "catalogueTable");
333
+ function viewOf(row) {
334
+ return {
335
+ provider: row.provider,
336
+ productId: row.productId,
337
+ status: row.status,
338
+ priceCents: row.priceCents,
339
+ sentPriceCents: row.sentPriceCents,
340
+ externalId: row.externalId,
341
+ warningCode: row.warningCode,
342
+ failedAction: row.failedAction,
343
+ failureCode: row.failureCode,
344
+ failureReason: row.failureReason,
345
+ requestedAt: row.requestedAt,
346
+ publishedAt: row.publishedAt,
347
+ withdrawnAt: row.withdrawnAt,
348
+ failedAt: row.failedAt
349
+ };
350
+ }
351
+ __name(viewOf, "viewOf");
352
+ var NO_FAILURE = { failedAction: null, failureCode: null, failureReason: null, failedAt: null };
353
+ var REASON_LIMIT = 300;
354
+ function truncateReason(reason) {
355
+ return reason.length > REASON_LIMIT ? reason.slice(0, REASON_LIMIT) : reason;
356
+ }
357
+ __name(truncateReason, "truncateReason");
358
+ async function catalogueConnection(ctx, clientId, provider, categoryState) {
359
+ const merchantId = await connectionMerchantId(ctx, clientId, provider);
360
+ if (merchantId === null) return { problem: "NOT_CONNECTED" };
361
+ try {
362
+ const connection = await readOutboundConnection(ctx, clientId, provider);
363
+ if (!connection) return { problem: "CREDENTIALS" };
364
+ const catalogue = ctx.ports.catalogue;
365
+ return {
366
+ ...connection,
367
+ http: ctx.ports.http,
368
+ tokens: ctx.tokens,
369
+ externalMerchantId: merchantId,
370
+ loadImage: /* @__PURE__ */ __name((url) => catalogue ? catalogue.image(url) : Promise.resolve(null), "loadImage"),
371
+ category: /* @__PURE__ */ __name((name, resolve) => resolveCategory(ctx, { clientId, provider }, name, resolve, categoryState), "category"),
372
+ forgetCategory: /* @__PURE__ */ __name((name) => forgetCategory(ctx, { clientId, provider }, name), "forgetCategory")
373
+ };
374
+ } catch (error) {
375
+ ctx.ports.logger.error(
376
+ `marketplace.catalogue: ${provider} credentials of ${clientId} do not open: ${error instanceof Error ? error.message : String(error)}`
377
+ );
378
+ return { problem: "CREDENTIALS" };
379
+ }
380
+ }
381
+ __name(catalogueConnection, "catalogueConnection");
382
+
383
+ // src/core/catalogue-job.ts
384
+ var MARKETPLACE_CATALOGUE_JOB = "marketplace.catalogue";
385
+ var CatalogueRetryError = class extends Error {
386
+ static {
387
+ __name(this, "CatalogueRetryError");
388
+ }
389
+ constructor(message) {
390
+ super(message);
391
+ this.name = "CatalogueRetryError";
392
+ }
393
+ };
394
+ var WANTED = { publish: "PUBLISHING", withdraw: "WITHDRAWING" };
395
+ function catalogueDedupeKey(payload, requestedAt) {
396
+ return `${MARKETPLACE_CATALOGUE_JOB}:${payload.action}:${payload.publicationId}:${requestedAt.getTime()}`;
397
+ }
398
+ __name(catalogueDedupeKey, "catalogueDedupeKey");
399
+ async function enqueueCatalogue(ctx, payload, dedupeKey) {
400
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_CATALOGUE_JOB, payload, { dedupeKey });
401
+ if (outcome.enqueued) return;
402
+ ctx.ports.logger.warn(
403
+ `${MARKETPLACE_CATALOGUE_JOB}: ${payload.action} of ${payload.publicationId} was not queued; the outbound sweep will re-queue it` + (outcome.reason ? ` (${outcome.reason})` : "")
404
+ );
405
+ }
406
+ __name(enqueueCatalogue, "enqueueCatalogue");
407
+ async function callFor(ctx, row, action, catalogue, call) {
408
+ if (action === "withdraw") {
409
+ if (catalogue.mode === "pull") return { result: await catalogue.notifyMenuChanged(call), sentPriceCents: null };
410
+ const ref = { ref: row.id, productId: row.productId, externalId: row.externalId };
411
+ return { result: await catalogue.withdrawItem(call, ref), sentPriceCents: null };
412
+ }
413
+ const item = (await ctx.ports.catalogue?.items(row.clientId, [row.productId]))?.get(row.productId);
414
+ if (!item) return { code: "PRODUCT_GONE" };
415
+ const priceCents = row.priceCents ?? item.priceCents;
416
+ if (catalogue.mode === "pull") {
417
+ return { result: await catalogue.notifyMenuChanged(call), sentPriceCents: priceCents, name: item.name };
418
+ }
419
+ const storedImage = row.imageRef && row.imageSourceUrl ? { ref: row.imageRef, sourceUrl: row.imageSourceUrl } : null;
420
+ const out = { ...item, priceCents, ref: row.id, productId: row.productId, externalId: row.externalId, storedImage };
421
+ return { result: await catalogue.publishItem(call, out), sentPriceCents: priceCents, name: item.name };
422
+ }
423
+ __name(callFor, "callFor");
424
+ var stillAsked = /* @__PURE__ */ __name((row, action) => ({
425
+ id: row.id,
426
+ status: WANTED[action],
427
+ requestedAt: row.requestedAt
428
+ }), "stillAsked");
429
+ async function withdrawLateLanding(ctx, table, row, externalId) {
430
+ const now = ctx.ports.clock.now();
431
+ const moved = await table.updateMany({
432
+ where: { id: row.id, status: { in: ["WITHDRAWING", "WITHDRAWN"] } },
433
+ data: { status: "WITHDRAWING", requestedAt: now, ...externalId === null ? {} : { externalId } }
434
+ });
435
+ if (moved.count === 0) return;
436
+ const payload = { clientId: row.clientId, publicationId: row.id, action: "withdraw" };
437
+ await enqueueCatalogue(ctx, payload, catalogueDedupeKey(payload, now));
438
+ }
439
+ __name(withdrawLateLanding, "withdrawLateLanding");
440
+ async function publishLateLanding(ctx, table, row) {
441
+ const now = ctx.ports.clock.now();
442
+ const moved = await table.updateMany({
443
+ where: { id: row.id, status: { in: ["PUBLISHING", "PUBLISHED"] } },
444
+ data: { status: "PUBLISHING", requestedAt: now }
445
+ });
446
+ if (moved.count === 0) return;
447
+ const payload = { clientId: row.clientId, publicationId: row.id, action: "publish" };
448
+ await enqueueCatalogue(ctx, payload, catalogueDedupeKey(payload, now));
449
+ }
450
+ __name(publishLateLanding, "publishLateLanding");
451
+ async function mapPublishedSku(ctx, row, result, name) {
452
+ const sku = (result.kind === "published" ? result.sku : void 0) ?? row.productId;
453
+ const db = await ctx.ports.db();
454
+ const key = { clientId: row.clientId, provider: row.provider, externalSku: sku };
455
+ const existing = await db.marketplaceMenuLink.findMany({ where: key, select: { menuItemId: true }, take: 1 });
456
+ if (existing[0]?.menuItemId) return;
457
+ await db.marketplaceMenuLink.upsert({
458
+ where: { clientId_provider_externalSku: key },
459
+ create: { ...key, externalName: name ?? null, menuItemId: row.productId, lastSeenAt: ctx.ports.clock.now() },
460
+ update: { menuItemId: row.productId }
461
+ });
462
+ }
463
+ __name(mapPublishedSku, "mapPublishedSku");
464
+ function publishedExtras(result) {
465
+ if (result.kind !== "published") return { warningCode: null };
466
+ const image = result.image === void 0 ? {} : { imageRef: result.image?.ref ?? null, imageSourceUrl: result.image?.sourceUrl ?? null };
467
+ return { externalId: result.externalId, warningCode: result.warning ?? null, ...image };
468
+ }
469
+ __name(publishedExtras, "publishedExtras");
470
+ async function stampSuccess(ctx, table, row, action, result, sentPriceCents) {
471
+ const now = ctx.ports.clock.now();
472
+ const externalId = result.kind === "published" ? result.externalId : null;
473
+ const data = action === "publish" ? { status: "PUBLISHED", publishedAt: now, sentPriceCents, ...publishedExtras(result), ...NO_FAILURE } : { status: "WITHDRAWN", withdrawnAt: now, ...NO_FAILURE };
474
+ const moved = await table.updateMany({ where: stillAsked(row, action), data });
475
+ if (moved.count > 0) return;
476
+ if (action === "publish") await withdrawLateLanding(ctx, table, row, externalId);
477
+ else await publishLateLanding(ctx, table, row);
478
+ }
479
+ __name(stampSuccess, "stampSuccess");
480
+ async function stampFailure(table, row, action, failure, now) {
481
+ await table.updateMany({
482
+ where: stillAsked(row, action),
483
+ data: {
484
+ status: "FAILED",
485
+ failedAction: action === "publish" ? "PUBLISH" : "WITHDRAW",
486
+ failureCode: failure.code,
487
+ failureReason: failure.reason === null ? null : truncateReason(failure.reason),
488
+ failedAt: now
489
+ }
490
+ });
491
+ }
492
+ __name(stampFailure, "stampFailure");
493
+ function failureOf(result) {
494
+ if (result.kind === "retry") return { code: "UNAVAILABLE", reason: null };
495
+ return { code: "REFUSED", reason: result.message === "" ? null : result.message };
496
+ }
497
+ __name(failureOf, "failureOf");
498
+ async function runFor(ctx, row, action) {
499
+ const catalogue = ctx.registry.get(row.provider)?.catalogue;
500
+ if (!catalogue) return { code: "UNSUPPORTED" };
501
+ const categoryState = { waited: false };
502
+ const connection = await catalogueConnection(ctx, row.clientId, row.provider, categoryState);
503
+ if ("problem" in connection && connection.problem === "NOT_CONNECTED" && action === "withdraw") {
504
+ return { result: { kind: "accepted" }, sentPriceCents: null };
505
+ }
506
+ if ("problem" in connection) return { code: connection.problem };
507
+ const run = await callFor(ctx, row, action, catalogue, { ...connection, now: ctx.ports.clock.now() });
508
+ return "result" in run ? { ...run, waited: categoryState.waited } : run;
509
+ }
510
+ __name(runFor, "runFor");
511
+ function waitedOut(ctx, row, action, detail) {
512
+ ctx.ports.logger.warn(`${MARKETPLACE_CATALOGUE_JOB}: ${action} of ${row.productId} on ${row.provider} left for the sweep: ${detail}`);
513
+ return { kind: "skipped", reason: detail };
514
+ }
515
+ __name(waitedOut, "waitedOut");
516
+ async function fail(ctx, table, row, action, failure, detail) {
517
+ await stampFailure(table, row, action, failure, ctx.ports.clock.now());
518
+ ctx.ports.logger.error(`${MARKETPLACE_CATALOGUE_JOB}: ${action} of ${row.productId} on ${row.provider} failed (${failure.code}): ${detail}`);
519
+ ctx.ports.publishChanged(row.clientId);
520
+ return { kind: "failed", action, reason: failure.code };
521
+ }
522
+ __name(fail, "fail");
523
+ async function runOnce(ctx, table, payload, attempt) {
524
+ const row = await readRow(table, payload);
525
+ if (!row) return { kind: "skipped", reason: "no such publication for this tenant" };
526
+ const { action } = payload;
527
+ if (row.status !== WANTED[action]) return { kind: "skipped", reason: `the publication is ${row.status}, not ${WANTED[action]}` };
528
+ const run = await runFor(ctx, row, action);
529
+ if ("code" in run) return fail(ctx, table, row, action, { code: run.code, reason: null }, run.code);
530
+ return settle(ctx, table, row, action, run, attempt);
531
+ }
532
+ __name(runOnce, "runOnce");
533
+ async function settle(ctx, table, row, action, run, attempt) {
534
+ const { result } = run;
535
+ if (result.kind === "accepted" || result.kind === "published") {
536
+ await stampSuccess(ctx, table, row, action, result, run.sentPriceCents);
537
+ if (action === "publish") await mapPublishedSku(ctx, row, result, run.name);
538
+ ctx.ports.publishChanged(row.clientId);
539
+ return { kind: "done", action };
540
+ }
541
+ const detail = result.kind === "retry" ? result.reason : `refused ${result.status}: ${result.message}`;
542
+ if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
543
+ throw new CatalogueRetryError(`${action} of ${row.productId} on ${row.provider}: ${detail}`);
544
+ }
545
+ if (result.kind === "retry" && run.waited) return waitedOut(ctx, row, action, detail);
546
+ return fail(ctx, table, row, action, failureOf(result), detail);
547
+ }
548
+ __name(settle, "settle");
549
+ function readRow(table, payload) {
550
+ return table.findFirst({
551
+ where: { id: payload.publicationId, clientId: payload.clientId },
552
+ select: CATALOGUE_ROW_SELECT
553
+ });
554
+ }
555
+ __name(readRow, "readRow");
556
+ async function runCatalogue(ctx, payload, attempt) {
557
+ const table = await catalogueTable(ctx);
558
+ if (!table) return { kind: "skipped", reason: "the host has no catalogue table" };
559
+ try {
560
+ return await runOnce(ctx, table, payload, attempt);
561
+ } catch (error) {
562
+ if (error instanceof CatalogueRetryError || attempt.attempt < attempt.maxAttempts) throw error;
563
+ const detail = error instanceof Error ? error.message : String(error);
564
+ const row = await readRow(table, payload);
565
+ if (row && row.status === WANTED[payload.action]) return fail(ctx, table, row, payload.action, { code: "INTERNAL", reason: null }, detail);
566
+ ctx.ports.logger.error(`${MARKETPLACE_CATALOGUE_JOB}: ${payload.action} of ${payload.publicationId} failed: ${detail}`);
567
+ return { kind: "failed", action: payload.action, reason: "INTERNAL" };
568
+ }
569
+ }
570
+ __name(runCatalogue, "runCatalogue");
571
+
572
+ // src/core/inbox.ts
573
+ async function recordInboxEvent(ctx, input) {
574
+ const db = await ctx.ports.db();
575
+ const key = { provider_eventId: { provider: input.event.provider, eventId: input.event.eventId } };
576
+ const existing = await db.marketplaceInboxEvent.findUnique({
577
+ where: key,
578
+ select: { id: true }
579
+ });
580
+ if (existing) return { id: existing.id, fresh: false };
581
+ try {
582
+ const row = await db.marketplaceInboxEvent.create({
583
+ data: {
584
+ clientId: input.clientId,
585
+ provider: input.event.provider,
586
+ eventId: input.event.eventId,
587
+ eventType: input.event.eventType,
588
+ externalOrderId: input.event.externalOrderId,
589
+ payload: input.payload,
590
+ // The engine's clock, not the database's: an announced order's
591
+ // acceptance window counts from here (`./fetch-order.ts`).
592
+ receivedAt: ctx.ports.clock.now()
593
+ },
594
+ select: { id: true }
595
+ });
596
+ return { id: row.id, fresh: true };
597
+ } catch (error) {
598
+ if (error.code !== "P2002") throw error;
599
+ const raced = await db.marketplaceInboxEvent.findUnique({
600
+ where: key,
601
+ select: { id: true }
602
+ });
603
+ return { id: raced?.id ?? "", fresh: false };
604
+ }
605
+ }
606
+ __name(recordInboxEvent, "recordInboxEvent");
607
+ async function settleInboxEvent(ctx, id, outcome, error) {
608
+ if (!id) return;
609
+ const db = await ctx.ports.db();
610
+ await db.marketplaceInboxEvent.update({
611
+ where: { id },
612
+ data: {
613
+ status: outcome,
614
+ // Truncated: a provider's error body can be a page of HTML, and the
615
+ // column exists to be read by a human in a list.
616
+ error: error ? error.slice(0, 500) : null,
617
+ processedAt: ctx.ports.clock.now(),
618
+ attempts: { increment: 1 }
619
+ }
620
+ });
621
+ }
622
+ __name(settleInboxEvent, "settleInboxEvent");
623
+ async function deferInboxEvent(ctx, id, reason) {
624
+ if (!id) return;
625
+ const db = await ctx.ports.db();
626
+ await db.marketplaceInboxEvent.update({
627
+ where: { id },
628
+ data: { error: reason.slice(0, 500), attempts: { increment: 1 } }
629
+ });
630
+ }
631
+ __name(deferInboxEvent, "deferInboxEvent");
632
+ async function listRetryableInboxEvents(ctx) {
633
+ const db = await ctx.ports.db();
634
+ const rows = await db.marketplaceInboxEvent.findMany({
635
+ where: {
636
+ status: { in: ["PENDING", "FAILED"] },
637
+ clientId: { not: null },
638
+ attempts: { lt: ctx.ports.maxInboxAttempts }
639
+ },
640
+ orderBy: { receivedAt: "asc" },
641
+ take: ctx.ports.reconcileBatchSize,
642
+ select: { id: true, clientId: true, provider: true, payload: true, receivedAt: true }
643
+ });
644
+ return rows.map((row) => ({
645
+ id: row.id,
646
+ clientId: row.clientId,
647
+ provider: row.provider,
648
+ payload: row.payload,
649
+ receivedAt: row.receivedAt
650
+ }));
651
+ }
652
+ __name(listRetryableInboxEvents, "listRetryableInboxEvents");
653
+
330
654
  // src/core/menu-links.ts
331
655
  var LINK_SELECT = {
332
656
  id: true,
@@ -889,6 +1213,33 @@ async function runFetchOrder(ctx, payload, attempt) {
889
1213
  }
890
1214
  __name(runFetchOrder, "runFetchOrder");
891
1215
 
1216
+ // src/core/catalogue-sweep.ts
1217
+ var CATALOGUE_STALE_MS = 10 * 6e4;
1218
+ var CATALOGUE_GIVE_UP_MS = 24 * 60 * 6e4;
1219
+ async function sweepCatalogue(ctx, now) {
1220
+ const table = await catalogueTable(ctx);
1221
+ if (!table) return 0;
1222
+ const stale = new Date(now.getTime() - CATALOGUE_STALE_MS);
1223
+ const giveUp = new Date(now.getTime() - CATALOGUE_GIVE_UP_MS);
1224
+ for (const [status, failedAction] of [["PUBLISHING", "PUBLISH"], ["WITHDRAWING", "WITHDRAW"]]) {
1225
+ await table.updateMany({
1226
+ where: { status, requestedAt: { lt: giveUp } },
1227
+ data: { status: "FAILED", failedAction, failureCode: "TIMEOUT", failureReason: null, failedAt: now }
1228
+ });
1229
+ }
1230
+ const rows = await table.findMany({
1231
+ where: { status: { in: ["PUBLISHING", "WITHDRAWING"] }, requestedAt: { lt: stale, gte: giveUp } },
1232
+ select: CATALOGUE_ROW_SELECT
1233
+ });
1234
+ for (const row of rows) {
1235
+ const action = row.status === "PUBLISHING" ? "publish" : "withdraw";
1236
+ const payload = { clientId: row.clientId, publicationId: row.id, action };
1237
+ await enqueueCatalogue(ctx, payload, `${catalogueDedupeKey(payload, row.requestedAt)}:sweep:${now.getTime()}`);
1238
+ }
1239
+ return rows.length;
1240
+ }
1241
+ __name(sweepCatalogue, "sweepCatalogue");
1242
+
892
1243
  // src/core/outbound-sweep.ts
893
1244
  var OUTBOUND_STALE_MS = 10 * 6e4;
894
1245
  var OUTBOUND_GIVE_UP_MS = 24 * 60 * 6e4;
@@ -967,7 +1318,8 @@ async function sweepOutbound(ctx, now) {
967
1318
  });
968
1319
  const requeued = await requeue(ctx, cancellations, "requestCancellation", now) + await requeue(ctx, confirms, "confirm", now);
969
1320
  if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} cancellation request(s).`);
970
- return { requeued, givenUp, timedOut };
1321
+ const catalogueRequeued = await sweepCatalogue(ctx, now);
1322
+ return { requeued, givenUp, timedOut, catalogueRequeued };
971
1323
  }
972
1324
  __name(sweepOutbound, "sweepOutbound");
973
1325
 
@@ -1070,7 +1422,7 @@ async function connectionFor(ctx, clientId, provider) {
1070
1422
  }
1071
1423
  }
1072
1424
  __name(connectionFor, "connectionFor");
1073
- async function settle(ctx, payload, row, result, attempt, succeed, fail) {
1425
+ async function settle2(ctx, payload, row, result, attempt, succeed, fail2) {
1074
1426
  if (result.kind === "accepted") {
1075
1427
  await succeed();
1076
1428
  ctx.ports.publishChanged(payload.clientId);
@@ -1080,12 +1432,12 @@ async function settle(ctx, payload, row, result, attempt, succeed, fail) {
1080
1432
  if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
1081
1433
  throw new OutboundRetryError(`${payload.action} for order ${row.orderId}: ${reason}`);
1082
1434
  }
1083
- await fail();
1435
+ await fail2();
1084
1436
  ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${row.orderId} failed: ${reason}`);
1085
1437
  ctx.ports.publishChanged(payload.clientId);
1086
1438
  return { kind: "failed", action: payload.action, reason };
1087
1439
  }
1088
- __name(settle, "settle");
1440
+ __name(settle2, "settle");
1089
1441
  async function runConfirm(ctx, payload, row, adapter, attempt) {
1090
1442
  const skip = confirmSkip(row, adapter);
1091
1443
  if (skip) return { kind: "skipped", reason: skip };
@@ -1097,7 +1449,7 @@ async function runConfirm(ctx, payload, row, adapter, attempt) {
1097
1449
  // The stated preparation time, for a marketplace whose confirm takes one.
1098
1450
  { preparationMinutes: adapter.capabilities.confirmTakesPreparationTime ? row.preparationMinutes : null }
1099
1451
  );
1100
- return settle(
1452
+ return settle2(
1101
1453
  ctx,
1102
1454
  payload,
1103
1455
  row,
@@ -1140,7 +1492,7 @@ async function runCancellation(ctx, payload, row, adapter, attempt) {
1140
1492
  );
1141
1493
  }
1142
1494
  const taken = adapter.capabilities.asyncCancellationOutcome ? "REQUESTED" : "CONFIRMED";
1143
- return settle(
1495
+ return settle2(
1144
1496
  ctx,
1145
1497
  payload,
1146
1498
  row,
@@ -1169,7 +1521,7 @@ async function stampLastAttemptFailure(ctx, payload, error) {
1169
1521
  return { kind: "failed", action: payload.action, reason };
1170
1522
  }
1171
1523
  __name(stampLastAttemptFailure, "stampLastAttemptFailure");
1172
- async function runOnce(ctx, payload, attempt) {
1524
+ async function runOnce2(ctx, payload, attempt) {
1173
1525
  const db = await ctx.ports.db();
1174
1526
  const row = await db.marketplaceAcceptance.findFirst({
1175
1527
  where: { orderId: payload.orderId, clientId: payload.clientId },
@@ -1180,10 +1532,10 @@ async function runOnce(ctx, payload, attempt) {
1180
1532
  if (!adapter) return { kind: "skipped", reason: `no adapter for ${row.provider}` };
1181
1533
  return payload.action === "confirm" ? runConfirm(ctx, payload, row, adapter, attempt) : runCancellation(ctx, payload, row, adapter, attempt);
1182
1534
  }
1183
- __name(runOnce, "runOnce");
1535
+ __name(runOnce2, "runOnce");
1184
1536
  async function runOutbound(ctx, payload, attempt) {
1185
1537
  try {
1186
- return await runOnce(ctx, payload, attempt);
1538
+ return await runOnce2(ctx, payload, attempt);
1187
1539
  } catch (error) {
1188
1540
  if (error instanceof OutboundRetryError || attempt.attempt < attempt.maxAttempts) throw error;
1189
1541
  return stampLastAttemptFailure(ctx, payload, error);
@@ -1219,6 +1571,16 @@ export {
1219
1571
  MARKETPLACE_OUTBOUND_JOB,
1220
1572
  outboundDedupeKey,
1221
1573
  enqueueOutbound,
1574
+ CATALOGUE_ROW_SELECT,
1575
+ catalogueTable,
1576
+ viewOf,
1577
+ NO_FAILURE,
1578
+ catalogueConnection,
1579
+ MARKETPLACE_CATALOGUE_JOB,
1580
+ CatalogueRetryError,
1581
+ catalogueDedupeKey,
1582
+ enqueueCatalogue,
1583
+ runCatalogue,
1222
1584
  recordInboxEvent,
1223
1585
  settleInboxEvent,
1224
1586
  deferInboxEvent,
@@ -1231,10 +1593,12 @@ export {
1231
1593
  requeueOwedFetch,
1232
1594
  merchantMismatch,
1233
1595
  runFetchOrder,
1596
+ CATALOGUE_STALE_MS,
1597
+ CATALOGUE_GIVE_UP_MS,
1234
1598
  OUTBOUND_STALE_MS,
1235
1599
  OUTBOUND_GIVE_UP_MS,
1236
1600
  sweepOutbound,
1237
1601
  OutboundRetryError,
1238
1602
  runOutbound
1239
1603
  };
1240
- //# sourceMappingURL=chunk-D2X7TOR6.js.map
1604
+ //# sourceMappingURL=chunk-XUAFXNOH.js.map