@12-apps/marketplace 1.10.0 → 1.12.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 (84) hide show
  1. package/ADOPTING.md +126 -1
  2. package/README.md +100 -1
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-CYJzu1c9.d.ts → adapter-nUyZpLzz.d.ts} +448 -173
  6. package/dist/{chunk-2BA2EHNF.js → chunk-45ZVN5XI.js} +316 -42
  7. package/dist/chunk-45ZVN5XI.js.map +1 -0
  8. package/dist/{chunk-PYHNM47K.js → chunk-L6FG6T4S.js} +2 -2
  9. package/dist/{chunk-HEXLCTOG.js → chunk-LACBT6NC.js} +1 -1
  10. package/dist/chunk-LACBT6NC.js.map +1 -0
  11. package/dist/{chunk-WVZ2IXFH.js → chunk-MIPNQ7X5.js} +190 -12
  12. package/dist/chunk-MIPNQ7X5.js.map +1 -0
  13. package/dist/chunk-SGOTN5PX.js +345 -0
  14. package/dist/chunk-SGOTN5PX.js.map +1 -0
  15. package/dist/{client-B4EQCRD_.d.ts → client-Ctas7WCS.d.ts} +1 -1
  16. package/dist/{engine-DK3iV_Kk.d.ts → engine-CIy9P7Cq.d.ts} +149 -8
  17. package/dist/hono/index.d.ts +2 -2
  18. package/dist/hono/index.js +3 -3
  19. package/dist/ifood/index.d.ts +10 -2
  20. package/dist/ifood/index.js +297 -25
  21. package/dist/ifood/index.js.map +1 -1
  22. package/dist/index.d.ts +23 -4
  23. package/dist/index.js +424 -84
  24. package/dist/index.js.map +1 -1
  25. package/dist/keeta/index.d.ts +2 -18
  26. package/dist/keeta/index.js +12 -3
  27. package/dist/keeta/index.js.map +1 -1
  28. package/dist/manifest/index.d.ts +219 -1
  29. package/dist/manifest/index.js +1 -1
  30. package/dist/manifest/server.d.ts +2 -2
  31. package/dist/manifest/server.js +3 -3
  32. package/dist/rappi/index.d.ts +1 -1
  33. package/dist/rappi/index.js +1 -1
  34. package/dist/server/en-US.d.ts +13 -0
  35. package/dist/server/en-US.js +13 -0
  36. package/dist/server/en-US.js.map +1 -1
  37. package/dist/server/index.d.ts +241 -7
  38. package/dist/server/index.js +3 -3
  39. package/dist/server/pt-BR.d.ts +13 -0
  40. package/dist/server/pt-BR.js +13 -0
  41. package/dist/server/pt-BR.js.map +1 -1
  42. package/package.json +1 -1
  43. package/prisma/marketplace.prisma +41 -0
  44. package/prisma/migrations/20261127090000_marketplace_app_link/migration.sql +81 -0
  45. package/src/core/adapter.ts +27 -0
  46. package/src/core/bulk.ts +43 -8
  47. package/src/core/courier-port.ts +100 -0
  48. package/src/core/courier.ts +153 -0
  49. package/src/core/engine.ts +63 -4
  50. package/src/core/integration.ts +60 -32
  51. package/src/core/lifecycle.ts +27 -4
  52. package/src/core/link-store.ts +170 -0
  53. package/src/core/linking-port.ts +100 -0
  54. package/src/core/linking.ts +363 -0
  55. package/src/core/merchant-claim.ts +106 -0
  56. package/src/core/outbound-queue.ts +24 -11
  57. package/src/core/outbound.ts +8 -6
  58. package/src/core/pickup-code.ts +136 -0
  59. package/src/core/pipeline.ts +15 -6
  60. package/src/core/ports.ts +26 -1
  61. package/src/core/status-store.ts +2 -3
  62. package/src/core/types.ts +56 -4
  63. package/src/ifood/courier.ts +210 -0
  64. package/src/ifood/index.ts +8 -0
  65. package/src/ifood/linking.ts +170 -0
  66. package/src/ifood/normalize.ts +7 -0
  67. package/src/ifood/outbound.ts +10 -3
  68. package/src/index.ts +30 -0
  69. package/src/keeta/normalize.ts +21 -6
  70. package/src/server/copy.ts +20 -2
  71. package/src/server/en-US.ts +13 -0
  72. package/src/server/index.ts +1 -1
  73. package/src/server/link-routes.ts +140 -0
  74. package/src/server/mcp-link.ts +103 -0
  75. package/src/server/mcp.ts +6 -2
  76. package/src/server/pt-BR.ts +13 -0
  77. package/src/server/routes.ts +5 -2
  78. package/src/server/webhook.ts +86 -0
  79. package/dist/chunk-2BA2EHNF.js.map +0 -1
  80. package/dist/chunk-HEXLCTOG.js.map +0 -1
  81. package/dist/chunk-WVZ2IXFH.js.map +0 -1
  82. package/dist/chunk-ZO4S3LF4.js +0 -254
  83. package/dist/chunk-ZO4S3LF4.js.map +0 -1
  84. /package/dist/{chunk-PYHNM47K.js.map → chunk-L6FG6T4S.js.map} +0 -0
