@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
package/ADOPTING.md CHANGED
@@ -34,6 +34,7 @@ error at mount, never a default that quietly adopts another host's policy.
34
34
  | `reconcileBatchSize` | `number` | Stored deliveries one reconciliation pass re-runs (origin: 50). |
35
35
  | `maxInboxAttempts` | `number` | Re-runs before a stored delivery is retired (origin: 5). |
36
36
  | `catalogue` | OPTIONAL. `{ items(clientId, productIds) => Promise<Map<string, CatalogueItem>>; image(url) => Promise<{ contentType; base64 } \| null> }` | Catalogue publishing (1.2, FUT-4768). `items` maps the host's products into `{ name, description, imageUrl, categoryName, priceCents }` (the store's price, smallest unit; the photo an absolute https URL that CHANGES when the photo changes, such as a content hash or upload id in it: a marketplace's uploaded copy is reused while the URL is the same), keyed by product id; a missing id is a product that no longer exists. Called at publish (to check it exists) and by the job when it sends, so what goes out is the product as it is then. `image` reads a photo's bytes for a marketplace that takes an upload (iFood); null publishes without a photo. Absent: every catalogue call answers `UNSUPPORTED`. |
37
+ | `appCredentials` | OPTIONAL. `(provider, environment) => { clientId; clientSecret; webhookSecret } \| null` (sync or async) | The software's OWN app on each marketplace, for linking a store without its own credentials (FUT-5613, section 9). Absent or null: linking is unavailable there and the per-store credentials work as before. |
37
38
  | `cancellationWindowMs` | OPTIONAL. `number` | For a host that requests first (binds `onCancellationConfirmed`): how long a store's cancellation request may wait (PENDING: not yet delivered, or REQUESTED: delivered and unanswered) before the outbound sweep fails it as TIMEOUT, for every adapter; a PENDING request's retries stop with it. A 1.0.0 host has no window: its requests are re-queued and given up after 24 hours, as before. Absent: each adapter's `capabilities.cancellationAnswerWindowMs` (iFood: 5 minutes, estimated); an adapter with none is given up on only after 24 hours. |
38
39
 
39
40
  Plus `adapters: readonly MarketplaceAdapter[]` — one per marketplace the host
@@ -240,6 +241,15 @@ not composed the model still compiles, and the two paths then do nothing.
240
241
  switches over either exhaustively adds the case; allow `"status"` in any
241
242
  action allow-list in front of the outbound job.
242
243
 
