@12-apps/marketplace 1.9.0 → 1.11.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 (75) hide show
  1. package/ADOPTING.md +63 -1
  2. package/README.md +64 -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-CD0SfdVS.d.ts} +124 -1
  6. package/dist/{chunk-PYHNM47K.js → chunk-DCWOQ5PN.js} +2 -2
  7. package/dist/{chunk-6N2HEV3U.js → chunk-OS4TSIFU.js} +190 -12
  8. package/dist/chunk-OS4TSIFU.js.map +1 -0
  9. package/dist/chunk-SGOTN5PX.js +345 -0
  10. package/dist/chunk-SGOTN5PX.js.map +1 -0
  11. package/dist/{chunk-HEXLCTOG.js → chunk-TVZU4HNT.js} +1 -1
  12. package/dist/chunk-TVZU4HNT.js.map +1 -0
  13. package/dist/{chunk-BMCERPQX.js → chunk-YWMEIMO3.js} +221 -27
  14. package/dist/chunk-YWMEIMO3.js.map +1 -0
  15. package/dist/{client-B4EQCRD_.d.ts → client-11sncog4.d.ts} +1 -1
  16. package/dist/{engine-wmW-VuBL.d.ts → engine-C_3RK8wC.d.ts} +207 -64
  17. package/dist/hono/index.d.ts +2 -2
  18. package/dist/hono/index.js +3 -3
  19. package/dist/ifood/index.d.ts +5 -2
  20. package/dist/ifood/index.js +125 -7
  21. package/dist/ifood/index.js.map +1 -1
  22. package/dist/index.d.ts +23 -4
  23. package/dist/index.js +280 -26
  24. package/dist/index.js.map +1 -1
  25. package/dist/keeta/index.d.ts +2 -2
  26. package/dist/keeta/index.js +2 -2
  27. package/dist/manifest/index.d.ts +223 -2
  28. package/dist/manifest/index.js +1 -1
  29. package/dist/manifest/server.d.ts +2 -2
  30. package/dist/manifest/server.js +3 -3
  31. package/dist/rappi/index.d.ts +1 -1
  32. package/dist/rappi/index.js +1 -1
  33. package/dist/server/en-US.d.ts +13 -0
  34. package/dist/server/en-US.js +13 -0
  35. package/dist/server/en-US.js.map +1 -1
  36. package/dist/server/index.d.ts +246 -8
  37. package/dist/server/index.js +3 -3
  38. package/dist/server/pt-BR.d.ts +13 -0
  39. package/dist/server/pt-BR.js +13 -0
  40. package/dist/server/pt-BR.js.map +1 -1
  41. package/package.json +1 -1
  42. package/prisma/marketplace.prisma +47 -0
  43. package/prisma/migrations/20261126230000_marketplace_menu_link_variation/migration.sql +11 -0
  44. package/prisma/migrations/20261127090000_marketplace_app_link/migration.sql +81 -0
  45. package/src/core/adapter.ts +21 -0
  46. package/src/core/bulk.ts +77 -15
  47. package/src/core/engine.ts +59 -3
  48. package/src/core/ingest.ts +2 -1
  49. package/src/core/integration.ts +60 -32
  50. package/src/core/link-store.ts +170 -0
  51. package/src/core/linking-port.ts +100 -0
  52. package/src/core/linking.ts +363 -0
  53. package/src/core/menu-links.ts +36 -6
  54. package/src/core/merchant-claim.ts +106 -0
  55. package/src/core/order-types.ts +74 -0
  56. package/src/core/ports.ts +26 -65
  57. package/src/ifood/index.ts +4 -0
  58. package/src/ifood/linking.ts +170 -0
  59. package/src/ifood/outbound.ts +10 -3
  60. package/src/index.ts +14 -0
  61. package/src/server/copy.ts +20 -2
  62. package/src/server/en-US.ts +13 -0
  63. package/src/server/index.ts +1 -1
  64. package/src/server/link-routes.ts +140 -0
  65. package/src/server/mcp-link.ts +103 -0
  66. package/src/server/mcp.ts +13 -4
  67. package/src/server/pt-BR.ts +13 -0
  68. package/src/server/routes.ts +5 -2
  69. package/src/server/webhook.ts +86 -0
  70. package/dist/chunk-6N2HEV3U.js.map +0 -1
  71. package/dist/chunk-BMCERPQX.js.map +0 -1
  72. package/dist/chunk-HEXLCTOG.js.map +0 -1
  73. package/dist/chunk-NP4EYKPO.js +0 -252
  74. package/dist/chunk-NP4EYKPO.js.map +0 -1
  75. /package/dist/{chunk-PYHNM47K.js.map → chunk-DCWOQ5PN.js.map} +0 -0