@@ -76,6 +76,64 @@ function suggestReason(adapter, input) {
76
76
  }
77
77
  __name(suggestReason, "suggestReason");
78
78
 
79
+ // src/core/merchant-claim.ts
80
+ var MarketplaceMerchantTakenError = class extends Error {
81
+ static {
82
+ __name(this, "MarketplaceMerchantTakenError");
83
+ }
84
+ code = "MERCHANT_TAKEN";
85
+ /** The field the refusal is about, as a problem path. */
86
+ path = ["externalMerchantId"];
87
+ constructor(provider, merchantId) {
88
+ super(`The ${provider} merchant ${merchantId} is already held by another store's live connection.`);
89
+ this.name = "MarketplaceMerchantTakenError";
90
+ }
91
+ };
92
+ function isUniqueViolation(error) {
93
+ const code = error?.code;
94
+ return code === "P2002" || code === "23505";
95
+ }
96
+ __name(isUniqueViolation, "isUniqueViolation");
97
+ async function merchantHeldElsewhere(db, clientId, provider, merchantId) {
98
+ const rows = await db.marketplaceIntegration.findMany({
99
+ where: { provider, externalMerchantId: merchantId, archivedAt: null },
100
+ select: { clientId: true }
101
+ });
102
+ return rows.some((row) => row.clientId !== clientId);
103
+ }
104
+ __name(merchantHeldElsewhere, "merchantHeldElsewhere");
105
+ async function assertMerchantFree(db, clientId, provider, merchantId) {
106
+ if (merchantId && await merchantHeldElsewhere(db, clientId, provider, merchantId)) {
107
+ throw new MarketplaceMerchantTakenError(provider, merchantId);
108
+ }
109
+ }
110
+ __name(assertMerchantFree, "assertMerchantFree");
111
+ async function guardMerchantClaim(ctx, claim3, write2) {
112
+ try {
113
+ return await write2();
114
+ } catch (error) {
115
+ const { merchantId } = claim3;
116
+ if (!isUniqueViolation(error) || !merchantId) throw error;
117
+ if (!await merchantHeldElsewhere(await ctx.ports.db(), claim3.clientId, claim3.provider, merchantId)) throw error;
118
+ throw new MarketplaceMerchantTakenError(claim3.provider, merchantId);
119
+ }
120
+ }
121
+ __name(guardMerchantClaim, "guardMerchantClaim");
122
+ async function resolveTenantByMerchant(ctx, provider, externalMerchantId) {
123
+ const db = await ctx.ports.db();
124
+ const rows = await db.marketplaceIntegration.findMany({
125
+ where: { provider, externalMerchantId, archivedAt: null },
126
+ select: { clientId: true },
127
+ take: 2
128
+ });
129
+ if (rows.length > 1) {
130
+ ctx.ports.logger.warn(`marketplace: ${provider} merchant ${externalMerchantId} is held by several live connections`);
131
+ return null;
132
+ }
133
+ return rows[0]?.clientId ?? null;
134
+ }
135
+ __name(resolveTenantByMerchant, "resolveTenantByMerchant");
136
+
79
137
  // src/core/outbound-queue.ts
80
138
  var MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