244
+ `20261127090000_marketplace_app_link` (FUT-5613) adds
245
+ `marketplace_integrations.auth_mode` (NOT NULL DEFAULT 'CREDENTIALS', CHECKed
246
+ CREDENTIALS | LINKED: every existing connection stays the store's own app) and
247
+ `marketplace_link_attempts`, one linking in progress per (store, marketplace)
248
+ with its sealed verifier, environment CHECKed and provider shape-checked.
249
+ Additive. Compose it with the schema in the same change as the engine bump:
250
+ the engine selects `auth_mode`. `MarketplaceDb.marketplaceLinkAttempt` is
251
+ optional in the type; without it linking reports itself unavailable.
252
+
243
253
  ## 6. What stays the host's
244
254
 
245
255
  The stock draw at the acceptance, the settlement effects, the board's and the
@@ -318,3 +328,29 @@ key, every existing link stays the item alone. The engine selects the column,
318
328
  so a Prisma client generated before the migration throws on the unknown
319
329
  `variationId`: on the bump, sync the partial, run `prisma generate` and apply
320
330
  the migration together.
331
+
332
+ ## 9. Linking a store through the software's own app
333
+
334
+ The flow and its routes are in the README ("Linking a store through the
335
+ software's own app"). What the host binds and decides:
336
+
337
+ - **`appCredentials`** (OPTIONAL port): `(provider, environment) =>
338
+ { clientId, clientSecret, webhookSecret } | null`, sync or async, read at
339
+ each use (a rotation reaches every linked store at once). Answer it from the
340
+ host's secret store; never from a store's row. Null or unbound: the screen
341
+ shows the per-store form, as before.
342
+ - **The app's webhook**: register `…/webhooks/marketplace/IFOOD` (under the
343
+ host's mount) as the app's one webhook address on iFood's developer portal,
344
+ iFood signs it with the app's client secret, so `webhookSecret` may be left
345
+ null; pass it only to verify with another key.
346
+ - **The screen** is the host's: `GET …/link` says whether to offer it and
347
+ restores a code in progress after a reload; `start`, `finish` and, when the
348
+ grant covers several iFood stores, `merchants` and `merchant`. Each refusal
349
+ answers a `code` (`UNAVAILABLE`, `NO_LINK_IN_PROGRESS`, `LINK_EXPIRED`,
350
+ `CODE_REFUSED`, `MARKETPLACE_REFUSED`, `NOT_LINKED`, `UNKNOWN_MERCHANT`,
351
+ `MERCHANT_TAKEN`; 503 `MARKETPLACE_UNREACHABLE`) and the pack's sentence
352
+ (`copy.link`, optional in the type, carried by both shipped packs).
353
+ - **Disconnect** is the existing archive (`PUT …/marketplace`, operation
354
+ `archive`): the row is kept; linking again unarchives it with its audit line.
355
+ - **A view** gains `authMode`; a host that switches on it treats an absent
356
+ value as `CREDENTIALS`.
package/README.md CHANGED
@@ -226,6 +226,69 @@ They live only in `src/ifood/outbound.ts` and `src/ifood/copy.ts`, whose
226
226
  headers say so, so the homologation run corrects two files. Tests never reach
227
227
  iFood: the HTTP client is the host's port.
228
228
 
229
+ ## Linking a store through the software's own app (FUT-5613)
230
+
231
+ A store connects iFood WITHOUT typing a client id, a secret, a webhook key or a
232
+ webhook address: it authorizes the software's own iFood app (iFood's
233
+ "distributed app") on iFood's portal. The host's screen is three steps; the
234
+ engine supplies each one:
235
+
236
+ | step | engine | route (`marketplace:manage`) |
237
+ |---|---|---|
238
+ | the code to copy, and the portal link that already carries it | `startLink({ clientId, provider, environment? })` → `{ userCode, verificationUrl, verificationUrlComplete, expiresAt }` | `POST …/marketplace/link/start` |
239
+ | the screen after a reload | `linkState(...)` → `{ available, pending }` | `GET …/marketplace/link?provider=` |
240
+ | the authorization code pasted back | `finishLink({ clientId, provider, authorizationCode, actorId, enabled? })` → `{ integration, merchants }` | `POST …/marketplace/link/finish` |
241
+ | a grant covering several iFood stores | `linkedMerchants(...)`, `selectLinkedMerchant({ …, merchantId })` | `GET …/link/merchants`, `PUT …/link/merchant` |
242
+
243
+ - **The verifier never leaves the server.** `startLink` seals iFood's
244
+ `authorizationCodeVerifier` with the host's secrets port into
245
+ `marketplace_link_attempts` (one per store and marketplace; starting again
246
+ replaces it; the exchange removes it). No answer carries a token, the
247
+ verifier or the app's credentials.
248
+ - **The tokens.** `finishLink` stores the refresh token sealed in the
249
+ connection's `credentials` and marks it `authMode: "LINKED"`, `VERIFIED`,
250
+ unarchived (a disconnected store reconnecting gets its `unarchive` audit
251
+ line). The merchant is selected when the grant covers exactly one, and
252
+ never when another store's live connection holds it. The access token lives
253
+ in the per-process cache, per STORE (never per app); a missing or expiring
254
+ one is refreshed once however many calls ask at once, and a rotated refresh
255
+ token is stored back. A refused refresh marks the connection `FAILED`: the
256
+ store links again.
257
+ - **The app's credentials** are the host's, through the optional
258
+ `appCredentials(provider, environment)` port (client id, secret, and
259
+ optionally a separate key the app's deliveries are signed with; absent or
260
+ empty, the client secret, which is what iFood signs with). Unbound, or null for a marketplace:
261
+ `available: false`, and a store's own credentials keep working exactly as
262
+ before. Typing credentials into a linked connection makes it `CREDENTIALS`
263
+ again.
264
+ - **One webhook address for every linked store:** `POST
265
+ /webhooks/marketplace/:provider`. The store is found by the merchant the
266
+ delivery names, and the delivery must carry a valid signature by the app's
267
+ key (unsigned is refused here, whatever the store's own setting). The
268
+ per-store address keeps working, and a linked store's never accepts an
269
+ unsigned delivery either. A merchant is held by one live connection of a
270
+ marketplace at a time: every write refuses `MERCHANT_TAKEN` at
271
+ `externalMerchantId`, and a partial unique index backs it. A linked
272
+ connection with no merchant chosen yet (the list failed, or the grant covers
273
+ several) has every delivery to this address refused, and iFood redelivers,
274
+ until the store chooses one.
275
+
276
+ What iFood's pages settle, read 2026-11-26 as Markdown
277
+ (`developer.ifood.com.br/pt-BR/docs/guides/modules/authentication/distributed.md`,
278
+ `…/merchant/endpoints.md`), and what they do not:
279
+
280
+ | fact | status |
281
+ |---|---|
282
+ | `POST /authentication/v1.0/oauth/userCode`, form `clientId` → `userCode`, `authorizationCodeVerifier`, `verificationUrl`, `verificationUrlComplete`, `expiresIn` (600: ten minutes) | CONFIRMED |
283
+ | `POST /authentication/v1.0/oauth/token`, form `grantType=authorization_code`, `clientId`, `clientSecret`, `authorizationCode`, `authorizationCodeVerifier`; and `grantType=refresh_token` with `refreshToken` | CONFIRMED |
284
+ | The token answer: `accessToken`, `type`, `expiresIn` (21600: six hours) | CONFIRMED |
285
+ | The refresh token's FIELD in that answer (`refreshToken`, `refresh_token` as a fallback) | ESTIMATED: the page says one is returned, its table lists none |
286
+ | Whether a refresh rotates the refresh token | ESTIMATED: stored when answered, kept when not |
287
+ | The refresh token's lifetime | ESTIMATED: unstated; a refused refresh marks the connection FAILED |
288
+ | `GET /merchant/v1.0/merchants?page=&size=` (size 100) → `[{ id, name, corporateName }]` | CONFIRMED |
289
+ | The status of a wrong or used authorization code | ESTIMATED: any final 4xx is `CODE_REFUSED` |
290
+ | The key iFood signs an app's webhook deliveries with | CONFIRMED (`webhook-signature.md`): the app's `client_secret`, the default when `webhookSecret` is absent |
291
+
229
292
  ## 99Food, on Open Delivery
230
293
 
231
294
  99Food completed Open Delivery (Abrasel) adherence, so its adapter speaks
@@ -1,5 +1,5 @@
1
- import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, C as CatalogueMenuEntry, b as CatalogueMenuOptions, P as PullCatalogue, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CYJzu1c9.js';
2
- import { O as OpenDeliveryApiBaseUrls } from '../client-B4EQCRD_.js';
1
+ import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, C as CatalogueMenuEntry, b as CatalogueMenuOptions, P as PullCatalogue, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CD0SfdVS.js';
2
+ import { O as OpenDeliveryApiBaseUrls } from '../client-11sncog4.js';
3
3
 
4
4
  /**
5
5
  * The words the 99Food adapter needs from its host, and nothing else.
@@ -12,10 +12,10 @@ import {
12
12
  openDeliveryStatus,
13
13
  openDeliverySwitchAvailability,
14
14
  verifyOpenDeliverySignature
15
- } from "../chunk-PYHNM47K.js";
15
+ } from "../chunk-DCWOQ5PN.js";
16
16
  import "../chunk-M2V4RFMA.js";
17
17
  import "../chunk-BD7DS3XM.js";
18
- import "../chunk-HEXLCTOG.js";
18
+ import "../chunk-TVZU4HNT.js";
19
19
  import {
20
20
  __name
21
21
  } from "../chunk-7QVYU63E.js";
@@ -303,6 +303,108 @@ interface CatalogueReader {
303
303
  */
304
304
  declare function centsFromMajor(value: unknown): number | null;
305
305
 
306
+ /**
307
+ * LINKING a store through the software's OWN marketplace app (FUT-5613): the
308
+ * store authorizes the software's app on the marketplace's portal, and never
309
+ * types a client id, a secret, a webhook key or a webhook address.
310
+ *
311
+ * The flow, as an adapter states it (iFood's "distributed app"):
312
+ *
313
+ * 1. `requestCode`: the app asks for a short code the store types (or a link
314
+ * that already carries it) on the marketplace's portal, plus a VERIFIER the
315
+ * engine keeps server-side for that store and never hands the browser.
316
+ * 2. The store authorizes the app on the portal and is shown an
317
+ * AUTHORIZATION CODE, which it pastes back.
318
+ * 3. `exchange`: the code plus the verifier buy an access token and a refresh
319
+ * token, stored sealed on the store's connection.
320
+ * 4. `merchants`: which of the marketplace's stores the grant covers; one is
321
+ * selected at once.
322
+ * 5. `refresh`: a new access token from the refresh token, whenever the
323
+ * cached one is gone. A rotated refresh token is stored back.
324
+ *
325
+ * The app's own credentials are the HOST's configuration, one pair per
326
+ * marketplace and environment ({@link MarketplaceAppCredentialsPort}), never a
327
+ * store's.
328
+ */
329
+ /** What a linking call is handed: the APP's credentials, never a store's. */
330
+ interface LinkCallContext {
331
+ http: MarketplaceHttp;
332
+ credentials: MarketplaceCredentials;
333
+ environment: "SANDBOX" | "PRODUCTION";
334
+ now: Date;
335
+ }
336
+ /** The code a store types on the marketplace's portal, and the verifier kept for it. */
337
+ interface LinkCode {
338
+ /** Shown to the person: they type it on the portal. */
339
+ userCode: string;
340
+ /** The portal page the code is typed on. */
341
+ verificationUrl: string;
342
+ /** The same page with the code already in it: the link the screen opens. */
343
+ verificationUrlComplete: string;
344
+ /** How long the code lives, in seconds. */
345
+ expiresInSeconds: number;
346
+ /** Kept server-side for this store until the exchange. NEVER sent to a browser. */
347
+ verifier: string;
348
+ }
349
+ /** What an exchange or a refresh buys. */
350
+ interface LinkGrant {
351
+ accessToken: string;
352
+ /** How long the access token lives, in seconds. */
353
+ expiresInSeconds: number;
354
+ /**
355
+ * The refresh token. An exchange always answers one; a refresh answers one
356
+ * when the marketplace rotates it, and null when the old one stays valid.
357
+ */
358
+ refreshToken: string | null;
359
+ }
360
+ /** One marketplace store the grant covers. */
361
+ interface LinkedMerchant {
362
+ id: string;
363
+ name: string | null;
364
+ corporateName: string | null;
365
+ }
366
+ /**
367
+ * A linking call's answer: the value, or why there is none. `refused` is
368
+ * final (the marketplace judged the request: a wrong or used code, a refresh
369
+ * token it no longer honours); `retry` is the network, a 5xx, a rate limit.
370
+ */
371
+ type LinkResult<T> = {
372
+ kind: "ok";
373
+ value: T;
374
+ } | Exclude<OutboundResult, {
375
+ kind: "accepted";
376
+ }>;
377
+ /** The adapter's half: the marketplace's wire format for each step, and nothing else. */
378
+ interface MarketplaceLinking {
379
+ requestCode(ctx: LinkCallContext): Promise<LinkResult<LinkCode>>;
380
+ exchange(ctx: LinkCallContext, input: {
381
+ authorizationCode: string;
382
+ verifier: string;
383
+ }): Promise<LinkResult<LinkGrant>>;
384
+ refresh(ctx: LinkCallContext, input: {
385
+ refreshToken: string;
386
+ }): Promise<LinkResult<LinkGrant>>;
387
+ merchants(ctx: LinkCallContext, input: {
388
+ accessToken: string;
389
+ }): Promise<LinkResult<LinkedMerchant[]>>;
390
+ }
391
+ /**
392
+ * The host's configuration of its OWN app on a marketplace: client id, client
393
+ * secret, and the key the marketplace signs the app's webhook deliveries with.
394
+ * Null (or the port not bound) means the software has no app there, and the
395
+ * linking flow reports itself unavailable; a store's own credentials keep
396
+ * working unchanged either way.
397
+ */
398
+ type MarketplaceAppCredentialsPort = (provider: string, environment: "SANDBOX" | "PRODUCTION") => MarketplaceCredentials | null | Promise<MarketplaceCredentials | null>;
399
+ /** The link-attempt delegate the engine reads and writes (the `MarketplaceLinkAttempt` model). */
400
+ interface MarketplaceLinkAttemptDelegate {
401
+ findUnique(args: unknown): Promise<unknown>;
402
+ upsert(args: unknown): Promise<unknown>;
403
+ deleteMany(args: unknown): Promise<{
404
+ count: number;
405
+ }>;
406
+ }
407
+
306
408
  /**
307
409
  * The adapter port's OPTIONAL availability capability: closing a store on a
308
410
  * marketplace for a while, and opening it again (FUT-4851).
@@ -705,14 +807,30 @@ type AdapterTokenCache = Map<string, {
705
807
  token: string;
706
808
  expiresAt: number;
707
809
  }>;
810
+ /**
811
+ * A connection LINKED through the software's own app (FUT-5613): the store's
812
+ * access token comes from its refresh token, not from a client-credentials
813
+ * grant. `key` is where the token sits in {@link AdapterTokenCache} (delete it
814
+ * to forget a token the marketplace refused); `accessToken` answers the cached
815
+ * one or refreshes, once per connection however many calls ask at once.
816
+ */
817
+ interface AdapterGrant {
818
+ key: string;
819
+ accessToken(): Promise<{
820
+ token: string;
821
+ } | OutboundResult>;
822
+ }
708
823
  /** What one outbound call is handed. */
709
824
  interface AdapterCallContext {
710
825
  http: MarketplaceHttp;
826
+ /** The store's own credentials, or, for a linked connection, the software's app. */
711
827
  credentials: MarketplaceCredentials;
712
828
  environment: "SANDBOX" | "PRODUCTION";
713
829
  /** Written to no row, log or audit entry: memory only, per process. */
714
830
  tokens: AdapterTokenCache;
715
831
  now: Date;
832
+ /** Present for a linked connection: the token comes from here, never from a client-credentials grant. */
833
+ grant?: AdapterGrant;
716
834
  }
717
835
  /** One outbound call's answer, in the three shapes the engine acts on. */
718
836
  type OutboundResult =
@@ -818,6 +936,11 @@ interface MarketplaceAdapter {
818
936
  * API, and the host says so.
819
937
  */
820
938
  readonly availability?: MarketplaceAvailability;
939
+ /**
940
+ * OPTIONAL. Linking a store through the software's own app on this
941
+ * marketplace (FUT-5613). Absent: a store connects with its own credentials only.
942
+ */
943
+ readonly linking?: MarketplaceLinking;
821
944
  /** Where "open it on the marketplace" goes: the order when `perOrderAppLink`, else the portal. Always https. */
822
945
  appLink(order: Pick<OutboundOrderRef, "externalOrderId" | "externalDisplayId">): string;
823
946
  }
@@ -837,4 +960,4 @@ declare function tokenGrantResultOf(response: MarketplaceHttpResponse): Outbound
837
960
  /** A call that never got an answer is a retry, with the reason a log can read. */
838
961
  declare function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult>;
839
962
 
840
- export { type NormalizedOrderLine as $, type AdapterCallContext as A, type CatalogueSnapshotCategory as B, type CatalogueMenuEntry as C, type CatalogueSnapshotItem as D, type CatalogueSnapshotOption as E, type CatalogueSnapshotOptionGroup as F, type CatalogueStoredImage as G, type CatalogueWarningCode as H, type FetchOrderResult as I, type MarketplaceCapabilities as J, type MarketplaceCatalogue as K, type MarketplaceCredentials as L, type MarketplaceAvailability as M, type NormalizedEvent as N, type OutboundResult as O, type PullCatalogue as P, type MarketplaceDeliveredBy as Q, type MarketplaceDiscountSponsor as R, type StorePauseRequest as S, type MarketplaceHttp as T, type MarketplaceHttpRequest as U, type MarketplaceHttpResponse as V, type MarketplaceLifecycle as W, type MarketplaceOrderType as X, type NormalizedAddress as Y, type NormalizedBuyer as Z, type NormalizedOrderDiscount as _, type NormalizedMarketplaceOrder as a, type OutboundOrderRef as a0, PROVIDER_ID_PATTERN as a1, type StatusFacts as a2, type StatusStep as a3, answered as a4, centsFromMajor as a5, outboundResultOf as a6, tokenGrantResultOf as a7, type CatalogueMenuOptions as b, type MarketplaceAdapter as c, type PushCatalogue as d, type CatalogueItemOut as e, type CatalogueReader as f, type StorePauseResult as g, type StorePauseRef as h, type MarketplaceProvider as i, type CancellationReason as j, type AdapterTokenCache as k, type CancellationOutcome as l, type CancellationRequestInput as m, type CatalogueCallContext as n, type CatalogueFailure as o, type CatalogueImage as p, type CatalogueItem as q, type CatalogueItemRef as r, type CataloguePublishResult as s, type CatalogueReadContext as t, type CatalogueReadNotice as u, type CatalogueReadRefusalCode as v, type CatalogueReadResult as w, type CatalogueReadWarning as x, type CatalogueReadWarningCode as y, type CatalogueSnapshot as z };
963
+ export { type MarketplaceHttp as $, type AdapterCallContext as A, type CatalogueReadWarningCode as B, type CatalogueMenuEntry as C, type CatalogueSnapshot as D, type CatalogueSnapshotCategory as E, type CatalogueSnapshotItem as F, type CatalogueSnapshotOption as G, type CatalogueSnapshotOptionGroup as H, type CatalogueStoredImage as I, type CatalogueWarningCode as J, type FetchOrderResult as K, type LinkCallContext as L, type MarketplaceAvailability as M, type NormalizedEvent as N, type OutboundResult as O, type PullCatalogue as P, type LinkCode as Q, type LinkGrant as R, type StorePauseRequest as S, type LinkResult as T, type LinkedMerchant as U, type MarketplaceAppCredentialsPort as V, type MarketplaceCapabilities as W, type MarketplaceCatalogue as X, type MarketplaceCredentials as Y, type MarketplaceDeliveredBy as Z, type MarketplaceDiscountSponsor as _, type NormalizedMarketplaceOrder as a, type MarketplaceHttpRequest as a0, type MarketplaceHttpResponse as a1, type MarketplaceLifecycle as a2, type MarketplaceLinkAttemptDelegate as a3, type MarketplaceOrderType as a4, type NormalizedAddress as a5, type NormalizedBuyer as a6, type NormalizedOrderDiscount as a7, type NormalizedOrderLine as a8, type OutboundOrderRef as a9, PROVIDER_ID_PATTERN as aa, type StatusFacts as ab, type StatusStep as ac, answered as ad, centsFromMajor as ae, outboundResultOf as af, tokenGrantResultOf as ag, type CatalogueMenuOptions as b, type MarketplaceAdapter as c, type PushCatalogue as d, type CatalogueItemOut as e, type CatalogueReader as f, type MarketplaceLinking as g, type StorePauseResult as h, type StorePauseRef as i, type MarketplaceProvider as j, type CancellationReason as k, type AdapterGrant as l, type AdapterTokenCache as m, type CancellationOutcome as n, type CancellationRequestInput as o, type CatalogueCallContext as p, type CatalogueFailure as q, type CatalogueImage as r, type CatalogueItem as s, type CatalogueItemRef as t, type CataloguePublishResult as u, type CatalogueReadContext as v, type CatalogueReadNotice as w, type CatalogueReadRefusalCode as x, type CatalogueReadResult as y, type CatalogueReadWarning as z };
@@ -14,7 +14,7 @@ import {
14
14
  answered,
15
15
  outboundResultOf,
16
16
  tokenGrantResultOf
17
- } from "./chunk-HEXLCTOG.js";
17
+ } from "./chunk-TVZU4HNT.js";
18
18
  import {
19
19
  __name
20
20
  } from "./chunk-7QVYU63E.js";
@@ -475,4 +475,4 @@ export {
475
475
  normalizeOpenDeliveryEventAs,
476
476
  normalizeOpenDeliveryOrderAs
477
477
  };
478
- //# sourceMappingURL=chunk-PYHNM47K.js.map
478
+ //# sourceMappingURL=chunk-DCWOQ5PN.js.map
@@ -2,18 +2,23 @@ import {
2
2
  MARKETPLACE_DECIDE,
3
3
  MARKETPLACE_MANAGE,
4
4
  decideMarketplaceOrdersBody,
5
+ finishLinkBody,
6
+ linkMerchantsQuery,
7
+ linkStateQuery,
5
8
  listMarketplaceAcceptancesQuery,
6
9
  listMarketplaceIntegrationsQuery,
7
10
  listMarketplaceMenuLinksQuery,
11
+ selectLinkMerchantBody,
12
+ startLinkBody,
8
13
  upsertMarketplaceIntegrationsBody,
9
14
  upsertMarketplaceMenuLinksBody
10
- } from "./chunk-ZO4S3LF4.js";
15
+ } from "./chunk-SGOTN5PX.js";
11
16
  import {
12
17
  AvailabilityRetryError,
13
18
  CatalogueRetryError,
14
19
  FetchOrderRetryError,
15
20
  OutboundRetryError
16
- } from "./chunk-2BA2EHNF.js";
21
+ } from "./chunk-YWMEIMO3.js";
17
22
  import {
18
23
  __name
19
24
  } from "./chunk-7QVYU63E.js";
