@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
@@ -160,6 +160,325 @@ interface PullCatalogue {
160
160
  /** The catalogue capability an adapter states, or leaves out. */
161
161
  type MarketplaceCatalogue = PushCatalogue | PullCatalogue;
162
162
 
163
+ /**
164
+ * The canonical shape every marketplace adapter normalizes INTO.
165
+ *
166
+ * This type is the seam. The engine below it knows no marketplace by name: a
167
+ * marketplace is an adapter registered with the engine (`./adapter`), and the
168
+ * provider id is whatever that adapter says it is. A second marketplace is a
169
+ * second adapter, never a second pipeline, a second acceptance clock or a
170
+ * second idea of what an order is.
171
+ *
172
+ * Deliberately POORER than any marketplace's own payload. Everything a store
173
+ * operates on is here; everything else stays in the inbox row's raw `payload`,
174
+ * which is where a normalization bug is reconstructed from.
175
+ */
176
+ /**
177
+ * A marketplace's id, as its adapter declares it (`"IFOOD"`). Uppercase
178
+ * letters, digits and underscores; the migration's CHECK holds the same shape.
179
+ * A string rather than a closed union, because the set of marketplaces is the
180
+ * set of registered adapters, and a union would make a new one a code change
181
+ * in the engine.
182
+ */
183
+ type MarketplaceProvider = string;
184
+ /** The shape a provider id must have. Shared by the registry and the CHECK. */
185
+ declare const PROVIDER_ID_PATTERN: RegExp;
186
+ /** One line of an incoming order, before it is resolved against the catalog. */
187
+ interface NormalizedOrderLine {
188
+ /** The marketplace's own SKU — the key the SKU map is matched on. */
189
+ externalSku: string;
190
+ /** What the marketplace called it. Snapshotted, and the fallback line text. */
191
+ name: string;
192
+ quantity: number;
193
+ /**
194
+ * Unit price in the smallest currency unit AS THE MARKETPLACE STATES IT. A
195
+ * marketplace's menu carries its own prices, and the buyer's receipt is the
196
+ * marketplace's one: re-pricing from the host's catalog would produce a
197
+ * total nobody was charged.
198
+ */
199
+ unitPriceCents: number;
200
+ /** The buyer's note on this line, when they left one. */
201
+ note: string | null;
202
+ }
203
+ /** The buyer, as much of them as the marketplace discloses. */
204
+ interface NormalizedBuyer {
205
+ /** The marketplace's own stable id for this customer, when it gives one. */
206
+ externalId: string | null;
207
+ name: string | null;
208
+ phone: string | null;
209
+ }
210
+ /** Where a delivery goes, as much of it as the marketplace states. */
211
+ interface NormalizedAddress {
212
+ street: string;
213
+ number: string;
214
+ neighborhood: string;
215
+ complement: string | null;
216
+ /** The sentence that finds the door. */
217
+ reference: string | null;
218
+ postalCode: string | null;
219
+ city: string | null;
220
+ state: string | null;
221
+ }
222
+ /** How the order reaches the buyer: brought to the door, or collected. */
223
+ type MarketplaceOrderType = "DELIVERY" | "TAKEOUT";
224
+ /** WHO carries a delivery: the merchant's own courier, or the marketplace's fleet. */
225
+ type MarketplaceDeliveredBy = "MERCHANT" | "MARKETPLACE";
226
+ /** WHO pays for a discount: the store, the marketplace's own campaign, or someone else (a card issuer, a voucher). */
227
+ type MarketplaceDiscountSponsor = "MERCHANT" | "MARKETPLACE" | "OTHER";
228
+ /** One discount on an order, as the part one sponsor pays. */
229
+ interface NormalizedOrderDiscount {
230
+ /** The discount's value in the smallest currency unit. */
231
+ cents: number;
232
+ sponsor: MarketplaceDiscountSponsor;
233
+ /** What the marketplace called the campaign, when it says. */
234
+ name?: string;
235
+ }
236
+ /** An incoming marketplace order, normalized. */
237
+ interface NormalizedMarketplaceOrder {
238
+ provider: MarketplaceProvider;
239
+ /** The marketplace's order id — THE idempotency key for the whole pipeline. */
240
+ externalOrderId: string;
241
+ /** The short code the courier and the buyer say out loud. */
242
+ externalDisplayId: string | null;
243
+ buyer: NormalizedBuyer;
244
+ lines: NormalizedOrderLine[];
245
+ /**
246
+ * What the buyer paid, gross. NOT derived from the lines when the
247
+ * marketplace states it: its total carries fees, promotions and rounding the
248
+ * line sum does not, and the number that must match the receipt is this one.
249
+ */
250
+ totalCents: number;
251
+ /** The marketplace's cut, when it states one. NULL is "did not say", not 0. */
252
+ commissionCents: number | null;
253
+ /** The marketplace's own promise to the buyer. */
254
+ deliveryDueAt: Date | null;
255
+ /** When the marketplace says the order was placed. */
256
+ placedAt: Date;
257
+ /** Null when the payload does not say. */
258
+ orderType?: MarketplaceOrderType | null;
259
+ /** Null on a take-out and when unstated. */
260
+ deliveredBy?: MarketplaceDeliveredBy | null;
261
+ /** Null on a take-out and when unstated. */
262
+ deliveryAddress?: NormalizedAddress | null;
263
+ /**
264
+ * OPTIONAL. The delivery fee the buyer was charged, in the smallest currency
265
+ * unit. 0 is a free delivery; null or absent is "did not say".
266
+ */
267
+ deliveryFeeCents?: number | null;
268
+ /** OPTIONAL. The items' sum as the marketplace states it, before fees and discounts. Null or absent is "did not say". */
269
+ subtotalCents?: number | null;
270
+ /**
271
+ * OPTIONAL. The discounts on the order, one entry per sponsor's share, so a
272
+ * host can tell what the store gave from what the marketplace paid for.
273
+ * Absent is "did not say"; an empty array is "no discount".
274
+ */
275
+ discounts?: NormalizedOrderDiscount[];
276
+ /**
277
+ * OPTIONAL. The merchant the order names, when its body says (Open
278
+ * Delivery's `merchant.id`). A fetched order naming another merchant than
279
+ * the connection's is refused.
280
+ */
281
+ externalMerchantId?: string | null;
282
+ /**
283
+ * OPTIONAL (FUT-5665). The code the marketplace's courier states at the
284
+ * counter to collect the bag (iFood's `delivery.pickupCode`), for the host
285
+ * to check locally at the hand-over. Null or absent: the marketplace asks
286
+ * none for this order (the check is off for the store, or the store carries
287
+ * the bag itself).
288
+ */
289
+ pickupCode?: string | null;
290
+ }
291
+ /**
292
+ * What an event says about the STORE's own cancellation request: `CONFIRMED`
293
+ * when the marketplace cancelled the order (a pending request is answered),
294
+ * `FAILED` when it refused the request.
295
+ */
296
+ type CancellationOutcome = "CONFIRMED" | "FAILED";
297
+ /**
298
+ * A step of the order's life a marketplace announces about an order it
299
+ * already has (FUT-4653): the courier left (`DISPATCHED`), the marketplace's
300
+ * courier has the bag (`COLLECTED`, FUT-5665: for a fleet bag it is the same
301
+ * hand-over as `DISPATCHED`) or the order is finished (`CONCLUDED`). An event
302
+ * that names one moves nothing by itself; the engine asks the host to move the
303
+ * order forward (`onLifecycle`).
304
+ */
305
+ type MarketplaceLifecycle = "DISPATCHED" | "COLLECTED" | "CONCLUDED";
306
+ /**
307
+ * Where the marketplace's own courier is with a bag (FUT-5665), provider-
308
+ * neutral: named (`ASSIGNED`), on the way to the store (`GOING_TO_ORIGIN`),
309
+ * at the counter (`ARRIVED_AT_ORIGIN`), holding the bag (`COLLECTED`), or
310
+ * bringing it back (`RETURNING_TO_ORIGIN`, then `RETURNED_TO_ORIGIN`).
311
+ */
312
+ type MarketplaceCourierStep = "ASSIGNED" | "GOING_TO_ORIGIN" | "ARRIVED_AT_ORIGIN" | "COLLECTED" | "RETURNING_TO_ORIGIN" | "RETURNED_TO_ORIGIN";
313
+ /** What the courier rides, as a closed set the host has words for. `OTHER`: stated, and none of these. */
314
+ type MarketplaceCourierVehicle = "MOTORCYCLE" | "BICYCLE" | "CAR" | "OTHER";
315
+ /** Who the marketplace sent, as much as it says. */
316
+ interface MarketplaceCourier {
317
+ name: string | null;
318
+ /** An https URL of the courier's photo, or null (any other scheme is dropped). */
319
+ photoUrl: string | null;
320
+ vehicle: MarketplaceCourierVehicle | null;
321
+ }
322
+ /** One courier event, normalized (FUT-5665). */
323
+ interface NormalizedCourierEvent {
324
+ step: MarketplaceCourierStep;
325
+ /** When the marketplace says it happened; null when it does not (the engine then hands the host its clock). */
326
+ at: Date | null;
327
+ /** Who is coming: on `ASSIGNED`, when the marketplace names them; null otherwise. */
328
+ courier: MarketplaceCourier | null;
329
+ /** The bag is coming back (`RETURNING`) or is back (`RETURNED`); null on every other step. */
330
+ returning: "RETURNING" | "RETURNED" | null;
331
+ }
332
+ /** What an adapter makes of one inbound delivery. */
333
+ interface NormalizedEvent {
334
+ provider: MarketplaceProvider;
335
+ /** The delivery's own id — the inbox dedup key, paired with the provider. */
336
+ eventId: string;
337
+ /** The provider's event type verbatim, kept for the inbox row and the log. */
338
+ eventType: string;
339
+ /** The merchant this event names, used to attribute it to a tenant. */
340
+ externalMerchantId: string | null;
341
+ externalOrderId: string | null;
342
+ /**
343
+ * The order this event carries, or null when the event is one the engine
344
+ * understands and does not ingest. A null here is an IGNORED inbox row (or a
345
+ * cancellation, below), never a failure.
346
+ */
347
+ order: NormalizedMarketplaceOrder | null;
348
+ /** The marketplace has CANCELLED the order. */
349
+ cancelled: boolean;
350
+ /**
351
+ * The answer to the store's own cancellation request, when this event is
352
+ * one. A `cancelled: true` event reads as `CONFIRMED` when this is absent.
353
+ */
354
+ cancellationOutcome?: CancellationOutcome | null;
355
+ /**
356
+ * OPTIONAL. This event announces an order whose body the marketplace serves
357
+ * separately (Open Delivery's `CREATED` carries only the order's id): the
358
+ * engine fetches it through the adapter's `fetchOrder`, in the
359
+ * `marketplace.fetch-order` job, never inside the request that delivered
360
+ * the event. Ignored when `order` is present.
361
+ */
362
+ orderToFetch?: boolean;
363
+ /**
364
+ * OPTIONAL. The lifecycle step this event announces about an order the
365
+ * engine already has. Absent or null: the event names none. An event that
366
+ * names one carries no order body.
367
+ */
368
+ lifecycle?: MarketplaceLifecycle | null;
369
+ /**
370
+ * OPTIONAL (FUT-5665). Where the marketplace's courier is, when this event
371
+ * says. A `COLLECTED` names the lifecycle too. Absent or null: the event
372
+ * names no courier step.
373
+ */
374
+ courier?: NormalizedCourierEvent | null;
375
+ }
376
+
377
+ /**
378
+ * The marketplace's own courier (FUT-5665): what an adapter can do about the
379
+ * courier its marketplace sends, and what the host is told. Optional in every
380
+ * type, so a host or an adapter that knows nothing of it compiles unchanged.
381
+ */
382
+ /** Where the marketplace's courier is, as its tracking read says. Every field null when unstated. */
383
+ interface MarketplaceCourierTracking {
384
+ /** When the courier reaches the store: the "chega em" time. */
385
+ pickupEtaAt: Date | null;
386
+ /** When the marketplace expects the bag at the buyer's door. */
387
+ deliveryEtaAt: Date | null;
388
+ latitude: number | null;
389
+ longitude: number | null;
390
+ /** When the marketplace took this reading. */
391
+ trackedAt: Date | null;
392
+ }
393
+ /** What an adapter's pickup-code check answers: the marketplace's verdict, or why there is none. */
394
+ type PickupCodeCallResult = {
395
+ kind: "answered";
396
+ valid: boolean;
397
+ } | Exclude<OutboundResult, {
398
+ kind: "accepted";
399
+ }>;
400
+ /**
401
+ * What an adapter's tracking read answers: the reading; `notYet` (no courier
402
+ * is assigned, so there is nothing to track); or the refusal and retry shapes
403
+ * of an outbound call.
404
+ */
405
+ type CourierTrackingCallResult = {
406
+ kind: "tracking";
407
+ tracking: MarketplaceCourierTracking;
408
+ } | {
409
+ kind: "notYet";
410
+ } | Exclude<OutboundResult, {
411
+ kind: "accepted";
412
+ }>;
413
+ /** The courier calls one marketplace takes. Present on an adapter whose marketplace has them (iFood). */
414
+ interface MarketplaceCourierApi {
415
+ /**
416
+ * Tell the marketplace the code the store checked at the hand-over, and
417
+ * read its verdict. Called only from the `marketplace.outbound` job, action
418
+ * `validatePickupCode`, after the host's own hand-over committed.
419
+ */
420
+ validatePickupCode(ctx: AdapterCallContext, order: OutboundOrderRef, input: {
421
+ code: string;
422
+ }): Promise<PickupCodeCallResult>;
423
+ /** Read where the courier is. Called only by `engine.courierTracking`, which the host runs in a job. */
424
+ tracking(ctx: AdapterCallContext, order: OutboundOrderRef): Promise<CourierTrackingCallResult>;
425
+ }
426
+ /**
427
+ * The marketplace's verdict on a pickup code, as the host is told it:
428
+ * `VALID`, `INVALID` (the hand-over has committed: warn, move nothing) or
429
+ * `UNVERIFIED` (no verdict came: a final refusal, retries that ran out, no
430
+ * connection).
431
+ */
432
+ type PickupCodeValidation = "VALID" | "INVALID" | "UNVERIFIED";
433
+ /** What the engine tells the host with a courier event. */
434
+ interface MarketplaceCourierFacts {
435
+ /** Who carries the delivery, as the acceptance row holds it. */
436
+ deliveredBy: MarketplaceDeliveredBy | null;
437
+ /** When it happened: the event's own instant, or the engine's clock when the event states none. */
438
+ at: Date;
439
+ }
440
+ /**
441
+ * The host's answer to a courier event: `recorded` (it stored the facts),
442
+ * `unchanged` (nothing to store, with the engine's reason), or `unchanged`
443
+ * with the host's own reason, which becomes the inbox row's.
444
+ */
445
+ type MarketplaceCourierAnswer = "recorded" | "unchanged" | {
446
+ kind: "unchanged";
447
+ reason: string;
448
+ };
449
+ /** What `engine.courierTracking` answers. */
450
+ type CourierTrackingResult = CourierTrackingCallResult
451
+ /** Nothing to call: no such marketplace order, a marketplace with no tracking, or a bag the store carries itself. */
452
+ | {
453
+ kind: "unsupported";
454
+ reason: string;
455
+ };
456
+ /** What the host says after its hand-over committed. */
457
+ interface ValidatePickupCodeInput {
458
+ clientId: string;
459
+ /** The host's order id. */
460
+ orderId: string;
461
+ /** The code the store checked (the one the courier stated). */
462
+ code: string;
463
+ /** The hand-over's own instant: it makes the job's key, so a hand-over after an undo is a new job. */
464
+ at: Date;
465
+ }
466
+ /** The engine's courier calls (FUT-5665), part of `MarketplaceEngine`. */
467
+ interface MarketplaceCourierEngine {
468
+ /**
469
+ * The store handed a marketplace courier's bag over after checking the
470
+ * pickup code locally: ONE enqueue of `marketplace.outbound`, action
471
+ * `validatePickupCode`, after the hand-over's commit. Never throws, runs no
472
+ * statement and calls nobody. True when the queue took it.
473
+ */
474
+ validatePickupCode(input: ValidatePickupCodeInput): Promise<boolean>;
475
+ /** Read where the marketplace's courier is: one call to the marketplace, at once. Run it from a job. */
476
+ courierTracking(input: {
477
+ clientId: string;
478
+ orderId: string;
479
+ }): Promise<CourierTrackingResult>;
480
+ }
481
+
163
482
  /**
164
483
  * The catalogue READ half of the adapter port (FUT-951): the menu a store
165
484
  * already keeps on a marketplace, read through the store's own connection, so
@@ -303,6 +622,108 @@ interface CatalogueReader {
303
622
  */
304
623
  declare function centsFromMajor(value: unknown): number | null;
305
624
 
625
+ /**
626
+ * LINKING a store through the software's OWN marketplace app (FUT-5613): the
627
+ * store authorizes the software's app on the marketplace's portal, and never
628
+ * types a client id, a secret, a webhook key or a webhook address.
629
+ *
630
+ * The flow, as an adapter states it (iFood's "distributed app"):
631
+ *
632
+ * 1. `requestCode`: the app asks for a short code the store types (or a link
633
+ * that already carries it) on the marketplace's portal, plus a VERIFIER the
634
+ * engine keeps server-side for that store and never hands the browser.
635
+ * 2. The store authorizes the app on the portal and is shown an
636
+ * AUTHORIZATION CODE, which it pastes back.
637
+ * 3. `exchange`: the code plus the verifier buy an access token and a refresh
638
+ * token, stored sealed on the store's connection.
639
+ * 4. `merchants`: which of the marketplace's stores the grant covers; one is
640
+ * selected at once.
641
+ * 5. `refresh`: a new access token from the refresh token, whenever the
642
+ * cached one is gone. A rotated refresh token is stored back.
643
+ *
644
+ * The app's own credentials are the HOST's configuration, one pair per
645
+ * marketplace and environment ({@link MarketplaceAppCredentialsPort}), never a
646
+ * store's.
647
+ */
648
+ /** What a linking call is handed: the APP's credentials, never a store's. */
649
+ interface LinkCallContext {
650
+ http: MarketplaceHttp;
651
+ credentials: MarketplaceCredentials;
652
+ environment: "SANDBOX" | "PRODUCTION";
653
+ now: Date;
654
+ }
655
+ /** The code a store types on the marketplace's portal, and the verifier kept for it. */
656
+ interface LinkCode {
657
+ /** Shown to the person: they type it on the portal. */
658
+ userCode: string;
659
+ /** The portal page the code is typed on. */
660
+ verificationUrl: string;
661
+ /** The same page with the code already in it: the link the screen opens. */
662
+ verificationUrlComplete: string;
663
+ /** How long the code lives, in seconds. */
664
+ expiresInSeconds: number;
665
+ /** Kept server-side for this store until the exchange. NEVER sent to a browser. */
666
+ verifier: string;
667
+ }
668
+ /** What an exchange or a refresh buys. */
669
+ interface LinkGrant {
670
+ accessToken: string;
671
+ /** How long the access token lives, in seconds. */
672
+ expiresInSeconds: number;
673
+ /**
674
+ * The refresh token. An exchange always answers one; a refresh answers one
675
+ * when the marketplace rotates it, and null when the old one stays valid.
676
+ */
677
+ refreshToken: string | null;
678
+ }
679
+ /** One marketplace store the grant covers. */
680
+ interface LinkedMerchant {
681
+ id: string;
682
+ name: string | null;
683
+ corporateName: string | null;
684
+ }
685
+ /**
686
+ * A linking call's answer: the value, or why there is none. `refused` is
687
+ * final (the marketplace judged the request: a wrong or used code, a refresh
688
+ * token it no longer honours); `retry` is the network, a 5xx, a rate limit.
689
+ */
690
+ type LinkResult<T> = {
691
+ kind: "ok";
692
+ value: T;
693
+ } | Exclude<OutboundResult, {
694
+ kind: "accepted";
695
+ }>;
696
+ /** The adapter's half: the marketplace's wire format for each step, and nothing else. */
697
+ interface MarketplaceLinking {
698
+ requestCode(ctx: LinkCallContext): Promise<LinkResult<LinkCode>>;
699
+ exchange(ctx: LinkCallContext, input: {
700
+ authorizationCode: string;
701
+ verifier: string;
702
+ }): Promise<LinkResult<LinkGrant>>;
703
+ refresh(ctx: LinkCallContext, input: {
704
+ refreshToken: string;
705
+ }): Promise<LinkResult<LinkGrant>>;
706
+ merchants(ctx: LinkCallContext, input: {
707
+ accessToken: string;
708
+ }): Promise<LinkResult<LinkedMerchant[]>>;
709
+ }
710
+ /**
711
+ * The host's configuration of its OWN app on a marketplace: client id, client
712
+ * secret, and the key the marketplace signs the app's webhook deliveries with.
713
+ * Null (or the port not bound) means the software has no app there, and the
714
+ * linking flow reports itself unavailable; a store's own credentials keep
715
+ * working unchanged either way.
716
+ */
717
+ type MarketplaceAppCredentialsPort = (provider: string, environment: "SANDBOX" | "PRODUCTION") => MarketplaceCredentials | null | Promise<MarketplaceCredentials | null>;
718
+ /** The link-attempt delegate the engine reads and writes (the `MarketplaceLinkAttempt` model). */
719
+ interface MarketplaceLinkAttemptDelegate {
720
+ findUnique(args: unknown): Promise<unknown>;
721
+ upsert(args: unknown): Promise<unknown>;
722
+ deleteMany(args: unknown): Promise<{
723
+ count: number;
724
+ }>;
725
+ }
726
+
306
727
  /**
307
728
  * The adapter port's OPTIONAL availability capability: closing a store on a
308
729
  * marketplace for a while, and opening it again (FUT-4851).
@@ -417,178 +838,6 @@ interface MarketplaceAvailability {
417
838
  resume(ctx: AdapterCallContext, ref: StorePauseRef): Promise<OutboundResult>;
418
839
  }
419
840
 
420
- /**
421
- * The canonical shape every marketplace adapter normalizes INTO.
422
- *
423
- * This type is the seam. The engine below it knows no marketplace by name: a
424
- * marketplace is an adapter registered with the engine (`./adapter`), and the
425
- * provider id is whatever that adapter says it is. A second marketplace is a
426
- * second adapter, never a second pipeline, a second acceptance clock or a
427
- * second idea of what an order is.
428
- *
429
- * Deliberately POORER than any marketplace's own payload. Everything a store
430
- * operates on is here; everything else stays in the inbox row's raw `payload`,
431
- * which is where a normalization bug is reconstructed from.
432
- */
433
- /**
434
- * A marketplace's id, as its adapter declares it (`"IFOOD"`). Uppercase
435
- * letters, digits and underscores; the migration's CHECK holds the same shape.
436
- * A string rather than a closed union, because the set of marketplaces is the
437
- * set of registered adapters, and a union would make a new one a code change
438
- * in the engine.
439
- */
440
- type MarketplaceProvider = string;
441
- /** The shape a provider id must have. Shared by the registry and the CHECK. */
442
- declare const PROVIDER_ID_PATTERN: RegExp;
443
- /** One line of an incoming order, before it is resolved against the catalog. */
444
- interface NormalizedOrderLine {
445
- /** The marketplace's own SKU — the key the SKU map is matched on. */
446
- externalSku: string;
447
- /** What the marketplace called it. Snapshotted, and the fallback line text. */
448
- name: string;
449
- quantity: number;
450
- /**
451
- * Unit price in the smallest currency unit AS THE MARKETPLACE STATES IT. A
452
- * marketplace's menu carries its own prices, and the buyer's receipt is the
453
- * marketplace's one: re-pricing from the host's catalog would produce a
454
- * total nobody was charged.
455
- */
456
- unitPriceCents: number;
457
- /** The buyer's note on this line, when they left one. */
458
- note: string | null;
459
- }
460
- /** The buyer, as much of them as the marketplace discloses. */
461
- interface NormalizedBuyer {
462
- /** The marketplace's own stable id for this customer, when it gives one. */
463
- externalId: string | null;
464
- name: string | null;
465
- phone: string | null;
466
- }
467
- /** Where a delivery goes, as much of it as the marketplace states. */
468
- interface NormalizedAddress {
469
- street: string;
470
- number: string;
471
- neighborhood: string;
472
- complement: string | null;
473
- /** The sentence that finds the door. */
474
- reference: string | null;
475
- postalCode: string | null;
476
- city: string | null;
477
- state: string | null;
478
- }
479
- /** How the order reaches the buyer: brought to the door, or collected. */
480
- type MarketplaceOrderType = "DELIVERY" | "TAKEOUT";
481
- /** WHO carries a delivery: the merchant's own courier, or the marketplace's fleet. */
482
- type MarketplaceDeliveredBy = "MERCHANT" | "MARKETPLACE";
483
- /** WHO pays for a discount: the store, the marketplace's own campaign, or someone else (a card issuer, a voucher). */
484
- type MarketplaceDiscountSponsor = "MERCHANT" | "MARKETPLACE" | "OTHER";
485
- /** One discount on an order, as the part one sponsor pays. */
486
- interface NormalizedOrderDiscount {
487
- /** The discount's value in the smallest currency unit. */
488
- cents: number;
489
- sponsor: MarketplaceDiscountSponsor;
490
- /** What the marketplace called the campaign, when it says. */
491
- name?: string;
492
- }
493
- /** An incoming marketplace order, normalized. */
494
- interface NormalizedMarketplaceOrder {
495
- provider: MarketplaceProvider;
496
- /** The marketplace's order id — THE idempotency key for the whole pipeline. */
497
- externalOrderId: string;
498
- /** The short code the courier and the buyer say out loud. */
499
- externalDisplayId: string | null;
500
- buyer: NormalizedBuyer;
501
- lines: NormalizedOrderLine[];
502
- /**
503
- * What the buyer paid, gross. NOT derived from the lines when the
504
- * marketplace states it: its total carries fees, promotions and rounding the
505
- * line sum does not, and the number that must match the receipt is this one.
506
- */
507
- totalCents: number;
508
- /** The marketplace's cut, when it states one. NULL is "did not say", not 0. */
509
- commissionCents: number | null;
510
- /** The marketplace's own promise to the buyer. */
511
- deliveryDueAt: Date | null;
512
- /** When the marketplace says the order was placed. */
513
- placedAt: Date;
514
- /** Null when the payload does not say. */
515
- orderType?: MarketplaceOrderType | null;
516
- /** Null on a take-out and when unstated. */
517
- deliveredBy?: MarketplaceDeliveredBy | null;
518
- /** Null on a take-out and when unstated. */
519
- deliveryAddress?: NormalizedAddress | null;
520
- /**
521
- * OPTIONAL. The delivery fee the buyer was charged, in the smallest currency
522
- * unit. 0 is a free delivery; null or absent is "did not say".
523
- */
524
- deliveryFeeCents?: number | null;
525
- /** OPTIONAL. The items' sum as the marketplace states it, before fees and discounts. Null or absent is "did not say". */
526
- subtotalCents?: number | null;
527
- /**
528
- * OPTIONAL. The discounts on the order, one entry per sponsor's share, so a
529
- * host can tell what the store gave from what the marketplace paid for.
530
- * Absent is "did not say"; an empty array is "no discount".
531
- */
532
- discounts?: NormalizedOrderDiscount[];
533
- /**
534
- * OPTIONAL. The merchant the order names, when its body says (Open
535
- * Delivery's `merchant.id`). A fetched order naming another merchant than
536
- * the connection's is refused.
537
- */
538
- externalMerchantId?: string | null;
539
- }
540
- /**
541
- * What an event says about the STORE's own cancellation request: `CONFIRMED`
542
- * when the marketplace cancelled the order (a pending request is answered),
543
- * `FAILED` when it refused the request.
544
- */
545
- type CancellationOutcome = "CONFIRMED" | "FAILED";
546
- /**
547
- * A step of the order's life a marketplace announces about an order it
548
- * already has (FUT-4653): the courier left (`DISPATCHED`) or the order is
549
- * finished (`CONCLUDED`). An event that names one moves nothing by itself; the
550
- * engine asks the host to move the order forward (`onLifecycle`).
551
- */
552
- type MarketplaceLifecycle = "DISPATCHED" | "CONCLUDED";
553
- /** What an adapter makes of one inbound delivery. */
554
- interface NormalizedEvent {
555
- provider: MarketplaceProvider;
556
- /** The delivery's own id — the inbox dedup key, paired with the provider. */
557
- eventId: string;
558
- /** The provider's event type verbatim, kept for the inbox row and the log. */
559
- eventType: string;
560
- /** The merchant this event names, used to attribute it to a tenant. */
561
- externalMerchantId: string | null;
562
- externalOrderId: string | null;
563
- /**
564
- * The order this event carries, or null when the event is one the engine
565
- * understands and does not ingest. A null here is an IGNORED inbox row (or a
566
- * cancellation, below), never a failure.
567
- */
568
- order: NormalizedMarketplaceOrder | null;
569
- /** The marketplace has CANCELLED the order. */
570
- cancelled: boolean;
571
- /**
572
- * The answer to the store's own cancellation request, when this event is
573
- * one. A `cancelled: true` event reads as `CONFIRMED` when this is absent.
574
- */
575
- cancellationOutcome?: CancellationOutcome | null;
576
- /**
577
- * OPTIONAL. This event announces an order whose body the marketplace serves
578
- * separately (Open Delivery's `CREATED` carries only the order's id): the
579
- * engine fetches it through the adapter's `fetchOrder`, in the
580
- * `marketplace.fetch-order` job, never inside the request that delivered
581
- * the event. Ignored when `order` is present.
582
- */
583
- orderToFetch?: boolean;
584
- /**
585
- * OPTIONAL. The lifecycle step this event announces about an order the
586
- * engine already has. Absent or null: the event names none. An event that
587
- * names one carries no order body.
588
- */
589
- lifecycle?: MarketplaceLifecycle | null;
590
- }
591
-
592
841
  /**
593
842
  * The adapter port: everything one marketplace is, behind one shape.
594
843
  *
@@ -705,14 +954,30 @@ type AdapterTokenCache = Map<string, {
705
954
  token: string;
706
955
  expiresAt: number;
707
956
  }>;
957
+ /**
958
+ * A connection LINKED through the software's own app (FUT-5613): the store's
959
+ * access token comes from its refresh token, not from a client-credentials
960
+ * grant. `key` is where the token sits in {@link AdapterTokenCache} (delete it
961
+ * to forget a token the marketplace refused); `accessToken` answers the cached
962
+ * one or refreshes, once per connection however many calls ask at once.
963
+ */
964
+ interface AdapterGrant {
965
+ key: string;
966
+ accessToken(): Promise<{
967
+ token: string;
968
+ } | OutboundResult>;
969
+ }
708
970
  /** What one outbound call is handed. */
709
971
  interface AdapterCallContext {
710
972
  http: MarketplaceHttp;
973
+ /** The store's own credentials, or, for a linked connection, the software's app. */
711
974
  credentials: MarketplaceCredentials;
712
975
  environment: "SANDBOX" | "PRODUCTION";
713
976
  /** Written to no row, log or audit entry: memory only, per process. */
714
977
  tokens: AdapterTokenCache;
715
978
  now: Date;
979
+ /** Present for a linked connection: the token comes from here, never from a client-credentials grant. */
980
+ grant?: AdapterGrant;
716
981
  }
717
982
  /** One outbound call's answer, in the three shapes the engine acts on. */
718
983
  type OutboundResult =
@@ -818,6 +1083,16 @@ interface MarketplaceAdapter {
818
1083
  * API, and the host says so.
819
1084
  */
820
1085
  readonly availability?: MarketplaceAvailability;
1086
+ /**
1087
+ * OPTIONAL. Linking a store through the software's own app on this
1088
+ * marketplace (FUT-5613). Absent: a store connects with its own credentials only.
1089
+ */
1090
+ readonly linking?: MarketplaceLinking;
1091
+ /**
1092
+ * OPTIONAL. The marketplace's own courier (FUT-5665): the pickup-code check
1093
+ * and the tracking read. Absent: neither is offered, and the host says so.
1094
+ */
1095
+ readonly courier?: MarketplaceCourierApi;
821
1096
  /** Where "open it on the marketplace" goes: the order when `perOrderAppLink`, else the portal. Always https. */
822
1097
  appLink(order: Pick<OutboundOrderRef, "externalOrderId" | "externalDisplayId">): string;
823
1098
  }
@@ -837,4 +1112,4 @@ declare function tokenGrantResultOf(response: MarketplaceHttpResponse): Outbound
837
1112
  /** A call that never got an answer is a retry, with the reason a log can read. */
838
1113
  declare function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult>;
839
1114
 
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 };
1115
+ export { type MarketplaceCatalogue as $, type AdapterCallContext as A, type CatalogueReadResult as B, type CatalogueMenuEntry as C, type CatalogueReadWarning as D, type CatalogueReadWarningCode as E, type CatalogueSnapshot as F, type CatalogueSnapshotCategory as G, type CatalogueSnapshotItem as H, type CatalogueSnapshotOption as I, type CatalogueSnapshotOptionGroup as J, type CatalogueStoredImage as K, type CatalogueWarningCode as L, type MarketplaceAvailability as M, type NormalizedEvent as N, type OutboundResult as O, type PullCatalogue as P, type CourierTrackingCallResult as Q, type CourierTrackingResult as R, type StorePauseRequest as S, type FetchOrderResult as T, type LinkCallContext as U, type LinkCode as V, type LinkGrant as W, type LinkResult as X, type LinkedMerchant as Y, type MarketplaceAppCredentialsPort as Z, type MarketplaceCapabilities as _, type NormalizedMarketplaceOrder as a, type MarketplaceCourier as a0, type MarketplaceCourierAnswer as a1, type MarketplaceCourierEngine as a2, type MarketplaceCourierFacts as a3, type MarketplaceCourierStep as a4, type MarketplaceCourierTracking as a5, type MarketplaceCourierVehicle as a6, type MarketplaceCredentials as a7, type MarketplaceDeliveredBy as a8, type MarketplaceDiscountSponsor as a9, type MarketplaceHttp as aa, type MarketplaceHttpRequest as ab, type MarketplaceHttpResponse as ac, type MarketplaceLifecycle as ad, type MarketplaceLinkAttemptDelegate as ae, type MarketplaceOrderType as af, type NormalizedAddress as ag, type NormalizedBuyer as ah, type NormalizedOrderDiscount as ai, type NormalizedOrderLine as aj, type OutboundOrderRef as ak, PROVIDER_ID_PATTERN as al, type PickupCodeCallResult as am, type PickupCodeValidation as an, type StatusFacts as ao, type StatusStep as ap, type ValidatePickupCodeInput as aq, answered as ar, centsFromMajor as as, outboundResultOf as at, tokenGrantResultOf as au, 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 MarketplaceCourierApi as h, type NormalizedCourierEvent as i, type StorePauseResult as j, type StorePauseRef as k, type MarketplaceProvider as l, type CancellationReason as m, type AdapterGrant as n, type AdapterTokenCache as o, type CancellationOutcome as p, type CancellationRequestInput as q, type CatalogueCallContext as r, type CatalogueFailure as s, type CatalogueImage as t, type CatalogueItem as u, type CatalogueItemRef as v, type CataloguePublishResult as w, type CatalogueReadContext as x, type CatalogueReadNotice as y, type CatalogueReadRefusalCode as z };