@12-apps/marketplace 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/ADOPTING.md +76 -4
  2. package/README.md +163 -3
  3. package/dist/99food/index.d.ts +79 -2
  4. package/dist/99food/index.js +117 -2
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/adapter-B8QtQ2RA.d.ts +612 -0
  7. package/dist/{chunk-CRYFYDQ2.js → chunk-DPCZVN2C.js} +69 -5
  8. package/dist/chunk-DPCZVN2C.js.map +1 -0
  9. package/dist/{chunk-D2X7TOR6.js → chunk-EBAIZQPB.js} +841 -86
  10. package/dist/chunk-EBAIZQPB.js.map +1 -0
  11. package/dist/chunk-M2V4RFMA.js +23 -0
  12. package/dist/chunk-M2V4RFMA.js.map +1 -0
  13. package/dist/{chunk-24RQZPSV.js → chunk-SZRZTLVU.js} +1 -1
  14. package/dist/chunk-SZRZTLVU.js.map +1 -0
  15. package/dist/{engine-D-a4mttc.d.ts → engine-o5cm54vC.d.ts} +462 -2
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +2 -2
  18. package/dist/ifood/index.d.ts +22 -2
  19. package/dist/ifood/index.js +396 -56
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +30 -4
  22. package/dist/index.js +445 -9
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/server.d.ts +5 -2
  25. package/dist/manifest/server.js +2 -2
  26. package/dist/rappi/index.d.ts +15 -2
  27. package/dist/rappi/index.js +62 -2
  28. package/dist/rappi/index.js.map +1 -1
  29. package/dist/server/index.d.ts +25 -10
  30. package/dist/server/index.js +4 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +158 -1
  33. package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
  34. package/prisma/migrations/20261113230000_marketplace_store_pause/migration.sql +70 -0
  35. package/src/99food/catalogue.ts +117 -0
  36. package/src/99food/index.ts +14 -0
  37. package/src/99food/outbound.ts +3 -3
  38. package/src/99food/pause.ts +56 -0
  39. package/src/core/adapter.ts +20 -1
  40. package/src/core/catalogue-category.ts +119 -0
  41. package/src/core/catalogue-ids.ts +23 -0
  42. package/src/core/catalogue-job.ts +332 -0
  43. package/src/core/catalogue-port.ts +173 -0
  44. package/src/core/catalogue-store.ts +172 -0
  45. package/src/core/catalogue-sweep.ts +43 -0
  46. package/src/core/catalogue.ts +226 -0
  47. package/src/core/engine.ts +83 -0
  48. package/src/core/outbound-sweep.ts +7 -2
  49. package/src/core/pause-job.ts +381 -0
  50. package/src/core/pause-port.ts +110 -0
  51. package/src/core/pause-retired.ts +139 -0
  52. package/src/core/pause-store.ts +151 -0
  53. package/src/core/pause-sweep.ts +148 -0
  54. package/src/core/pause.ts +316 -0
  55. package/src/core/ports.ts +47 -0
  56. package/src/ifood/catalogue.ts +273 -0
  57. package/src/ifood/index.ts +8 -0
  58. package/src/ifood/outbound.ts +9 -6
  59. package/src/ifood/pause.ts +257 -0
  60. package/src/index.ts +64 -0
  61. package/src/rappi/index.ts +17 -0
  62. package/src/rappi/outbound.ts +2 -2
  63. package/src/rappi/pause.ts +98 -0
  64. package/src/server/index.ts +1 -0
  65. package/src/server/jobs.ts +100 -10
  66. package/dist/adapter-_iuSxvVD.d.ts +0 -319
  67. package/dist/chunk-24RQZPSV.js.map +0 -1
  68. package/dist/chunk-CRYFYDQ2.js.map +0 -1
  69. package/dist/chunk-D2X7TOR6.js.map +0 -1
@@ -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 } }
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 }
157
156
  });
158
157
  }
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 }
171
- });
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
- }
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, fail3) {
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 fail3();
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);
@@ -1191,6 +1543,387 @@ async function runOutbound(ctx, payload, attempt) {
1191
1543
  }