@@ -43,6 +48,121 @@ function iso(value) {
43
48
  }
44
49
  __name(iso, "iso");
45
50
 
51
+ // src/server/link-routes.ts
52
+ var BASE = "/admin/:tenantSlug/marketplace/link";
53
+ var STATUS = {
54
+ UNAVAILABLE: 409,
55
+ NO_LINK_IN_PROGRESS: 409,
56
+ LINK_EXPIRED: 409,
57
+ CODE_REFUSED: 422,
58
+ MARKETPLACE_REFUSED: 502,
59
+ NOT_LINKED: 409,
60
+ UNKNOWN_MERCHANT: 422,
61
+ MERCHANT_TAKEN: 409
62
+ };
63
+ function failed(config, failure) {
64
+ const words = config.copy.link;
65
+ if (failure.kind === "retry") {
66
+ return refuse(503, words?.tryAgain ?? "MARKETPLACE_UNREACHABLE", { code: "MARKETPLACE_UNREACHABLE" });
67
+ }
68
+ return refuse(STATUS[failure.code], words?.problems[failure.code] ?? failure.code, {
69
+ code: failure.code,
70
+ ...failure.message === null ? {} : { marketplaceStatus: failure.status, marketplaceMessage: failure.message }
71
+ });
72
+ }
73
+ __name(failed, "failed");
74
+ var pendingOut = /* @__PURE__ */ __name((pending) => pending ? { ...pending, expiresAt: pending.expiresAt.toISOString() } : null, "pendingOut");
75
+ function connectionOut(row) {
76
+ return { ...row, lastEventAt: iso(row.lastEventAt), lastVerifiedAt: iso(row.lastVerifiedAt), archivedAt: iso(row.archivedAt) };
77
+ }
78
+ __name(connectionOut, "connectionOut");
79
+ function unknown(config, id) {
80
+ return config.engine.knows(id) ? null : refuse(422, config.copy.problems.UNKNOWN_PROVIDER, { code: "UNKNOWN_PROVIDER" });
81
+ }
82
+ __name(unknown, "unknown");
83
+ function readRoutes(config) {
84
+ const { engine, copy } = config;
85
+ return [
86
+ {
87
+ method: "GET",
88
+ path: BASE,
89
+ permission: MARKETPLACE_MANAGE,
90
+ handle: /* @__PURE__ */ __name(async ({ actor, query }) => {
91
+ const parsed = parse(linkStateQuery, query, copy);
92
+ if (!parsed.ok) return parsed.response;
93
+ const refusal = unknown(config, parsed.value.provider);
94
+ if (refusal) return refusal;
95
+ const state = await engine.linkState({ clientId: actor.clientId, ...parsed.value });
96
+ return ok({ available: state.available, pending: pendingOut(state.pending) });
97
+ }, "handle")
98
+ },
99
+ {
100
+ method: "GET",
101
+ path: `${BASE}/merchants`,
102
+ permission: MARKETPLACE_MANAGE,
103
+ handle: /* @__PURE__ */ __name(async ({ actor, query }) => {
104
+ const parsed = parse(linkMerchantsQuery, query, copy);
105
+ if (!parsed.ok) return parsed.response;
106
+ const refusal = unknown(config, parsed.value.provider);
107
+ if (refusal) return refusal;
108
+ const result = await engine.linkedMerchants({ clientId: actor.clientId, provider: parsed.value.provider });
109
+ return result.kind === "listed" ? ok(result.merchants) : failed(config, result);
110
+ }, "handle")
111
+ }
112
+ ];
113
+ }
114
+ __name(readRoutes, "readRoutes");
115
+ function writeRoutes(config) {
116
+ const { engine, copy } = config;
117
+ return [
118
+ {
119
+ method: "POST",
120
+ path: `${BASE}/start`,
121
+ permission: MARKETPLACE_MANAGE,
122
+ handle: /* @__PURE__ */ __name(async ({ actor, body }) => {
123
+ const parsed = parse(startLinkBody, body, copy);
124
+ if (!parsed.ok) return parsed.response;
125
+ const refusal = unknown(config, parsed.value.provider);
126
+ if (refusal) return refusal;
127
+ const result = await engine.startLink({ clientId: actor.clientId, ...parsed.value });
128
+ return result.kind === "started" ? ok(pendingOut(result.pending)) : failed(config, result);
129
+ }, "handle")
130
+ },
131
+ {
132
+ method: "POST",
133
+ path: `${BASE}/finish`,
134
+ permission: MARKETPLACE_MANAGE,
135
+ handle: /* @__PURE__ */ __name(async ({ actor, body }) => {
136
+ const parsed = parse(finishLinkBody, body, copy);
137
+ if (!parsed.ok) return parsed.response;
138
+ const refusal = unknown(config, parsed.value.provider);
139
+ if (refusal) return refusal;
140
+ const result = await engine.finishLink({ clientId: actor.clientId, actorId: actor.userId ?? null, ...parsed.value });
141
+ if (result.kind !== "linked") return failed(config, result);
142
+ return ok({ integration: connectionOut(result.integration), merchants: result.merchants });
143
+ }, "handle")
144
+ },
145
+ {
146
+ method: "PUT",
147
+ path: `${BASE}/merchant`,
148
+ permission: MARKETPLACE_MANAGE,
149
+ handle: /* @__PURE__ */ __name(async ({ actor, body }) => {
150
+ const parsed = parse(selectLinkMerchantBody, body, copy);
151
+ if (!parsed.ok) return parsed.response;
152
+ const refusal = unknown(config, parsed.value.provider);
153
+ if (refusal) return refusal;
154
+ const result = await engine.selectLinkedMerchant({ clientId: actor.clientId, ...parsed.value });
155
+ return result.kind === "selected" ? ok({ integration: connectionOut(result.integration) }) : failed(config, result);
156
+ }, "handle")
157
+ }
158
+ ];
159
+ }
160
+ __name(writeRoutes, "writeRoutes");
161
+ function linkRoutes(config) {
162
+ return [...readRoutes(config), ...writeRoutes(config)];
163
+ }
164
+ __name(linkRoutes, "linkRoutes");
165
+
46
166
  // src/server/webhook.ts
