@12-apps/marketplace 1.10.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 (71) hide show
  1. package/ADOPTING.md +36 -0
  2. package/README.md +63 -0
  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-WVZ2IXFH.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-2BA2EHNF.js → chunk-YWMEIMO3.js} +206 -22
  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-DK3iV_Kk.d.ts → engine-C_3RK8wC.d.ts} +116 -4
  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 +264 -21
  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 +219 -1
  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 +241 -7
  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 +41 -0
  43. package/prisma/migrations/20261127090000_marketplace_app_link/migration.sql +81 -0
  44. package/src/core/adapter.ts +21 -0
  45. package/src/core/bulk.ts +43 -8
  46. package/src/core/engine.ts +59 -3
  47. package/src/core/integration.ts +60 -32
  48. package/src/core/link-store.ts +170 -0
  49. package/src/core/linking-port.ts +100 -0
  50. package/src/core/linking.ts +363 -0
  51. package/src/core/merchant-claim.ts +106 -0
  52. package/src/core/ports.ts +3 -0
  53. package/src/ifood/index.ts +4 -0
  54. package/src/ifood/linking.ts +170 -0
  55. package/src/ifood/outbound.ts +10 -3
  56. package/src/index.ts +14 -0
  57. package/src/server/copy.ts +20 -2
  58. package/src/server/en-US.ts +13 -0
  59. package/src/server/index.ts +1 -1
  60. package/src/server/link-routes.ts +140 -0
  61. package/src/server/mcp-link.ts +103 -0
  62. package/src/server/mcp.ts +6 -2
  63. package/src/server/pt-BR.ts +13 -0
  64. package/src/server/routes.ts +5 -2
  65. package/src/server/webhook.ts +86 -0
  66. package/dist/chunk-2BA2EHNF.js.map +0 -1
  67. package/dist/chunk-HEXLCTOG.js.map +0 -1
  68. package/dist/chunk-WVZ2IXFH.js.map +0 -1
  69. package/dist/chunk-ZO4S3LF4.js +0 -254
  70. package/dist/chunk-ZO4S3LF4.js.map +0 -1
  71. /package/dist/{chunk-PYHNM47K.js.map → chunk-DCWOQ5PN.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) {
@@ -161,6 +219,113 @@ async function forgetCategory(ctx, connection, name) {
161
219
  }
162
220
  __name(forgetCategory, "forgetCategory");
163
221
 
222
+ // src/core/link-store.ts
223
+ var TOKEN_MARGIN_MS = 6e4;
224
+ function sealLink(ctx, refreshToken) {
225
+ return ctx.ports.secrets.seal(JSON.stringify({ clientId: "", clientSecret: "", webhookSecret: null, refreshToken }));
226
+ }
227
+ __name(sealLink, "sealLink");
228
+ function openLinkRefreshToken(ctx, sealed) {
229
+ const parsed = JSON.parse(ctx.ports.secrets.open(sealed));
230
+ const token = typeof parsed === "object" && parsed !== null ? parsed.refreshToken : null;
231
+ if (typeof token !== "string" || token === "") throw new Error("The linked connection holds no refresh token.");
232
+ return token;
233
+ }
234
+ __name(openLinkRefreshToken, "openLinkRefreshToken");
235
+ async function appCredentialsOf(ctx, provider, environment) {
236
+ const port = ctx.ports.appCredentials;
237
+ if (!port) return null;
238
+ const credentials = await port(provider, environment);
239
+ return credentials && credentials.clientId !== "" && credentials.clientSecret !== "" ? credentials : null;
240
+ }
241
+ __name(appCredentialsOf, "appCredentialsOf");
242
+ var linkTokenKey = /* @__PURE__ */ __name((provider, environment, clientId) => `LINK:${provider}:${environment}:${clientId}`, "linkTokenKey");
243
+ async function cacheLinkToken(ctx, link, key, grant) {
244
+ const db = await ctx.ports.db();
245
+ const row = await db.marketplaceIntegration.findUnique({
246
+ where: { clientId_provider: { clientId: link.clientId, provider: link.provider } },
247
+ select: { credentials: true }
248
+ });
249
+ if (row?.credentials !== link.sealed) return false;
250
+ setToken(ctx, key, grant);
251
+ return true;
252
+ }
253
+ __name(cacheLinkToken, "cacheLinkToken");
254
+ function setToken(ctx, key, grant) {
255
+ const expiresAt = ctx.ports.clock.now().getTime() + Math.max(grant.expiresInSeconds, 1) * 1e3;
256
+ ctx.tokens.set(key, { token: grant.accessToken, expiresAt });
257
+ }
258
+ __name(setToken, "setToken");
259
+ var inflight = /* @__PURE__ */ new WeakMap();
260
+ async function storeRotated(ctx, link, refreshToken) {
261
+ const db = await ctx.ports.db();
262
+ const { count } = await db.marketplaceIntegration.updateMany({
263
+ where: { clientId: link.clientId, provider: link.provider, authMode: "LINKED", archivedAt: null, credentials: link.sealed },
264
+ data: { credentials: sealLink(ctx, refreshToken) }
265
+ });
266
+ return count > 0;
267
+ }
268
+ __name(storeRotated, "storeRotated");
269
+ async function markLinkFailed(ctx, link) {
270
+ const db = await ctx.ports.db();
271
+ const { count } = await db.marketplaceIntegration.updateMany({
272
+ where: { clientId: link.clientId, provider: link.provider, authMode: "LINKED", credentials: link.sealed },
273
+ data: { status: "FAILED" }
274
+ });
275
+ if (count > 0) ctx.ports.publishChanged(link.clientId);
276
+ return count > 0;
277
+ }
278
+ __name(markLinkFailed, "markLinkFailed");
279
+ var RELINKED = { kind: "retry", reason: "the connection was linked again during the refresh" };
280
+ async function refreshOnce(ctx, link, key) {
281
+ const linking = ctx.registry.get(link.provider)?.linking;
282
+ if (!linking) return { kind: "refused", status: 0, message: "this marketplace links no store", own: true };
283
+ const answer = await linking.refresh(
284
+ { http: ctx.ports.http, credentials: link.app, environment: link.environment, now: ctx.ports.clock.now() },
285
+ { refreshToken: link.refreshToken }
286
+ );
287
+ if (answer.kind === "retry") return answer;
288
+ if (answer.kind === "refused") return await markLinkFailed(ctx, link) ? { ...answer, own: true } : RELINKED;
289
+ const rotated = answer.value.refreshToken;
290
+ if (rotated === null || rotated === link.refreshToken) {
291
+ return await cacheLinkToken(ctx, link, key, answer.value) ? { token: answer.value.accessToken } : RELINKED;
292
+ }
293
+ const stored = await storeRotated(ctx, link, rotated).catch((error) => {
294
+ ctx.ports.logger.error(
295
+ `marketplace.link: ${link.provider} rotated refresh token of ${link.clientId} not stored: ` + (error instanceof Error ? error.message : String(error))
296
+ );
297
+ return null;
298
+ });
299
+ if (stored === false) return RELINKED;
300
+ setToken(ctx, key, answer.value);
301
+ return { token: answer.value.accessToken };
302
+ }
303
+ __name(refreshOnce, "refreshOnce");
304
+ function linkGrant(ctx, link) {
305
+ const key = linkTokenKey(link.provider, link.environment, link.clientId);
306
+ return {
307
+ key,
308
+ accessToken: /* @__PURE__ */ __name(async () => {
309
+ const cached = ctx.tokens.get(key);
310
+ if (cached && cached.expiresAt > ctx.ports.clock.now().getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
311
+ let running = inflight.get(ctx.tokens);
312
+ if (!running) {
313
+ running = /* @__PURE__ */ new Map();
314
+ inflight.set(ctx.tokens, running);
315
+ }
316
+ const pending = running.get(key);
317
+ if (pending) return pending;
318
+ const call = refreshOnce(ctx, link, key).catch((error) => ({
319
+ kind: "retry",
320
+ reason: error instanceof Error ? error.message : String(error)
321
+ })).finally(() => running.delete(key));
322
+ running.set(key, call);
323
+ return call;
324
+ }, "accessToken")
325
+ };
326
+ }
327
+ __name(linkGrant, "linkGrant");
328
+
164
329
  // src/core/integration.ts
165
330
  var VIEW_SELECT = {
166
331
  provider: true,
@@ -174,7 +339,8 @@ var VIEW_SELECT = {
174
339
  credentials: true,
175
340
  lastEventAt: true,
176
341
  lastVerifiedAt: true,
177
- archivedAt: true
342
+ archivedAt: true,
343
+ authMode: true
178
344
  };
179
345
  function toView(row) {
180
346
  return {
@@ -189,7 +355,8 @@ function toView(row) {
189
355
  connected: row.credentials !== "",
190
356
  lastEventAt: row.lastEventAt,
191
357
  lastVerifiedAt: row.lastVerifiedAt,
192
- archivedAt: row.archivedAt ?? null
358
+ archivedAt: row.archivedAt ?? null,
359
+ authMode: row.authMode === "LINKED" ? "LINKED" : "CREDENTIALS"
193
360
  };
194
361
  }
195
362
  __name(toView, "toView");
@@ -208,6 +375,7 @@ async function listMarketplaceIntegrations(ctx, clientId, options = {}) {
208
375
  }
209
376
  __name(listMarketplaceIntegrations, "listMarketplaceIntegrations");
210
377
  async function saveMarketplaceIntegration(ctx, input, db) {
378
+ await assertMerchantFree(db, input.clientId, input.provider, input.externalMerchantId);
211
379
  const sealed = input.credentials ? ctx.ports.secrets.seal(JSON.stringify(input.credentials)) : void 0;
212
380
  const mutable = {
213
381
  ...input.enabled === void 0 ? {} : { enabled: input.enabled },
@@ -216,7 +384,8 @@ async function saveMarketplaceIntegration(ctx, input, db) {
216
384
  ...input.autoAccept === void 0 ? {} : { autoAccept: input.autoAccept },
217
385
  ...input.followStatus === void 0 ? {} : { followStatus: input.followStatus },
218
386
  ...input.ackSlaSeconds === void 0 ? {} : { ackSlaSeconds: input.ackSlaSeconds },
219
- ...sealed === void 0 ? {} : { credentials: sealed, status: "UNVERIFIED" }
387
+ // Typed credentials make the connection the store's own app again.
388
+ ...sealed === void 0 ? {} : { credentials: sealed, status: "UNVERIFIED", authMode: "CREDENTIALS" }
220
389
  };
221
390
  const row = await db.marketplaceIntegration.upsert({
222
391
  where: { clientId_provider: { clientId: input.clientId, provider: input.provider } },
@@ -253,7 +422,9 @@ async function resolveIngestionTarget(ctx, clientId, provider) {
253
422
  ackSlaSeconds: true,
254
423
  credentials: true,
255
424
  archivedAt: true,
256
- externalMerchantId: true
425
+ externalMerchantId: true,
426
+ authMode: true,
427
+ environment: true
257
428
  }
258
429
  });
259
430
  if (!row || row.archivedAt) return null;
@@ -266,10 +437,22 @@ async function resolveIngestionTarget(ctx, clientId, provider) {
266
437
  // An unopenable blob must not read as "no secret configured" — that would
267
438
  // turn a key-rotation problem into an endpoint that accepts unsigned
268
439
  // deliveries. The secrets port throws instead, and the caller answers 401.
269
- webhookSecret: row.credentials === "" ? null : openCredentials(ctx, row.credentials).webhookSecret
440
+ webhookSecret: await webhookSecretOf(ctx, provider, row)
270
441
  };
271
442
  }
272
443
  __name(resolveIngestionTarget, "resolveIngestionTarget");
444
+ async function webhookSecretOf(ctx, provider, row) {
445
+ if (row.authMode !== "LINKED") {
446
+ return row.credentials === "" ? null : openCredentials(ctx, row.credentials).webhookSecret;
447
+ }
448
+ const app = await appCredentialsOf(ctx, provider, environmentOf(row.environment));
449
+ if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
450
+ const secret = app.webhookSecret || app.clientSecret;
451
+ if (!secret) throw new Error(`No webhook key is configured for ${provider}.`);
452
+ return secret;
453
+ }
454
+ __name(webhookSecretOf, "webhookSecretOf");
455
+ var environmentOf = /* @__PURE__ */ __name((value) => value === "PRODUCTION" ? "PRODUCTION" : "SANDBOX", "environmentOf");
273
456
  function openCredentials(ctx, sealed) {
274
457
  const parsed = JSON.parse(ctx.ports.secrets.open(sealed));
275
458
  if (typeof parsed !== "object" || parsed === null) {
@@ -283,16 +466,6 @@ function openCredentials(ctx, sealed) {
283
466
  };
284
467
  }
285
468
  __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
469
  async function markMarketplaceEventSeen(db, clientId, provider, at) {
297
470
  await db.marketplaceIntegration.updateMany({
298
471
  where: { clientId, provider },
@@ -304,13 +477,16 @@ async function readOutboundConnection(ctx, clientId, provider) {
304
477
  const db = await ctx.ports.db();
305
478
  const row = await db.marketplaceIntegration.findUnique({
306
479
  where: { clientId_provider: { clientId, provider } },
307
- select: { environment: true, credentials: true }
480
+ select: { environment: true, credentials: true, authMode: true }
308
481
  });
309
482
  if (!row || row.credentials === "") return null;
310
- return {
311
- environment: row.environment === "PRODUCTION" ? "PRODUCTION" : "SANDBOX",
312
- credentials: openCredentials(ctx, row.credentials)
313
- };
483
+ const environment = environmentOf(row.environment);
484
+ if (row.authMode !== "LINKED") return { environment, credentials: openCredentials(ctx, row.credentials) };
485
+ const app = await appCredentialsOf(ctx, provider, environment);
486
+ if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
487
+ const refreshToken = openLinkRefreshToken(ctx, row.credentials);
488
+ const link = { clientId, provider, environment, refreshToken, app, sealed: row.credentials };
489
+ return { environment, credentials: app, grant: linkGrant(ctx, link) };
314
490
  }
315
491
  __name(readOutboundConnection, "readOutboundConnection");
316
492
 
@@ -2149,11 +2325,19 @@ export {
2149
2325
  listPendingAcceptances,
2150
2326
  expireLapsedAcceptances,
2151
2327
  cancelAcceptance,
2328
+ sealLink,
2329
+ appCredentialsOf,
2330
+ linkTokenKey,
2331
+ cacheLinkToken,
2332
+ MarketplaceMerchantTakenError,
2333
+ isUniqueViolation,
2334
+ merchantHeldElsewhere,
2335
+ guardMerchantClaim,
2336
+ resolveTenantByMerchant,
2152
2337
  listMarketplaceIntegrations,
2153
2338
  saveMarketplaceIntegration,
2154
2339
  connectionMerchantId,
2155
2340
  resolveIngestionTarget,
2156
- resolveTenantByMerchant,
2157
2341
  readOutboundConnection,
2158
2342
  listMarketplaceMenuLinks,
2159
2343
  upsertLink,
@@ -2206,4 +2390,4 @@ export {
2206
2390
  AvailabilityRetryError,
2207
2391
  runAvailability
2208
2392
  };
2209
- //# sourceMappingURL=chunk-2BA2EHNF.js.map
2393
+ //# sourceMappingURL=chunk-YWMEIMO3.js.map