package/dist/index.js CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  MARKETPLACE_FETCH_ORDER_JOB,
13
13
  MARKETPLACE_OUTBOUND_JOB,
14
14
  MarketplaceAdapterRegistrationError,
15
+ MarketplaceMerchantTakenError,
15
16
  NO_FAILURE,
16
17
  NO_STANDING_REQUEST,
17
18
  OUTBOUND_GIVE_UP_MS,
@@ -19,8 +20,10 @@ import {
19
20
  OutboundRetryError,
20
21
  PROVIDER_ID_PATTERN,
21
22
  STORE_PAUSE_LEASE_MS,
23
+ appCredentialsOf,
22
24
  availabilityDedupeKey,
23
25
  awaitOrderBody,
26
+ cacheLinkToken,
24
27
  cancelAcceptance,
25
28
  cancelledBeforeIngest,
26
29
  catalogueConnection,
@@ -34,14 +37,18 @@ import {
34
37
  enqueueOutbound,
35
38
  expireLapsedAcceptances,
36
39
  failCancellationRequest,
40
+ guardMerchantClaim,
37
41
  hasPauseTable,
38
42
  holdsSomething,
39
43
  ingestMarketplaceOrder,
44
+ isUniqueViolation,
45
+ linkTokenKey,
40
46
  listMarketplaceIntegrations,
41
47
  listMarketplaceMenuLinks,
42
48
  listPendingAcceptances,
43
49
  listRetryableInboxEvents,
44
50
  markCancelledBeforeIngest,
51
+ merchantHeldElsewhere,
45
52
  merchantMismatch,
46
53
  notPendingProblem,
47
54
  noteMarketplaceStep,
@@ -64,6 +71,7 @@ import {
64
71
  runFetchOrder,
65
72
  runOutbound,
66
73
  saveMarketplaceIntegration,
74
+ sealLink,
67
75
  settleInboxEvent,
68
76
  statusDedupeKey,
69
77
  statusTable,
@@ -72,7 +80,7 @@ import {
72
80
  tellCancellationFailed,
73
81
  upsertLink,
74
82
  viewOf
75
- } from "./chunk-BMCERPQX.js";
83
+ } from "./chunk-YWMEIMO3.js";
76
84
  import {
77
85
  centsFromMajor
78
86
  } from "./chunk-WN2EK4KX.js";
@@ -83,16 +91,16 @@ import {
83
91
  answered,
84
92
  outboundResultOf,
85
93
  tokenGrantResultOf
86
- } from "./chunk-HEXLCTOG.js";
94
+ } from "./chunk-TVZU4HNT.js";
87
95
  import {
88
96
  __name
89
97
  } from "./chunk-7QVYU63E.js";
90
98
 
91
99
  // src/core/bulk.ts
92
- function duplicates(rows, keyOf, list, field) {
100
+ function duplicates(rows, keyOf2, list, field) {
93
101
  const seen = /* @__PURE__ */ new Set();
94
102
  return rows.flatMap((row, index) => {
95
- const key = keyOf(row);
103
+ const key = keyOf2(row);
96
104
  if (!seen.has(key)) {
97
105
  seen.add(key);
98
106
  return [];
@@ -117,6 +125,19 @@ function integrationRowProblems(row, index, existing) {
117
125
  return changes ? [] : [{ path: ["integrations", index], code: "NOTHING_TO_UPDATE" }];
118
126
  }
119
127
  __name(integrationRowProblems, "integrationRowProblems");
128
+ async function merchantProblems(ctx, clientId, rows, merchantOf) {
129
+ const db = await ctx.ports.db();
130
+ const problems = [];
131
+ for (const [index, row] of rows.entries()) {
132
+ const unarchive = row.operation === "unarchive";
133
+ const merchantId = unarchive ? merchantOf.get(row.provider) : "externalMerchantId" in row ? row.externalMerchantId : null;
134
+ if (row.operation === "archive" || !merchantId) continue;
135
+ if (!await merchantHeldElsewhere(db, clientId, row.provider, merchantId)) continue;
136
+ problems.push({ path: ["integrations", index, unarchive ? "provider" : "externalMerchantId"], code: "MERCHANT_TAKEN" });
137
+ }
138
+ return problems;
139
+ }
140
+ __name(merchantProblems, "merchantProblems");
120
141
  var ValidateOnly = class extends Error {
121
142
  static {
122
143
  __name(this, "ValidateOnly");
@@ -152,21 +173,29 @@ async function writeIntegration(ctx, db, clientId, row, now) {
152
173
  }
153
174
  __name(writeIntegration, "writeIntegration");
154
175
  async function upsertIntegrations(ctx, input) {
155
- const existing = new Set(
156
- (await listMarketplaceIntegrations(ctx, input.clientId, { includeArchived: true })).map((row) => row.provider)
157
- );
176
+ const stored = await listMarketplaceIntegrations(ctx, input.clientId, { includeArchived: true });
177
+ const existing = new Set(stored.map((row) => row.provider));
178
+ const merchantOf = new Map(stored.map((row) => [row.provider, row.externalMerchantId]));
158
179
  const problems = [
159
180
  ...duplicates(input.rows, (row) => row.provider, "integrations", "provider"),
160
181
  ...unknownProviders(ctx, input.rows, "integrations"),
161
182
  ...input.rows.flatMap((row, index) => integrationRowProblems(row, index, existing))
162
183
  ];
184
+ if (problems.length === 0) problems.push(...await merchantProblems(ctx, input.clientId, input.rows, merchantOf));
163
185
  if (problems.length > 0) return { kind: "refused", problems };
164
186
  const validateOnly = input.validateOnly === true;
165
187
  const now = ctx.ports.clock.now();
166
- await inTransaction(ctx, validateOnly, async (db) => {
167
- for (const row of input.rows) await writeIntegration(ctx, db, input.clientId, row, now);
168
- await auditArchives(ctx, db, input, now);
169
- });
188
+ try {
189
+ await inTransaction(ctx, validateOnly, async (db) => {
190
+ for (const row of input.rows) await writeIntegration(ctx, db, input.clientId, row, now);
191
+ await auditArchives(ctx, db, input, now);
192
+ });
193
+ } catch (error) {
194
+ const raced = error instanceof MarketplaceMerchantTakenError || isUniqueViolation(error);
195
+ const lost = raced ? await merchantProblems(ctx, input.clientId, input.rows, merchantOf) : [];
196
+ if (lost.length === 0) throw error;
197
+ return { kind: "refused", problems: lost };
198
+ }
170
199
  const providers = input.rows.map((row) => row.provider);
171
200
  const rows = validateOnly ? [] : await listMarketplaceIntegrations(ctx, input.clientId, { providers, includeArchived: true });
172
201
  return { kind: "saved", validateOnly, rows };
@@ -187,16 +216,27 @@ async function auditArchives(ctx, db, input, now) {
187
216
  }
188
217
  }
189
218
  __name(auditArchives, "auditArchives");
219
+ async function linkRowProblems(ctx, clientId, row, index) {
220
+ const variationPath = ["links", index, "variationId"];
221
+ const variationId = row.variationId ?? null;
222
+ if (row.menuItemId === null) {
223
+ return variationId === null ? [] : [{ path: variationPath, code: "CATALOG_ITEM_NOT_FOUND" }];
224
+ }
225
+ if (!await ctx.ports.order.catalogHas(clientId, row.menuItemId)) {
226
+ return [{ path: ["links", index, "menuItemId"], code: "CATALOG_ITEM_NOT_FOUND" }];
227
+ }
228
+ if (variationId === null) return [];
229
+ const order = ctx.ports.order;
230
+ const belongs = order.catalogHasVariation ? await order.catalogHasVariation(clientId, row.menuItemId, variationId) : false;
231
+ return belongs ? [] : [{ path: variationPath, code: "CATALOG_ITEM_NOT_FOUND" }];
232
+ }
233
+ __name(linkRowProblems, "linkRowProblems");
190
234
  async function upsertMenuLinks(ctx, input) {
191
235
  const problems = [
192
236
  ...duplicates(input.rows, (row) => `${row.provider}\0${row.externalSku}`, "links", "externalSku"),
193
237
  ...unknownProviders(ctx, input.rows, "links")
194
238
  ];
195
- for (const [index, row] of input.rows.entries()) {
196
- if (row.menuItemId !== null && !await ctx.ports.order.catalogHas(input.clientId, row.menuItemId)) {
197
- problems.push({ path: ["links", index, "menuItemId"], code: "CATALOG_ITEM_NOT_FOUND" });
198
- }
199
- }
239
+ for (const [index, row] of input.rows.entries()) problems.push(...await linkRowProblems(ctx, input.clientId, row, index));
200
240
  if (problems.length > 0) return { kind: "refused", problems };
201
241
  const validateOnly = input.validateOnly === true;
202
242
  const written = await inTransaction(ctx, validateOnly, async (db) => {
@@ -274,7 +314,7 @@ function requestOnly(ctx, plan) {
274
314
  __name(requestOnly, "requestOnly");
275
315
  async function admitAndClaim(ctx, clientId, planned, validateOnly) {
276
316
  await ctx.ports.transaction(async (tx) => {
277
- const refused2 = [];
317
+ const refused3 = [];
278
318
  for (const one of planned) {
279
319
  const admission = one.input.decision === "ACCEPT" ? one.input.admission ?? {} : {};
280
320
  const answer = await ctx.ports.order.admit({
@@ -286,18 +326,18 @@ async function admitAndClaim(ctx, clientId, planned, validateOnly) {
286
326
  });
287
327
  if (!answer.admitted) {
288
328
  const host = { code: answer.code, message: answer.message, details: answer.details };
289
- refused2.push({ path: ["decisions", one.index], code: "HOST_REFUSED", host });
329
+ refused3.push({ path: ["decisions", one.index], code: "HOST_REFUSED", host });
290
330
  }
291
331
  }
292
- if (refused2.length > 0) throw new Rollback(refused2);
332
+ if (refused3.length > 0) throw new Rollback(refused3);
293
333
  for (const one of planned) {
294
334
  const claimed = await tx.marketplaceAcceptance.updateMany({
295
335
  where: { orderId: one.input.orderId, clientId, status: "AWAITING", ...NO_STANDING_REQUEST },
296
336
  data: one.data
297
337
  });
298
- if (claimed.count === 0) refused2.push({ path: ["decisions", one.index, "orderId"], code: "CONFLICT" });
338
+ if (claimed.count === 0) refused3.push({ path: ["decisions", one.index, "orderId"], code: "CONFLICT" });
299
339
  }
300
- if (refused2.length > 0) throw new Rollback(refused2);
340
+ if (refused3.length > 0) throw new Rollback(refused3);
301
341
  if (validateOnly) throw new Rollback(null);
302
342
  });
303
343
  }
@@ -555,6 +595,210 @@ var engineRefusal = /* @__PURE__ */ __name((code) => ({
555
595
  message: null
556
596
  }), "engineRefusal");
557
597
 
598
+ // src/core/linking.ts
599
+ var refused2 = /* @__PURE__ */ __name((code, status = null, message = null) => ({
600
+ kind: "refused",
601
+ code,
602
+ status,
603
+ message
604
+ }), "refused");
605
+ var pendingOf = /* @__PURE__ */ __name((row) => ({
606
+ userCode: row.userCode,
607
+ verificationUrl: row.verificationUrl,
608
+ verificationUrlComplete: row.verificationUrlComplete,
609
+ expiresAt: row.expiresAt
610
+ }), "pendingOf");
611
+ async function linkingOf(ctx, provider, environment) {
612
+ const linking = ctx.registry.get(provider)?.linking;
613
+ if (!linking) return null;
614
+ const attempts = (await ctx.ports.db()).marketplaceLinkAttempt;
615
+ if (!attempts) return null;
616
+ const app = await appCredentialsOf(ctx, provider, environment);
617
+ if (!app) return null;
618
+ return { linking, attempts, call: { http: ctx.ports.http, credentials: app, environment, now: ctx.ports.clock.now() } };
619
+ }
620
+ __name(linkingOf, "linkingOf");
621
+ var keyOf = /* @__PURE__ */ __name((clientId, provider) => ({ clientId_provider: { clientId, provider } }), "keyOf");
622
+ async function linkState(ctx, input) {
623
+ const ready = await linkingOf(ctx, input.provider, input.environment ?? "PRODUCTION");
624
+ if (!ready) return { available: false, pending: null };
625
+ const row = await ready.attempts.findUnique({ where: keyOf(input.clientId, input.provider) });
626
+ const live = row && row.expiresAt.getTime() > ctx.ports.clock.now().getTime();
627
+ return { available: true, pending: live ? pendingOf(row) : null };
628
+ }
629
+ __name(linkState, "linkState");
630
+ async function startLink(ctx, input) {
631
+ const environment = input.environment ?? "PRODUCTION";
632
+ const ready = await linkingOf(ctx, input.provider, environment);
633
+ if (!ready) return refused2("UNAVAILABLE");
634
+ const answer = await ready.linking.requestCode(ready.call);
635
+ if (answer.kind === "retry") return answer;
636
+ if (answer.kind === "refused") return refused2("MARKETPLACE_REFUSED", answer.status, answer.message);
637
+ const code = answer.value;
638
+ const row = {
639
+ environment,
640
+ verifier: ctx.ports.secrets.seal(code.verifier),
641
+ userCode: code.userCode,
642
+ verificationUrl: code.verificationUrl,
643
+ verificationUrlComplete: code.verificationUrlComplete,
644
+ expiresAt: new Date(ready.call.now.getTime() + code.expiresInSeconds * 1e3)
645
+ };
646
+ await ready.attempts.upsert({
647
+ where: keyOf(input.clientId, input.provider),
648
+ create: { clientId: input.clientId, provider: input.provider, ...row },
649
+ update: row
650
+ });
651
+ return { kind: "started", pending: pendingOf(row) };
652
+ }
653
+ __name(startLink, "startLink");
654
+ async function chooseMerchant(db, input, merchants, current) {
655
+ if (!merchants) return current;
656
+ const candidate = merchants.length === 1 ? merchants[0].id : merchants.some((merchant) => merchant.id === current) ? current : null;
657
+ if (candidate === null) return null;
658
+ return await merchantHeldElsewhere(db, input.clientId, input.provider, candidate) ? null : candidate;
659
+ }
660
+ __name(chooseMerchant, "chooseMerchant");
661
+ async function saveLink(ctx, input, link) {
662
+ const now = ctx.ports.clock.now();
663
+ const credentials = sealLink(ctx, link.refreshToken);
664
+ await ctx.ports.transaction(async (db) => {
665
+ const existing = await db.marketplaceIntegration.findUnique({
666
+ where: keyOf(input.clientId, input.provider),
667
+ select: { archivedAt: true, externalMerchantId: true }
668
+ });
669
+ const data = {
670
+ credentials,
671
+ authMode: "LINKED",
672
+ environment: link.environment,
673
+ status: "VERIFIED",
674
+ lastVerifiedAt: now,
675
+ archivedAt: null,
676
+ externalMerchantId: await chooseMerchant(db, input, link.merchants, existing?.externalMerchantId ?? null),
677
+ ...input.enabled === void 0 ? {} : { enabled: input.enabled }
678
+ };
679
+ await db.marketplaceIntegration.upsert({
680
+ where: keyOf(input.clientId, input.provider),
681
+ create: { clientId: input.clientId, provider: input.provider, ackSlaSeconds: ctx.ports.defaultAckSlaSeconds, ...data },
682
+ update: data
683
+ });
684
+ if (existing?.archivedAt) {
685
+ await ctx.ports.audit.record(
686
+ {
687
+ clientId: input.clientId,
688
+ actorId: input.actorId,
689
+ action: "marketplace.integration.unarchive",
690
+ provider: input.provider,
691
+ reason: "linked again",
692
+ at: now
693
+ },
694
+ db
695
+ );
696
+ }
697
+ await db.marketplaceLinkAttempt.deleteMany({ where: { clientId: input.clientId, provider: input.provider, verifier: link.verifier } });
698
+ });
699
+ return credentials;
700
+ }
701
+ __name(saveLink, "saveLink");
702
+ async function saveLinkKeepingTokens(ctx, input, link) {
703
+ try {
704
+ return await saveLink(ctx, input, link);
705
+ } catch (error) {
706
+ if (!isUniqueViolation(error)) throw error;
707
+ ctx.ports.logger.warn(`marketplace.link: ${input.provider} merchant of ${input.clientId} taken meanwhile; none chosen`);
708
+ return saveLink(ctx, input, { ...link, merchants: [] });
709
+ }
710
+ }
711
+ __name(saveLinkKeepingTokens, "saveLinkKeepingTokens");
712
+ async function viewOf2(ctx, clientId, provider) {
713
+ const [view] = await listMarketplaceIntegrations(ctx, clientId, { providers: [provider] });
714
+ if (!view) throw new Error(`The ${provider} connection of ${clientId} was not saved.`);
715
+ return view;
716
+ }
717
+ __name(viewOf2, "viewOf");
718
+ async function finishLink(ctx, input) {
719
+ const opened = await openAttempt(ctx, input);
720
+ if ("kind" in opened) return opened;
721
+ const { ready, environment, verifier, sealedVerifier } = opened;
722
+ const exchanged = await ready.linking.exchange(ready.call, { authorizationCode: input.authorizationCode.trim(), verifier });
723
+ if (exchanged.kind === "retry") return exchanged;
724
+ if (exchanged.kind === "refused") return refused2("CODE_REFUSED", exchanged.status, exchanged.message);
725
+ const grant = exchanged.value;
726
+ if (grant.refreshToken === null) return refused2("CODE_REFUSED", null, "the marketplace answered no refresh token");
727
+ const listed = await ready.linking.merchants(ready.call, { accessToken: grant.accessToken });
728
+ const merchants = listed.kind === "ok" ? listed.value : null;
729
+ if (listed.kind !== "ok") {
730
+ ctx.ports.logger.warn(`marketplace.link: ${input.provider} merchants of ${input.clientId} not listed (${listed.kind})`);
731
+ }
732
+ const sealed = await saveLinkKeepingTokens(ctx, input, { environment, refreshToken: grant.refreshToken, merchants, verifier: sealedVerifier });
733
+ await cacheLinkToken(ctx, { ...input, sealed }, linkTokenKey(input.provider, environment, input.clientId), grant);
734
+ ctx.ports.publishChanged(input.clientId);
735
+ return { kind: "linked", integration: await viewOf2(ctx, input.clientId, input.provider), merchants };
736
+ }
737
+ __name(finishLink, "finishLink");
738
+ async function openAttempt(ctx, input) {
739
+ const attempts = (await ctx.ports.db()).marketplaceLinkAttempt;
740
+ if (!attempts) return refused2("UNAVAILABLE");
741
+ const attempt = await attempts.findUnique({ where: keyOf(input.clientId, input.provider) });
742
+ if (!attempt) return refused2("NO_LINK_IN_PROGRESS");
743
+ const environment = attempt.environment === "SANDBOX" ? "SANDBOX" : "PRODUCTION";
744
+ const ready = await linkingOf(ctx, input.provider, environment);
745
+ if (!ready) return refused2("UNAVAILABLE");
746
+ if (attempt.expiresAt.getTime() <= ready.call.now.getTime()) return refused2("LINK_EXPIRED");
747
+ return { ready, environment, verifier: ctx.ports.secrets.open(attempt.verifier), sealedVerifier: attempt.verifier };
748
+ }
749
+ __name(openAttempt, "openAttempt");
750
+ async function grantCall(ctx, clientId, provider) {
751
+ const views = await listMarketplaceIntegrations(ctx, clientId, { providers: [provider] });
752
+ if (views[0]?.authMode !== "LINKED") return refused2("NOT_LINKED");
753
+ const connection = await readOutboundConnection(ctx, clientId, provider).catch(() => null);
754
+ if (!connection?.grant) return refused2("UNAVAILABLE");
755
+ const token = await connection.grant.accessToken();
756
+ if ("token" in token) {
757
+ const call = { http: ctx.ports.http, credentials: connection.credentials, environment: connection.environment, now: ctx.ports.clock.now() };
758
+ return { call, accessToken: token.token };
759
+ }
760
+ if (token.kind === "retry") return token;
761
+ return token.kind === "refused" ? refused2("NOT_LINKED", token.status, token.message) : refused2("NOT_LINKED");
762
+ }
763
+ __name(grantCall, "grantCall");
764
+ async function grantMerchants(ctx, clientId, provider) {
765
+ const linking = ctx.registry.get(provider)?.linking;
766
+ if (!linking) return refused2("UNAVAILABLE");
767
+ const granted = await grantCall(ctx, clientId, provider);
768
+ if ("kind" in granted) return granted;
769
+ const listed = await linking.merchants(granted.call, { accessToken: granted.accessToken });
770
+ if (listed.kind === "ok") return listed.value;
771
+ return listed.kind === "retry" ? listed : refused2("MARKETPLACE_REFUSED", listed.status, listed.message);
772
+ }
773
+ __name(grantMerchants, "grantMerchants");
774
+ async function linkedMerchants(ctx, input) {
775
+ const merchants = await grantMerchants(ctx, input.clientId, input.provider);
776
+ return Array.isArray(merchants) ? { kind: "listed", merchants } : merchants;
777
+ }
778
+ __name(linkedMerchants, "linkedMerchants");
779
+ async function selectLinkedMerchant(ctx, input) {
780
+ const merchants = await grantMerchants(ctx, input.clientId, input.provider);
781
+ if (!Array.isArray(merchants)) return merchants;
782
+ if (!merchants.some((merchant) => merchant.id === input.merchantId)) return refused2("UNKNOWN_MERCHANT");
783
+ const db = await ctx.ports.db();
784
+ if (await merchantHeldElsewhere(db, input.clientId, input.provider, input.merchantId)) return refused2("MERCHANT_TAKEN");
785
+ const write = /* @__PURE__ */ __name(() => db.marketplaceIntegration.updateMany({
786
+ where: { clientId: input.clientId, provider: input.provider, authMode: "LINKED", archivedAt: null },
787
+ data: { externalMerchantId: input.merchantId }
788
+ }), "write");
789
+ const taken = await guardMerchantClaim(ctx, { ...input, merchantId: input.merchantId }, write).then(
790
+ () => false,
791
+ (error) => {
792
+ if (error instanceof MarketplaceMerchantTakenError) return true;
793
+ throw error;
794
+ }
795
+ );
796
+ if (taken) return refused2("MERCHANT_TAKEN");
797
+ ctx.ports.publishChanged(input.clientId);
798
+ return { kind: "selected", integration: await viewOf2(ctx, input.clientId, input.provider) };
799
+ }
800
+ __name(selectLinkedMerchant, "selectLinkedMerchant");
801
+
558
802
  // src/core/status-inform.ts
559
803
  async function informStatus(ctx, input) {
560
804
  const payload = { clientId: input.clientId, orderId: input.orderId, action: "status", step: input.step, claimKey: String(input.at.getTime()) };
@@ -725,7 +969,7 @@ var NEVER_ASKED = {
725
969
  resumedAt: null,
726
970
  updatedAt: null
727
971
  };
728
- function viewOf2(ctx, provider, connection, row) {
972
+ function viewOf3(ctx, provider, connection, row) {
729
973
  const availability = ctx.registry.get(provider)?.availability;
730
974
  const recorded = row ? {
731
975
  state: row.state,
@@ -746,18 +990,18 @@ function viewOf2(ctx, provider, connection, row) {
746
990
  ...recorded
747
991
  };
748
992
  }
749
- __name(viewOf2, "viewOf");
993
+ __name(viewOf3, "viewOf");
750
994
  async function availabilityState(ctx, clientId) {
751
995
  const db = await ctx.ports.db();
752
996
  const connections = await liveConnections(ctx, clientId);
753
997
  const rows = db.marketplaceStorePause ? await db.marketplaceStorePause.findMany({ where: { clientId } }) : [];
754
998
  const byProvider = new Map(rows.map((row) => [row.provider, row]));
755
999
  const views = connections.map(
756
- (connection) => viewOf2(ctx, connection.provider, connection, byProvider.get(connection.provider))
1000
+ (connection) => viewOf3(ctx, connection.provider, connection, byProvider.get(connection.provider))
757
1001
  );
758
1002
  const live = new Set(connections.map((connection) => connection.provider));
759
1003
  for (const row of rows) {
760
- if (!live.has(row.provider) && holdsSomething(row)) views.push(viewOf2(ctx, row.provider, void 0, row));
1004
+ if (!live.has(row.provider) && holdsSomething(row)) views.push(viewOf3(ctx, row.provider, void 0, row));
761
1005
  }
762
1006
  return views;
763
1007
  }
@@ -1103,8 +1347,17 @@ function createMarketplaceEngine(config) {
1103
1347
  ingest: /* @__PURE__ */ __name((input) => ingestMarketplaceOrder(ctx, input), "ingest"),
1104
1348
  deliver: /* @__PURE__ */ __name((input) => processDelivery(ctx, input), "deliver"),
1105
1349
  integrations: /* @__PURE__ */ __name((clientId, options) => listMarketplaceIntegrations(ctx, clientId, options), "integrations"),
1106
- saveIntegration: /* @__PURE__ */ __name(async (input) => saveMarketplaceIntegration(ctx, input, await ports.db()), "saveIntegration"),
1350
+ saveIntegration: /* @__PURE__ */ __name((input) => guardMerchantClaim(
1351
+ ctx,
1352
+ { ...input, merchantId: input.externalMerchantId },
1353
+ async () => saveMarketplaceIntegration(ctx, input, await ports.db())
1354
+ ), "saveIntegration"),
1107
1355
  upsertIntegrations: /* @__PURE__ */ __name((input) => upsertIntegrations(ctx, input), "upsertIntegrations"),
1356
+ linkState: /* @__PURE__ */ __name((input) => linkState(ctx, input), "linkState"),
1357
+ startLink: /* @__PURE__ */ __name((input) => startLink(ctx, input), "startLink"),
1358
+ finishLink: /* @__PURE__ */ __name((input) => finishLink(ctx, input), "finishLink"),
1359
+ linkedMerchants: /* @__PURE__ */ __name((input) => linkedMerchants(ctx, input), "linkedMerchants"),
1360
+ selectLinkedMerchant: /* @__PURE__ */ __name((input) => selectLinkedMerchant(ctx, input), "selectLinkedMerchant"),
1108
1361
  menuLinks: /* @__PURE__ */ __name((input) => listMarketplaceMenuLinks(ctx, input), "menuLinks"),
1109
1362
  upsertMenuLinks: /* @__PURE__ */ __name((input) => upsertMenuLinks(ctx, input), "upsertMenuLinks"),
1110
1363
  setMenuLink: /* @__PURE__ */ __name(async ({ clientId, ...row }) => {
@@ -1151,6 +1404,7 @@ export {
1151
1404
  MARKETPLACE_FETCH_ORDER_JOB,
1152
1405
  MARKETPLACE_OUTBOUND_JOB,
1153
1406
  MarketplaceAdapterRegistrationError,
1407
+ MarketplaceMerchantTakenError,
1154
1408
  OUTBOUND_GIVE_UP_MS,
1155
1409
  OUTBOUND_STALE_MS,
1156
1410
  OutboundRetryError,