47
167
  var UNAUTHORIZED = { status: 401, body: { error: "unauthorized" } };
48
168
  async function connectionOf(config, tenantSlug, provider) {
@@ -86,6 +206,10 @@ __name(admit, "admit");
86
206
  async function handleWebhook(config, request) {
87
207
  const admitted = await admit(config, request);
88
208
  if ("status" in admitted) return admitted;
209
+ return deliverAdmitted(config, admitted);
210
+ }
211
+ __name(handleWebhook, "handleWebhook");
212
+ async function deliverAdmitted(config, admitted) {
89
213
  const { clientId, provider, payload, target } = admitted;
90
214
  const { engine } = config;
91
215
  const event = engine.normalize(provider, payload);
@@ -106,7 +230,59 @@ async function handleWebhook(config, request) {
106
230
  }
107
231
  return { status: 200, body: { received: true, outcome: outcome.kind } };
108
232
  }
109
- __name(handleWebhook, "handleWebhook");
233
+ __name(deliverAdmitted, "deliverAdmitted");
234
+ async function admitApp(config, request) {
235
+ const { provider = "" } = request.params;
236
+ if (!config.engine.knows(provider)) return { status: 404, body: { error: "unknown_provider" } };
237
+ const raw = request.request;
238
+ if (!raw) return { status: 400, body: { error: "raw_request_required" } };
239
+ const rawBody = await raw.text();
240
+ const payload = parsedJson(rawBody);
241
+ if (payload === void 0) return { status: 400, body: { error: "invalid_json" } };
242
+ const found = await appConnection(config, provider, payload);
243
+ if ("status" in found) return found;
244
+ const signature = config.engine.readSignature(provider, (name) => raw.headers.get(name));
245
+ const secret = found.target.webhookSecret;
246
+ if (!secret || !config.engine.verifySignature(provider, rawBody, signature, secret)) {
247
+ config.logger.warn(`marketplace.webhook: app ${provider} delivery for ${found.clientId} refused`);
248
+ return UNAUTHORIZED;
249
+ }
250
+ return { ...found, provider, payload };
251
+ }
252
+ __name(admitApp, "admitApp");
253
+ function parsedJson(rawBody) {
254
+ try {
255
+ return JSON.parse(rawBody);
256
+ } catch {
257
+ return void 0;
258
+ }
259
+ }
260
+ __name(parsedJson, "parsedJson");
261
+ async function appConnection(config, provider, payload) {
262
+ const merchantId = config.engine.normalize(provider, payload)?.externalMerchantId ?? null;
263
+ const clientId = merchantId === null ? null : await config.engine.tenantFor(provider, merchantId);
264
+ if (!clientId) return UNAUTHORIZED;
265
+ try {
266
+ const target = await config.engine.target(clientId, provider);
267
+ return target ? { clientId, target } : UNAUTHORIZED;
268
+ } catch (error) {
269
+ config.logger.error(`marketplace.webhook: app ${provider} key of ${clientId} unavailable: ${String(error)}`);
270
+ return UNAUTHORIZED;
271
+ }
272
+ }
273
+ __name(appConnection, "appConnection");
274
+ function appWebhookRoute(config) {
275
+ return {
276
+ method: "POST",
277
+ path: "/webhooks/marketplace/:provider",
278
+ kind: "webhook",
279
+ handle: /* @__PURE__ */ __name(async (request) => {
280
+ const admitted = await admitApp(config, request);
281
+ return "status" in admitted ? admitted : deliverAdmitted(config, admitted);
282
+ }, "handle")
283
+ };
284
+ }
285
+ __name(appWebhookRoute, "appWebhookRoute");
110
286
  function webhookRoute(config) {
111
287
  return {
112
288
  method: "POST",
@@ -118,7 +294,7 @@ function webhookRoute(config) {
118
294
  __name(webhookRoute, "webhookRoute");
119
295
 
120
296
  // src/server/routes.ts
121
- var BASE = "/admin/:tenantSlug/marketplace";
297
+ var BASE2 = "/admin/:tenantSlug/marketplace";
122
298
  var ORDER_NOT_PENDING_CODE = "MARKETPLACE_ORDER_NOT_PENDING";
123
299
  var NOT_PENDING = /* @__PURE__ */ new Set(["NOT_FOUND", "ALREADY_DECIDED", "EXPIRED", "CONFLICT"]);
124
300
  function integrationOut(config, row) {
@@ -142,7 +318,7 @@ function problemsOut(copy, problems) {
142
318
  const host = "host" in problem ? problem.host : void 0;
143
319
  return {
144
320
  ...problem,
145
- message: host?.message ?? copy.problems[problem.code],
321
+ message: host?.message ?? (problem.code === "MERCHANT_TAKEN" ? copy.link?.problems.MERCHANT_TAKEN ?? problem.code : copy.problems[problem.code]),
146
322
  ...host ? { hostCode: host.code, details: host.details } : {}
147
323
  };
148
324
  });
@@ -167,7 +343,7 @@ function integrationRoutes(config) {
167
343
  return [
168
344
  {
169
345
  method: "GET",
170
- path: BASE,
346
+ path: BASE2,
171
347
  permission: MARKETPLACE_MANAGE,
172
348
  handle: /* @__PURE__ */ __name(async ({ actor, query }) => {
173
349
  const parsed = parse(listMarketplaceIntegrationsQuery, query, copy);
@@ -181,7 +357,7 @@ function integrationRoutes(config) {
181
357
  },
182
358
  {
183
359
  method: "PUT",
184
- path: BASE,
360
+ path: BASE2,
185
361
  permission: MARKETPLACE_MANAGE,
186
362
  handle: /* @__PURE__ */ __name(async ({ actor, body }) => {
187
363
  const parsed = parse(upsertMarketplaceIntegrationsBody, body, copy);
@@ -206,7 +382,7 @@ function menuLinkRoutes(config) {
206
382
  return [
207
383
  {
208
384
  method: "GET",
209
- path: `${BASE}/menu-links`,
385
+ path: `${BASE2}/menu-links`,
210
386
  permission: MARKETPLACE_MANAGE,
211
387
  handle: /* @__PURE__ */ __name(async ({ actor, query }) => {
212
388
  const parsed = parse(listMarketplaceMenuLinksQuery, query, copy);
@@ -222,7 +398,7 @@ function menuLinkRoutes(config) {
222
398
  },
223
399
  {
224
400
  method: "PUT",
225
- path: `${BASE}/menu-links`,
401
+ path: `${BASE2}/menu-links`,
226
402
  permission: MARKETPLACE_MANAGE,
227
403
  handle: /* @__PURE__ */ __name(async ({ actor, body }) => {
228
404
  const parsed = parse(upsertMarketplaceMenuLinksBody, body, copy);
@@ -244,7 +420,7 @@ function acceptanceRoutes(config) {
244
420
  return [
245
421
  {
246
422
  method: "GET",
247
- path: `${BASE}/acceptances`,
423
+ path: `${BASE2}/acceptances`,
248
424
  permission: MARKETPLACE_DECIDE,
249
425
  handle: /* @__PURE__ */ __name(async ({ actor, query }) => {
250
426
  const parsed = parse(listMarketplaceAcceptancesQuery, query, copy);
@@ -261,7 +437,7 @@ function acceptanceRoutes(config) {
261
437
  },
262
438
  {
263
439
  method: "POST",
264
- path: `${BASE}/acceptances`,
440
+ path: `${BASE2}/acceptances`,
265
441
  permission: MARKETPLACE_DECIDE,
266
442
  handle: /* @__PURE__ */ __name(async ({ actor, body }) => {
267
443
  const parsed = parse(decideMarketplaceOrdersBody, body, copy);
@@ -281,7 +457,9 @@ __name(acceptanceRoutes, "acceptanceRoutes");
281
457
  function marketplaceRoutes(config) {
282
458
  return [
283
459
  webhookRoute(config),
460
+ appWebhookRoute(config),
284
461
  ...integrationRoutes(config),
462
+ ...linkRoutes(config),
285
463
  ...menuLinkRoutes(config),
286
464
  ...acceptanceRoutes(config)
287
465
  ];
@@ -473,4 +651,4 @@ export {
473
651
  MARKETPLACE_JOBS,
474
652
  createApiMarketplace
475
653
  };
476
- //# sourceMappingURL=chunk-WVZ2IXFH.js.map
654
+ //# sourceMappingURL=chunk-OS4TSIFU.js.map