81
139
  function outboundDedupeKey(payload) {
@@ -86,11 +144,21 @@ function statusDedupeKey(step, orderId, at) {
86
144
  return `${MARKETPLACE_OUTBOUND_JOB}:status:${step}:${orderId}:${at.getTime()}`;
87
145
  }
88
146
  __name(statusDedupeKey, "statusDedupeKey");
147
+ function ableTo(adapter, payload) {
148
+ switch (payload.action) {
149
+ case "status":
150
+ return Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step));
151
+ case "confirm":
152
+ return adapter.capabilities.apiConfirm;
153
+ default:
154
+ return adapter.capabilities.apiCancel;
155
+ }
156
+ }
157
+ __name(ableTo, "ableTo");
89
158
  async function enqueueOutbound(ctx, payload, provider, dedupeKey = outboundDedupeKey(payload)) {
90
159
  const adapter = ctx.registry.get(provider);
91
160
  if (!adapter) return false;
92
- const able = payload.action === "status" ? Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step)) : payload.action === "confirm" ? adapter.capabilities.apiConfirm : adapter.capabilities.apiCancel;
93
- if (!able) return false;
161
+ if (!ableTo(adapter, payload)) return false;
94
162
  const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
95
163
  if (!outcome.enqueued) {
96
164
  ctx.ports.logger.warn(
@@ -161,6 +229,113 @@ async function forgetCategory(ctx, connection, name) {
161
229
  }
162
230
  __name(forgetCategory, "forgetCategory");
163
231
 
232
+ // src/core/link-store.ts
233
+ var TOKEN_MARGIN_MS = 6e4;
234
+ function sealLink(ctx, refreshToken) {
235
+ return ctx.ports.secrets.seal(JSON.stringify({ clientId: "", clientSecret: "", webhookSecret: null, refreshToken }));
236
+ }
237
+ __name(sealLink, "sealLink");
238
+ function openLinkRefreshToken(ctx, sealed) {
239
+ const parsed = JSON.parse(ctx.ports.secrets.open(sealed));
240
+ const token = typeof parsed === "object" && parsed !== null ? parsed.refreshToken : null;
241
+ if (typeof token !== "string" || token === "") throw new Error("The linked connection holds no refresh token.");
242
+ return token;
243
+ }
244
+ __name(openLinkRefreshToken, "openLinkRefreshToken");
245
+ async function appCredentialsOf(ctx, provider, environment) {
246
+ const port = ctx.ports.appCredentials;
247
+ if (!port) return null;
248
+ const credentials = await port(provider, environment);
249
+ return credentials && credentials.clientId !== "" && credentials.clientSecret !== "" ? credentials : null;
250
+ }
251
+ __name(appCredentialsOf, "appCredentialsOf");
252
+ var linkTokenKey = /* @__PURE__ */ __name((provider, environment, clientId) => `LINK:${provider}:${environment}:${clientId}`, "linkTokenKey");
253
+ async function cacheLinkToken(ctx, link, key, grant) {
254
+ const db = await ctx.ports.db();
255
+ const row = await db.marketplaceIntegration.findUnique({
256
+ where: { clientId_provider: { clientId: link.clientId, provider: link.provider } },
257
+ select: { credentials: true }
258
+ });
259
+ if (row?.credentials !== link.sealed) return false;
260
+ setToken(ctx, key, grant);
261
+ return true;
262
+ }
263
+ __name(cacheLinkToken, "cacheLinkToken");
264
+ function setToken(ctx, key, grant) {
265
+ const expiresAt = ctx.ports.clock.now().getTime() + Math.max(grant.expiresInSeconds, 1) * 1e3;
266
+ ctx.tokens.set(key, { token: grant.accessToken, expiresAt });
267
+ }
268
+ __name(setToken, "setToken");
269
+ var inflight = /* @__PURE__ */ new WeakMap();
270
+ async function storeRotated(ctx, link, refreshToken) {
271
+ const db = await ctx.ports.db();
272
+ const { count } = await db.marketplaceIntegration.updateMany({
273
+ where: { clientId: link.clientId, provider: link.provider, authMode: "LINKED", archivedAt: null, credentials: link.sealed },
274
+ data: { credentials: sealLink(ctx, refreshToken) }
275
+ });
276
+ return count > 0;
277
+ }
278
+ __name(storeRotated, "storeRotated");
279
+ async function markLinkFailed(ctx, link) {
280
+ const db = await ctx.ports.db();
281
+ const { count } = await db.marketplaceIntegration.updateMany({
282
+ where: { clientId: link.clientId, provider: link.provider, authMode: "LINKED", credentials: link.sealed },
283
+ data: { status: "FAILED" }
284
+ });
285
+ if (count > 0) ctx.ports.publishChanged(link.clientId);
286
+ return count > 0;
287
+ }
288
+ __name(markLinkFailed, "markLinkFailed");
289
+ var RELINKED = { kind: "retry", reason: "the connection was linked again during the refresh" };
290
+ async function refreshOnce(ctx, link, key) {
291
+ const linking = ctx.registry.get(link.provider)?.linking;
292
+ if (!linking) return { kind: "refused", status: 0, message: "this marketplace links no store", own: true };
293
+ const answer = await linking.refresh(
294
+ { http: ctx.ports.http, credentials: link.app, environment: link.environment, now: ctx.ports.clock.now() },
295
+ { refreshToken: link.refreshToken }
296
+ );
297
+ if (answer.kind === "retry") return answer;
298
+ if (answer.kind === "refused") return await markLinkFailed(ctx, link) ? { ...answer, own: true } : RELINKED;
299
+ const rotated = answer.value.refreshToken;
300
+ if (rotated === null || rotated === link.refreshToken) {
301
+ return await cacheLinkToken(ctx, link, key, answer.value) ? { token: answer.value.accessToken } : RELINKED;
302
+ }
303
+ const stored = await storeRotated(ctx, link, rotated).catch((error) => {
304
+ ctx.ports.logger.error(
305
+ `marketplace.link: ${link.provider} rotated refresh token of ${link.clientId} not stored: ` + (error instanceof Error ? error.message : String(error))
306
+ );
307
+ return null;
308
+ });
309
+ if (stored === false) return RELINKED;
310
+ setToken(ctx, key, answer.value);
311
+ return { token: answer.value.accessToken };
312
+ }
313
+ __name(refreshOnce, "refreshOnce");
314
+ function linkGrant(ctx, link) {
315
+ const key = linkTokenKey(link.provider, link.environment, link.clientId);
316
+ return {
317
+ key,
318
+ accessToken: /* @__PURE__ */ __name(async () => {
319
+ const cached = ctx.tokens.get(key);
320
+ if (cached && cached.expiresAt > ctx.ports.clock.now().getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
321
+ let running = inflight.get(ctx.tokens);
322
+ if (!running) {
323
+ running = /* @__PURE__ */ new Map();
324
+ inflight.set(ctx.tokens, running);
325
+ }
326
+ const pending = running.get(key);
327
+ if (pending) return pending;
328
+ const call2 = refreshOnce(ctx, link, key).catch((error) => ({
329
+ kind: "retry",
330
+ reason: error instanceof Error ? error.message : String(error)
331
+ })).finally(() => running.delete(key));
332
+ running.set(key, call2);
333
+ return call2;
334
+ }, "accessToken")
335
+ };
336
+ }
337
+ __name(linkGrant, "linkGrant");
338
+
164
339
  // src/core/integration.ts
165
340
  var VIEW_SELECT = {
166
341
  provider: true,
@@ -174,7 +349,8 @@ var VIEW_SELECT = {
174
349
  credentials: true,
175
350
  lastEventAt: true,
176
351
  lastVerifiedAt: true,
177
- archivedAt: true
352
+ archivedAt: true,
353
+ authMode: true
178
354
  };
179
355
  function toView(row) {
180
356
  return {
@@ -189,7 +365,8 @@ function toView(row) {
189
365
  connected: row.credentials !== "",
190
366
  lastEventAt: row.lastEventAt,
191
367
  lastVerifiedAt: row.lastVerifiedAt,
192
- archivedAt: row.archivedAt ?? null
368
+ archivedAt: row.archivedAt ?? null,
369
+ authMode: row.authMode === "LINKED" ? "LINKED" : "CREDENTIALS"
193
370
  };
194
371
  }
195
372
  __name(toView, "toView");
@@ -208,6 +385,7 @@ async function listMarketplaceIntegrations(ctx, clientId, options = {}) {
208
385
  }
209
386
  __name(listMarketplaceIntegrations, "listMarketplaceIntegrations");
210
387
  async function saveMarketplaceIntegration(ctx, input, db) {
388
+ await assertMerchantFree(db, input.clientId, input.provider, input.externalMerchantId);
211
389
  const sealed = input.credentials ? ctx.ports.secrets.seal(JSON.stringify(input.credentials)) : void 0;
212
390
  const mutable = {
213
391
  ...input.enabled === void 0 ? {} : { enabled: input.enabled },
@@ -216,7 +394,8 @@ async function saveMarketplaceIntegration(ctx, input, db) {
216
394
  ...input.autoAccept === void 0 ? {} : { autoAccept: input.autoAccept },
217
395
  ...input.followStatus === void 0 ? {} : { followStatus: input.followStatus },
218
396
  ...input.ackSlaSeconds === void 0 ? {} : { ackSlaSeconds: input.ackSlaSeconds },
219
- ...sealed === void 0 ? {} : { credentials: sealed, status: "UNVERIFIED" }
397
+ // Typed credentials make the connection the store's own app again.
398
+ ...sealed === void 0 ? {} : { credentials: sealed, status: "UNVERIFIED", authMode: "CREDENTIALS" }
220
399
  };
221
400
  const row = await db.marketplaceIntegration.upsert({
222
401
  where: { clientId_provider: { clientId: input.clientId, provider: input.provider } },
@@ -253,7 +432,9 @@ async function resolveIngestionTarget(ctx, clientId, provider) {
253
432
  ackSlaSeconds: true,
254
433
  credentials: true,
255
434
  archivedAt: true,
256
- externalMerchantId: true
435
+ externalMerchantId: true,
436
+ authMode: true,
437
+ environment: true
257
438
  }
258
439
  });
259
440
  if (!row || row.archivedAt) return null;
@@ -266,10 +447,22 @@ async function resolveIngestionTarget(ctx, clientId, provider) {
266
447
  // An unopenable blob must not read as "no secret configured" — that would
267
448
  // turn a key-rotation problem into an endpoint that accepts unsigned
268
449
  // deliveries. The secrets port throws instead, and the caller answers 401.
269
- webhookSecret: row.credentials === "" ? null : openCredentials(ctx, row.credentials).webhookSecret
450
+ webhookSecret: await webhookSecretOf(ctx, provider, row)
270
451
  };
271
452
  }
272
453
  __name(resolveIngestionTarget, "resolveIngestionTarget");
454
+ async function webhookSecretOf(ctx, provider, row) {
455
+ if (row.authMode !== "LINKED") {
456
+ return row.credentials === "" ? null : openCredentials(ctx, row.credentials).webhookSecret;
457
+ }
458
+ const app = await appCredentialsOf(ctx, provider, environmentOf(row.environment));
459
+ if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
460
+ const secret = app.webhookSecret || app.clientSecret;
461
+ if (!secret) throw new Error(`No webhook key is configured for ${provider}.`);
462
+ return secret;
463
+ }
464
+ __name(webhookSecretOf, "webhookSecretOf");
465
+ var environmentOf = /* @__PURE__ */ __name((value) => value === "PRODUCTION" ? "PRODUCTION" : "SANDBOX", "environmentOf");
273
466
  function openCredentials(ctx, sealed) {
274
467
  const parsed = JSON.parse(ctx.ports.secrets.open(sealed));
275
468
  if (typeof parsed !== "object" || parsed === null) {
@@ -283,16 +476,6 @@ function openCredentials(ctx, sealed) {
283
476
  };
284
477
  }
285
478
  __name(openCredentials, "openCredentials");
286
- async function resolveTenantByMerchant(ctx, provider, externalMerchantId) {
287
- const db = await ctx.ports.db();
288
- const rows = await db.marketplaceIntegration.findMany({
289
- where: { provider, externalMerchantId, archivedAt: null },
290
- select: { clientId: true },
291
- take: 1
292
- });
293
- return rows[0]?.clientId ?? null;
294
- }
295
- __name(resolveTenantByMerchant, "resolveTenantByMerchant");
296
479
  async function markMarketplaceEventSeen(db, clientId, provider, at) {
297
480
  await db.marketplaceIntegration.updateMany({
298
481
  where: { clientId, provider },
@@ -304,13 +487,16 @@ async function readOutboundConnection(ctx, clientId, provider) {
304
487
  const db = await ctx.ports.db();
305
488
  const row = await db.marketplaceIntegration.findUnique({
306
489
  where: { clientId_provider: { clientId, provider } },
307
- select: { environment: true, credentials: true }
490
+ select: { environment: true, credentials: true, authMode: true }
308
491
  });
309
492
  if (!row || row.credentials === "") return null;
310
- return {
311
- environment: row.environment === "PRODUCTION" ? "PRODUCTION" : "SANDBOX",
312
- credentials: openCredentials(ctx, row.credentials)
313
- };
493
+ const environment = environmentOf(row.environment);
494
+ if (row.authMode !== "LINKED") return { environment, credentials: openCredentials(ctx, row.credentials) };
495
+ const app = await appCredentialsOf(ctx, provider, environment);
496
+ if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
497
+ const refreshToken = openLinkRefreshToken(ctx, row.credentials);
498
+ const link = { clientId, provider, environment, refreshToken, app, sealed: row.credentials };
499
+ return { environment, credentials: app, grant: linkGrant(ctx, link) };
314
500
  }
315
501
  __name(readOutboundConnection, "readOutboundConnection");
316
502
 
@@ -413,21 +599,21 @@ async function enqueueCatalogue(ctx, payload, dedupeKey) {
413
599
  );
414
600
  }
415
601
  __name(enqueueCatalogue, "enqueueCatalogue");
416
- async function callFor(ctx, row, action, catalogue, call) {
602
+ async function callFor(ctx, row, action, catalogue, call2) {
417
603
  if (action === "withdraw") {
418
- if (catalogue.mode === "pull") return { result: await catalogue.notifyMenuChanged(call), sentPriceCents: null };
604
+ if (catalogue.mode === "pull") return { result: await catalogue.notifyMenuChanged(call2), sentPriceCents: null };
419
605
  const ref = { ref: row.id, productId: row.productId, externalId: row.externalId };
420
- return { result: await catalogue.withdrawItem(call, ref), sentPriceCents: null };
606
+ return { result: await catalogue.withdrawItem(call2, ref), sentPriceCents: null };
421
607
  }
422
608
  const item = (await ctx.ports.catalogue?.items(row.clientId, [row.productId]))?.get(row.productId);
423
609
  if (!item) return { code: "PRODUCT_GONE" };
424
610
  const priceCents = row.priceCents ?? item.priceCents;
425
611
  if (catalogue.mode === "pull") {
426
- return { result: await catalogue.notifyMenuChanged(call), sentPriceCents: priceCents, name: item.name };
612
+ return { result: await catalogue.notifyMenuChanged(call2), sentPriceCents: priceCents, name: item.name };
427
613
  }
428
614
  const storedImage = row.imageRef && row.imageSourceUrl ? { ref: row.imageRef, sourceUrl: row.imageSourceUrl } : null;
429
615
  const out = { ...item, priceCents, ref: row.id, productId: row.productId, externalId: row.externalId, storedImage };
430
- return { result: await catalogue.publishItem(call, out), sentPriceCents: priceCents, name: item.name };
616
+ return { result: await catalogue.publishItem(call2, out), sentPriceCents: priceCents, name: item.name };
431
617
  }
432
618
  __name(callFor, "callFor");
433
619
  var stillAsked = /* @__PURE__ */ __name((row, action) => ({
@@ -842,9 +1028,9 @@ async function ingestMarketplaceOrder(ctx, input) {
842
1028
  __name(ingestMarketplaceOrder, "ingestMarketplaceOrder");
843
1029
 
844
1030
  // src/core/cancellation-outcome.ts
845
- async function tell(ctx, what, orderId, call) {
1031
+ async function tell(ctx, what, orderId, call2) {
846
1032
  try {
847
- await call();
1033
+ await call2();
848
1034
  } catch (error) {
849
1035
  ctx.ports.logger.error(
850
1036
  `marketplace.cancellation: order ${orderId} ${what} but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
@@ -1419,6 +1605,84 @@ async function sweepOutbound(ctx, now) {
1419
1605
  }
1420
1606
  __name(sweepOutbound, "sweepOutbound");
1421
1607
 
1608
+ // src/core/pickup-code.ts
1609
+ async function validatePickupCode(ctx, input) {
1610
+ const payload = {
1611
+ clientId: input.clientId,
1612
+ orderId: input.orderId,
1613
+ action: "validatePickupCode",
1614
+ code: input.code
1615
+ };
1616
+ const dedupeKey = `${MARKETPLACE_OUTBOUND_JOB}:validatePickupCode:${input.orderId}:${input.at.getTime()}`;
1617
+ const notQueued = /* @__PURE__ */ __name((why) => {
1618
+ ctx.ports.logger.warn(`${MARKETPLACE_OUTBOUND_JOB}: validatePickupCode for order ${input.orderId} was not queued${why}`);
1619
+ return false;
1620
+ }, "notQueued");
1621
+ try {
1622
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
1623
+ return outcome.enqueued || notQueued(outcome.reason ? ` (${outcome.reason})` : "");
1624
+ } catch (error) {
1625
+ return notQueued(`: ${error instanceof Error ? error.message : String(error)}`);
1626
+ }
1627
+ }
1628
+ __name(validatePickupCode, "validatePickupCode");
1629
+ async function tellPickupCode(ctx, payload, validation) {
1630
+ const hook = ctx.ports.order.onPickupCodeValidated;
1631
+ const log = validation === "VALID" ? ctx.ports.logger.info : ctx.ports.logger.warn;
1632
+ log.call(ctx.ports.logger, `marketplace.outbound: pickup code of order ${payload.orderId}: ${validation}`);
1633
+ if (!hook) return;
1634
+ try {
1635
+ await hook.call(ctx.ports.order, payload.clientId, payload.orderId, validation);
1636
+ } catch (error) {
1637
+ ctx.ports.logger.error(
1638
+ `marketplace.outbound: the host's half of the pickup-code verdict for order ${payload.orderId} failed: ` + (error instanceof Error ? error.message : String(error))
1639
+ );
1640
+ }
1641
+ }
1642
+ __name(tellPickupCode, "tellPickupCode");
1643
+ function skipOf(payload, row, adapter) {
1644
+ if (!adapter.courier) return "the marketplace has no pickup-code check";
1645
+ if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
1646
+ if (row.deliveredBy !== "MARKETPLACE") return "the order is not carried by the marketplace's courier";
1647
+ return payload.code ? null : "no pickup code to send";
1648
+ }
1649
+ __name(skipOf, "skipOf");
1650
+ async function call(ctx, payload, row, adapter, ref) {
1651
+ let connection;
1652
+ try {
1653
+ connection = await readOutboundConnection(ctx, payload.clientId, row.provider);
1654
+ } catch (error) {
1655
+ const message = `credentials do not open: ${error instanceof Error ? error.message : String(error)}`;
1656
+ return { kind: "refused", status: 0, message, own: true };
1657
+ }
1658
+ if (!connection) return { kind: "refused", status: 0, message: "no credentials on file", own: true };
1659
+ return adapter.courier.validatePickupCode(
1660
+ { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
1661
+ ref,
1662
+ { code: payload.code }
1663
+ );
1664
+ }
1665
+ __name(call, "call");
1666
+ async function runPickupCode(ctx, payload, row, adapter, deps) {
1667
+ const skip = skipOf(payload, row, adapter);
1668
+ if (skip) return { kind: "skipped", reason: skip };
1669
+ const result = await call(ctx, payload, row, adapter, deps.ref);
1670
+ if (result.kind === "answered") {
1671
+ await tellPickupCode(ctx, payload, result.valid ? "VALID" : "INVALID");
1672
+ ctx.ports.publishChanged(payload.clientId);
1673
+ return { kind: "done", action: "validatePickupCode" };
1674
+ }
1675
+ const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
1676
+ if (result.kind === "retry" && deps.attempt.attempt < deps.attempt.maxAttempts) {
1677
+ throw deps.retryError(`validatePickupCode for order ${row.orderId}: ${reason}`);
1678
+ }
1679
+ ctx.ports.logger.error(`marketplace.outbound: validatePickupCode for order ${row.orderId} failed: ${reason}`);
1680
+ await tellPickupCode(ctx, payload, "UNVERIFIED");
1681
+ ctx.ports.publishChanged(payload.clientId);
1682
+ return { kind: "failed", action: "validatePickupCode", reason };
1683
+ }
1684
+ __name(runPickupCode, "runPickupCode");
1685
+
1422
1686
  // src/core/status-job.ts
1423
1687
  function deliveredByOf(row) {
1424
1688
  return row.deliveredBy === "MERCHANT" || row.deliveredBy === "MARKETPLACE" ? row.deliveredBy : null;
@@ -1704,9 +1968,10 @@ async function runCancellation(ctx, payload, row, adapter, attempt) {
1704
1968
  __name(runCancellation, "runCancellation");
1705
1969
  async function stampLastAttemptFailure(ctx, payload, error) {
1706
1970
  const reason = error instanceof Error ? error.message : String(error);
1707
- if (payload.action === "status") {
1708
- await failStatusRow(ctx, payload);
1709
- ctx.ports.logger.error(`marketplace.outbound: status ${payload.step ?? ""} for order ${payload.orderId} failed: ${reason}`);
1971
+ if (payload.action === "status" || payload.action === "validatePickupCode") {
1972
+ if (payload.action === "status") await failStatusRow(ctx, payload);
1973
+ else await tellPickupCode(ctx, payload, "UNVERIFIED");
1974
+ ctx.ports.logger.error(`marketplace.outbound: ${payload.action}${payload.step ? ` ${payload.step}` : ""} for order ${payload.orderId} failed: ${reason}`);
1710
1975
  return { kind: "failed", action: payload.action, reason };
1711
1976
  }
1712
1977
  const db = await ctx.ports.db();
@@ -1734,9 +1999,9 @@ async function runOnce2(ctx, payload, attempt) {
1734
1999
  if (!row) return { kind: "skipped", reason: "no acceptance for this order" };
1735
2000
  const adapter = ctx.registry.get(row.provider);
1736
2001
  if (!adapter) return { kind: "skipped", reason: `no adapter for ${row.provider}` };
1737
- if (payload.action === "status") {
1738
- return runStatus(ctx, payload, row, adapter, { attempt, ref: refOf(row), retryError: /* @__PURE__ */ __name((m) => new OutboundRetryError(m), "retryError") });
1739
- }
2002
+ const deps = { attempt, ref: refOf(row), retryError: /* @__PURE__ */ __name((m) => new OutboundRetryError(m), "retryError") };
2003
+ if (payload.action === "status") return runStatus(ctx, payload, row, adapter, deps);
2004
+ if (payload.action === "validatePickupCode") return runPickupCode(ctx, payload, row, adapter, deps);
1740
2005
  return payload.action === "confirm" ? runConfirm(ctx, payload, row, adapter, attempt) : runCancellation(ctx, payload, row, adapter, attempt);
1741
2006
  }
1742
2007
  __name(runOnce2, "runOnce");
@@ -1926,9 +2191,9 @@ var PAUSE_CODES = { refused: "PAUSE_REFUSED", unanswered: "PAUSE_UNANSWERED" };
1926
2191
  var RESUME_CODES = { refused: "RESUME_REFUSED", unanswered: "RESUME_UNANSWERED" };
1927
2192
  var upToDate = /* @__PURE__ */ __name((row) => row.sentUntil !== null && row.until !== null && row.sentUntil.getTime() === row.until.getTime(), "upToDate");
1928
2193
  var holds = /* @__PURE__ */ __name((row) => row.externalId !== null || row.sentUntil !== null, "holds");
1929
- async function calledSafely(call) {
2194
+ async function calledSafely(call2) {
1930
2195
  try {
1931
- return await call();
2196
+ return await call2();
1932
2197
  } catch (error) {
1933
2198
  return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
1934
2199
  }
@@ -2149,11 +2414,19 @@ export {
2149
2414
  listPendingAcceptances,
2150
2415
  expireLapsedAcceptances,
2151
2416
  cancelAcceptance,
2417
+ sealLink,
2418
+ appCredentialsOf,
2419
+ linkTokenKey,
2420
+ cacheLinkToken,
2421
+ MarketplaceMerchantTakenError,
2422
+ isUniqueViolation,
2423
+ merchantHeldElsewhere,
2424
+ guardMerchantClaim,
2425
+ resolveTenantByMerchant,
2152
2426
  listMarketplaceIntegrations,
2153
2427
  saveMarketplaceIntegration,
2154
2428
  connectionMerchantId,
2155
2429
  resolveIngestionTarget,
2156
- resolveTenantByMerchant,
2157
2430
  readOutboundConnection,
2158
2431
  listMarketplaceMenuLinks,
2159
2432
  upsertLink,
@@ -2175,6 +2448,10 @@ export {
2175
2448
  settleInboxEvent,
2176
2449
  deferInboxEvent,
2177
2450
  listRetryableInboxEvents,
2451
+ statusTable,
2452
+ readStatusRows,
2453
+ noteMarketplaceStep,
2454
+ validatePickupCode,
2178
2455
  ingestMarketplaceOrder,
2179
2456
  CANCELLED_BEFORE_INGEST_REASON,
2180
2457
  markCancelledBeforeIngest,
@@ -2187,9 +2464,6 @@ export {
2187
2464
  runFetchOrder,
2188
2465
  CATALOGUE_STALE_MS,
2189
2466
  CATALOGUE_GIVE_UP_MS,
2190
- statusTable,
2191
- readStatusRows,
2192
- noteMarketplaceStep,
2193
2467
  OUTBOUND_STALE_MS,
2194
2468
  OUTBOUND_GIVE_UP_MS,
2195
2469
  sweepOutbound,
@@ -2206,4 +2480,4 @@ export {
2206
2480
  AvailabilityRetryError,
2207
2481
  runAvailability
2208
2482
  };
2209
- //# sourceMappingURL=chunk-2BA2EHNF.js.map
2483
+ //# sourceMappingURL=chunk-45ZVN5XI.js.map