1192
1544
  __name(runOutbound, "runOutbound");
1193
1545
 
1546
+ // src/core/pause-store.ts
1547
+ import { randomUUID } from "crypto";
1548
+ var MARKETPLACE_AVAILABILITY_JOB = "marketplace.availability";
1549
+ var STORE_PAUSE_LEASE_MS = 2 * 6e4;
1550
+ var DETAIL_MAX = 300;
1551
+ function pauseTable(db) {
1552
+ const table = db.marketplaceStorePause;
1553
+ if (!table) {
1554
+ throw new Error(
1555
+ "@12-apps/marketplace: the store pause needs the MarketplaceStorePause model (migration 20261113230000_marketplace_store_pause); compose the partial and migrate."
1556
+ );
1557
+ }
1558
+ return table;
1559
+ }
1560
+ __name(pauseTable, "pauseTable");
1561
+ function hasPauseTable(db) {
1562
+ return db.marketplaceStorePause !== void 0;
1563
+ }
1564
+ __name(hasPauseTable, "hasPauseTable");
1565
+ async function readPause(ctx, clientId, provider) {
1566
+ const table = pauseTable(await ctx.ports.db());
1567
+ return await table.findFirst({ where: { clientId, provider } });
1568
+ }
1569
+ __name(readPause, "readPause");
1570
+ function holdsSomething(row) {
1571
+ const retired = row.retiredExternalIds !== null && row.retiredExternalIds.trim() !== "";
1572
+ return row.externalId !== null || row.sentUntil !== null || row.attemptKey !== null || retired;
1573
+ }
1574
+ __name(holdsSomething, "holdsSomething");
1575
+ function newAttemptKey() {
1576
+ return randomUUID();
1577
+ }
1578
+ __name(newAttemptKey, "newAttemptKey");
1579
+ function detailOf(message) {
1580
+ return message.slice(0, DETAIL_MAX);
1581
+ }
1582
+ __name(detailOf, "detailOf");
1583
+ function availabilityDedupeKey(payload, requestedAt, suffix = "") {
1584
+ return `${MARKETPLACE_AVAILABILITY_JOB}:${payload.clientId}:${payload.provider}:${requestedAt.getTime()}${suffix}`;
1585
+ }
1586
+ __name(availabilityDedupeKey, "availabilityDedupeKey");
1587
+ async function enqueueAvailability(ctx, payload, dedupeKey) {
1588
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_AVAILABILITY_JOB, payload, { dedupeKey });
1589
+ if (!outcome.enqueued) {
1590
+ ctx.ports.logger.warn(
1591
+ `${MARKETPLACE_AVAILABILITY_JOB}: ${payload.provider} for ${payload.clientId} was not queued; the sweep will re-queue it` + (outcome.reason ? ` (${outcome.reason})` : "")
1592
+ );
1593
+ }
1594
+ return outcome.enqueued;
1595
+ }
1596
+ __name(enqueueAvailability, "enqueueAvailability");
1597
+
1598
+ // src/core/pause-retired.ts
1599
+ var RETIRED_CAP = 10;
1600
+ function parse(token) {
1601
+ const at = token.lastIndexOf("@");
1602
+ const head = at === -1 ? token : token.slice(0, at);
1603
+ const end = at === -1 ? null : new Date(token.slice(at + 1));
1604
+ const valid = end !== null && !Number.isNaN(end.getTime()) ? end : null;
1605
+ if (head.startsWith("key:")) return { by: "key", value: head.slice(4), end: valid };
1606
+ const value = head.startsWith("id:") ? head.slice(3) : head;
1607
+ return value === "" ? null : { by: "id", value, end: valid };
1608
+ }
1609
+ __name(parse, "parse");
1610
+ function retiredOf(row) {
1611
+ return (row.retiredExternalIds ?? "").split(" ").filter((token) => token !== "").map(parse).filter((entry) => entry !== null);
1612
+ }
1613
+ __name(retiredOf, "retiredOf");
1614
+ function retiredValue(list) {
1615
+ if (list.length === 0) return null;
1616
+ return list.map((entry) => `${entry.by}:${entry.value}${entry.end ? `@${entry.end.toISOString()}` : ""}`).join(" ");
1617
+ }
1618
+ __name(retiredValue, "retiredValue");
1619
+ function withRetired(ctx, row, entry) {
1620
+ const list = [...retiredOf(row), entry];
1621
+ const dropped = list.splice(0, Math.max(0, list.length - RETIRED_CAP));
1622
+ for (const gone of dropped) {
1623
+ ctx.ports.logger.warn(
1624
+ `marketplace.availability: ${row.provider} for ${row.clientId}: more than ${RETIRED_CAP} replaced closures; ${gone.by} ${gone.value} is no longer deleted (it ends on its own${gone.end ? ` at ${gone.end.toISOString()}` : ""})`
1625
+ );
1626
+ }
1627
+ return list;
1628
+ }
1629
+ __name(withRetired, "withRetired");
1630
+ var ended = /* @__PURE__ */ __name((entry, now) => entry.end !== null && entry.end.getTime() <= now.getTime(), "ended");
1631
+ function heldIds(row) {
1632
+ const replaced = retiredOf(row).filter((entry) => entry.by === "id").map((entry) => entry.value);
1633
+ return row.externalId === null ? replaced : [row.externalId, ...replaced];
1634
+ }
1635
+ __name(heldIds, "heldIds");
1636
+ function refOf2(entry, row, merchantId) {
1637
+ if (entry.by === "id") return { merchantId, externalId: entry.value, key: null, sent: null };
1638
+ const sent = entry.end ? { until: entry.end, reason: row.reason ?? "", timeZone: row.timeZone ?? "UTC" } : null;
1639
+ return { merchantId, externalId: null, key: entry.value, sent, keep: heldIds(row) };
1640
+ }
1641
+ __name(refOf2, "refOf");
1642
+ var sameEndAsCurrent = /* @__PURE__ */ __name((entry, row) => entry.by === "key" && entry.end !== null && row.sentUntil !== null && Math.floor(entry.end.getTime() / 1e3) === Math.floor(row.sentUntil.getTime() / 1e3), "sameEndAsCurrent");
1643
+ async function retire(env, row) {
1644
+ const left = [];
1645
+ for (const entry of retiredOf(row)) {
1646
+ if (ended(entry, env.call.now)) continue;
1647
+ if (sameEndAsCurrent(entry, row) || await stillOwed(env, row, entry)) left.push(entry);
1648
+ }
1649
+ return left;
1650
+ }
1651
+ __name(retire, "retire");
1652
+ async function stillOwed(env, row, entry) {
1653
+ let result;
1654
+ try {
1655
+ result = await env.availability.resume(env.call, refOf2(entry, row, env.merchantId));
1656
+ } catch (error) {
1657
+ result = { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
1658
+ }
1659
+ if (result.kind === "accepted") return false;
1660
+ const refused = result.kind === "refused";
1661
+ const why = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
1662
+ env.ctx.ports.logger.warn(
1663
+ `marketplace.availability: ${row.provider} for ${row.clientId}: the replaced closure ${entry.by} ${entry.value} was not deleted (${why})${refused ? "; dropped" : "; the sweep retries it"}`
1664
+ );
1665
+ return !refused;
1666
+ }
1667
+ __name(stillOwed, "stillOwed");
1668
+
1669
+ // src/core/pause-job.ts
1670
+ var AvailabilityRetryError = class extends Error {
1671
+ static {
1672
+ __name(this, "AvailabilityRetryError");
1673
+ }
1674
+ constructor(message) {
1675
+ super(message);
1676
+ this.name = "AvailabilityRetryError";
1677
+ }
1678
+ };
1679
+ var MAX_STEPS = 8;
1680
+ var AGAIN = { settled: false };
1681
+ async function write(ctx, where, data) {
1682
+ const table = pauseTable(await ctx.ports.db());
1683
+ return (await table.updateMany({ where, data })).count;
1684
+ }
1685
+ __name(write, "write");
1686
+ async function failRow(ctx, now, row, code, failure) {
1687
+ const moved = await write(
1688
+ ctx,
1689
+ { id: row.id, wanted: row.wanted },
1690
+ {
1691
+ state: "FAILED",
1692
+ failureCode: code,
1693
+ failureDetail: failure.detail === null || failure.detail === "" ? null : detailOf(failure.detail),
1694
+ failedAt: now
1695
+ }
1696
+ );
1697
+ if (moved === 0) return false;
1698
+ ctx.ports.logger.error(`marketplace.availability: ${row.provider} for ${row.clientId} failed: ${code} (${failure.log})`);
1699
+ ctx.ports.publishChanged(row.clientId);
1700
+ return true;
1701
+ }
1702
+ __name(failRow, "failRow");
1703
+ async function fail2(run, row, code, failure) {
1704
+ const moved = await failRow(run.ctx, run.call.now, row, code, failure);
1705
+ return moved ? { settled: true, outcome: { kind: "failed", code } } : AGAIN;
1706
+ }
1707
+ __name(fail2, "fail");
1708
+ async function unanswered(run, row, result, codes) {
1709
+ if (result.kind === "refused") {
1710
+ return fail2(run, row, codes.refused, { detail: result.message, log: `refused ${result.status}: ${result.message}` });
1711
+ }
1712
+ if (run.attempt.attempt < run.attempt.maxAttempts) {
1713
+ throw new AvailabilityRetryError(`${row.provider} for ${row.clientId}: ${result.reason}`);
1714
+ }
1715
+ return fail2(run, row, codes.unanswered, { detail: null, log: result.reason });
1716
+ }
1717
+ __name(unanswered, "unanswered");
1718
+ var PAUSE_CODES = { refused: "PAUSE_REFUSED", unanswered: "PAUSE_UNANSWERED" };
1719
+ var RESUME_CODES = { refused: "RESUME_REFUSED", unanswered: "RESUME_UNANSWERED" };
1720
+ var upToDate = /* @__PURE__ */ __name((row) => row.sentUntil !== null && row.until !== null && row.sentUntil.getTime() === row.until.getTime(), "upToDate");
1721
+ var holds = /* @__PURE__ */ __name((row) => row.externalId !== null || row.sentUntil !== null, "holds");
1722
+ async function calledSafely(call) {
1723
+ try {
1724
+ return await call();
1725
+ } catch (error) {
1726
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
1727
+ }
1728
+ }
1729
+ __name(calledSafely, "calledSafely");
1730
+ var sentOf = /* @__PURE__ */ __name((row, until) => row.attemptKey !== null && until !== null ? { until, reason: row.reason ?? "", timeZone: row.timeZone ?? "UTC" } : null, "sentOf");
1731
+ async function claimKey(run, row) {
1732
+ const key = newAttemptKey();
1733
+ const moved = await write(run.ctx, { id: row.id, attemptKey: null, wanted: "PAUSED" }, { attemptKey: key, attemptUntil: row.until });
1734
+ return moved > 0 ? key : null;
1735
+ }
1736
+ __name(claimKey, "claimKey");
1737
+ async function sendPause(run, row) {
1738
+ const until = row.until;
1739
+ const key = row.attemptKey ?? await claimKey(run, row);
1740
+ if (key === null) return AGAIN;
1741
+ const request = { merchantId: run.merchantId, until, reason: row.reason ?? "", key, timeZone: row.timeZone ?? "UTC", keep: heldIds(row) };
1742
+ const extend = run.availability.extend;
1743
+ const ref = { merchantId: run.merchantId, externalId: row.externalId, key: null, sent: null };
1744
+ const result = await calledSafely(
1745
+ () => holds(row) && extend ? extend(run.call, ref, request) : run.availability.pause(run.call, request)
1746
+ );
1747
+ if (result.kind === "refused") {
1748
+ await write(run.ctx, { id: row.id, attemptKey: key }, { attemptKey: null, attemptUntil: null });
1749
+ return unanswered(run, row, result, PAUSE_CODES);
1750
+ }
1751
+ if (result.kind !== "paused") return unanswered(run, row, result, PAUSE_CODES);
1752
+ const replaced = row.externalId !== null && result.externalId !== row.externalId;
1753
+ const retired = replaced ? withRetired(run.ctx, row, { by: "id", value: row.externalId, end: row.sentUntil }) : retiredOf(row);
1754
+ await write(
1755
+ run.ctx,
1756
+ { id: row.id },
1757
+ { externalId: result.externalId, sentUntil: result.until, attemptKey: null, attemptUntil: null, retiredExternalIds: retiredValue(retired) }
1758
+ );
1759
+ return AGAIN;
1760
+ }
1761
+ __name(sendPause, "sendPause");
1762
+ async function resolveStaleKey(run, row) {
1763
+ if (run.availability.kind === "switch") return null;
1764
+ if (row.attemptKey === null || row.attemptUntil === null || row.attemptUntil.getTime() === row.until?.getTime()) return null;
1765
+ const retired = withRetired(run.ctx, row, { by: "key", value: row.attemptKey, end: row.attemptUntil });
1766
+ await write(
1767
+ run.ctx,
1768
+ { id: row.id, attemptKey: row.attemptKey },
1769
+ { attemptKey: null, attemptUntil: null, retiredExternalIds: retiredValue(retired) }
1770
+ );
1771
+ return AGAIN;
1772
+ }
1773
+ __name(resolveStaleKey, "resolveStaleKey");
1774
+ async function stepPause(run, current) {
1775
+ let row = current;
1776
+ if (row.until === null) return fail2(run, row, "PAUSE_REFUSED", { detail: null, log: "no end on the record" });
1777
+ const stale = await resolveStaleKey(run, row);
1778
+ if (stale) return stale;
1779
+ if (!upToDate(row)) return sendPause(run, row);
1780
+ if (row.retiredExternalIds !== null) {
1781
+ const left = await retire(run, row);
1782
+ await write(run.ctx, { id: row.id }, { retiredExternalIds: retiredValue(left) });
1783
+ row = await readPause(run.ctx, row.clientId, row.provider) ?? row;
1784
+ }
1785
+ const moved = await write(
1786
+ run.ctx,
1787
+ { id: row.id, wanted: "PAUSED", until: row.until },
1788
+ { state: "PAUSED", pausedAt: row.pausedAt ?? run.call.now, failureCode: null, failureDetail: null, failedAt: null }
1789
+ );
1790
+ if (moved === 0) return AGAIN;
1791
+ run.ctx.ports.publishChanged(row.clientId);
1792
+ return { settled: true, outcome: { kind: "done", state: "PAUSED" } };
1793
+ }
1794
+ __name(stepPause, "stepPause");
1795
+ function nextDelete(row, kind) {
1796
+ if (kind === "switch") {
1797
+ if (row.sentUntil === null && row.attemptKey === null) return null;
1798
+ return {
1799
+ ref: { merchantId: "", externalId: null, key: row.attemptKey, sent: sentOf(row, row.attemptUntil) },
1800
+ clear: { sentUntil: null, attemptKey: null, attemptUntil: null, externalId: null }
1801
+ };
1802
+ }
1803
+ if (row.externalId !== null) {
1804
+ return { ref: { merchantId: "", externalId: row.externalId, key: null, sent: null }, clear: { externalId: null, sentUntil: null } };
1805
+ }
1806
+ const [retired, ...rest] = retiredOf(row);
1807
+ if (retired !== void 0) return { ref: refOf2(retired, row, ""), clear: { retiredExternalIds: retiredValue(rest) }, replaced: true };
1808
+ if (row.attemptKey !== null) {
1809
+ return {
1810
+ ref: { merchantId: "", externalId: null, key: row.attemptKey, sent: sentOf(row, row.attemptUntil), keep: heldIds(row) },
1811
+ clear: { attemptKey: null, attemptUntil: null, sentUntil: null }
1812
+ };
1813
+ }
1814
+ return null;
1815
+ }
1816
+ __name(nextDelete, "nextDelete");
1817
+ async function pruneEnded(run, row) {
1818
+ const list = retiredOf(row);
1819
+ const live = list.filter((entry) => !ended(entry, run.call.now));
1820
+ if (live.length === list.length) return row;
1821
+ await write(run.ctx, { id: row.id }, { retiredExternalIds: retiredValue(live) });
1822
+ return { ...row, retiredExternalIds: retiredValue(live) };
1823
+ }
1824
+ __name(pruneEnded, "pruneEnded");
1825
+ async function stepResume(run, current) {
1826
+ const row = await pruneEnded(run, current);
1827
+ const next = nextDelete(row, run.availability.kind);
1828
+ if (next === null) {
1829
+ await write(
1830
+ run.ctx,
1831
+ { id: row.id, wanted: "OPEN" },
1832
+ { state: "OPEN", sentUntil: null, resumedAt: run.call.now, failureCode: null, failureDetail: null, failedAt: null }
1833
+ );
1834
+ run.ctx.ports.publishChanged(row.clientId);
1835
+ return { settled: true, outcome: { kind: "done", state: "OPEN" } };
1836
+ }
1837
+ const ref = { ...next.ref, merchantId: run.merchantId };
1838
+ const result = await calledSafely(() => run.availability.resume(run.call, ref));
1839
+ const dropped = result.kind === "refused" && next.replaced === true;
1840
+ if (dropped) {
1841
+ run.ctx.ports.logger.warn(
1842
+ `marketplace.availability: ${row.provider} for ${row.clientId}: a replaced closure's delete was refused (${result.status}: ${result.message}); dropped, it ends on its own`
1843
+ );
1844
+ }
1845
+ if (result.kind !== "accepted" && !dropped) return unanswered(run, row, result, RESUME_CODES);
1846
+ await write(run.ctx, { id: row.id }, next.clear);
1847
+ return AGAIN;
1848
+ }
1849
+ __name(stepResume, "stepResume");
1850
+ async function callContext(ctx, row) {
1851
+ const db = await ctx.ports.db();
1852
+ const integration = await db.marketplaceIntegration.findUnique({
1853
+ where: { clientId_provider: { clientId: row.clientId, provider: row.provider } },
1854
+ select: { externalMerchantId: true }
1855
+ });
1856
+ if (!integration?.externalMerchantId) return "no merchant id on the connection";
1857
+ try {
1858
+ const connection = await readOutboundConnection(ctx, row.clientId, row.provider);
1859
+ if (!connection) return "no credentials on file";
1860
+ return {
1861
+ merchantId: integration.externalMerchantId,
1862
+ call: { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection }
1863
+ };
1864
+ } catch (error) {
1865
+ return `credentials do not open: ${error instanceof Error ? error.message : String(error)}`;
1866
+ }
1867
+ }
1868
+ __name(callContext, "callContext");
1869
+ async function lease(ctx, row, now) {
1870
+ const until = new Date(now.getTime() + STORE_PAUSE_LEASE_MS);
1871
+ const taken = await write(ctx, { id: row.id, OR: [{ leaseUntil: null }, { leaseUntil: { lt: now } }] }, { leaseUntil: until });
1872
+ return taken > 0 ? until : null;
1873
+ }
1874
+ __name(lease, "lease");
1875
+ async function steps(run, first) {
1876
+ let row = first;
1877
+ for (let step = 0; step < MAX_STEPS && row; step += 1) {
1878
+ const result = row.wanted === "PAUSED" ? await stepPause(run, row) : await stepResume(run, row);
1879
+ if (result.settled) return result.outcome;
1880
+ row = await readPause(run.ctx, first.clientId, first.provider);
1881
+ }
1882
+ return { kind: "skipped", reason: "the ask kept changing; the next run or the sweep finishes it" };
1883
+ }
1884
+ __name(steps, "steps");
1885
+ async function runOnce3(ctx, payload, attempt) {
1886
+ const row = await readPause(ctx, payload.clientId, payload.provider);
1887
+ if (!row) return { kind: "skipped", reason: "no pause record" };
1888
+ const settled = row.state === "FAILED" || row.state === "OPEN" && !holdsSomething(row);
1889
+ if (settled) return { kind: "skipped", reason: `the record is ${row.state}` };
1890
+ const availability = ctx.registry.get(row.provider)?.availability;
1891
+ const now = ctx.ports.clock.now();
1892
+ if (!availability) {
1893
+ await failRow(ctx, now, row, "UNSUPPORTED", { detail: null, log: "the adapter has no availability capability" });
1894
+ return { kind: "failed", code: "UNSUPPORTED" };
1895
+ }
1896
+ const held = await lease(ctx, row, now);
1897
+ if (held === null) {
1898
+ if (attempt.attempt < attempt.maxAttempts) throw new AvailabilityRetryError(`${row.provider} for ${row.clientId}: another run holds it`);
1899
+ return { kind: "skipped", reason: "another run holds the record" };
1900
+ }
1901
+ try {
1902
+ const opened = await callContext(ctx, row);
1903
+ if (typeof opened === "string") {
1904
+ await failRow(ctx, now, row, "NOT_CONNECTED", { detail: null, log: opened });
1905
+ return { kind: "failed", code: "NOT_CONNECTED" };
1906
+ }
1907
+ return await steps({ ctx, availability, attempt, ...opened }, row);
1908
+ } finally {
1909
+ await write(ctx, { id: row.id, leaseUntil: held }, { leaseUntil: null });
1910
+ }
1911
+ }
1912
+ __name(runOnce3, "runOnce");
1913
+ async function runAvailability(ctx, payload, attempt) {
1914
+ try {
1915
+ return await runOnce3(ctx, payload, attempt);
1916
+ } catch (error) {
1917
+ if (error instanceof AvailabilityRetryError || attempt.attempt < attempt.maxAttempts) throw error;
1918
+ const row = await readPause(ctx, payload.clientId, payload.provider);
1919
+ if (!row) return { kind: "skipped", reason: "no pause record" };
1920
+ const code = row.wanted === "PAUSED" ? "PAUSE_UNANSWERED" : "RESUME_UNANSWERED";
1921
+ await failRow(ctx, ctx.ports.clock.now(), row, code, { detail: null, log: error instanceof Error ? error.message : String(error) });
1922
+ return { kind: "failed", code };
1923
+ }
1924
+ }
1925
+ __name(runAvailability, "runAvailability");
1926
+
1194
1927
  export {
1195
1928
  requestsFirst,
1196
1929
  tellCancellationFailed,
@@ -1219,6 +1952,16 @@ export {
1219
1952
  MARKETPLACE_OUTBOUND_JOB,
1220
1953
  outboundDedupeKey,
1221
1954
  enqueueOutbound,
1955
+ CATALOGUE_ROW_SELECT,
1956
+ catalogueTable,
1957
+ viewOf,
1958
+ NO_FAILURE,
1959
+ catalogueConnection,
1960
+ MARKETPLACE_CATALOGUE_JOB,
1961
+ CatalogueRetryError,
1962
+ catalogueDedupeKey,
1963
+ enqueueCatalogue,
1964
+ runCatalogue,
1222
1965
  recordInboxEvent,
1223
1966
  settleInboxEvent,
1224
1967
  deferInboxEvent,
@@ -1231,10 +1974,22 @@ export {
1231
1974
  requeueOwedFetch,
1232
1975
  merchantMismatch,
1233
1976
  runFetchOrder,
1977
+ CATALOGUE_STALE_MS,
1978
+ CATALOGUE_GIVE_UP_MS,
1234
1979
  OUTBOUND_STALE_MS,
1235
1980
  OUTBOUND_GIVE_UP_MS,
1236
1981
  sweepOutbound,
1237
1982
  OutboundRetryError,
1238
- runOutbound
1983
+ runOutbound,
1984
+ MARKETPLACE_AVAILABILITY_JOB,
1985
+ STORE_PAUSE_LEASE_MS,
1986
+ pauseTable,
1987
+ hasPauseTable,
1988
+ readPause,
1989
+ holdsSomething,
1990
+ availabilityDedupeKey,
1991
+ enqueueAvailability,
1992
+ AvailabilityRetryError,
1993
+ runAvailability
1239
1994
  };
1240
- //# sourceMappingURL=chunk-D2X7TOR6.js.map
1995
+ //# sourceMappingURL=chunk-EBAIZQPB.js.map