@12-apps/marketplace 1.12.0 → 1.13.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 (39) hide show
  1. package/ADOPTING.md +44 -0
  2. package/README.md +12 -2
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-nUyZpLzz.d.ts → adapter-CQ4QiZPi.d.ts} +3 -2
  6. package/dist/{chunk-LACBT6NC.js → chunk-4J2KJ3ZW.js} +1 -1
  7. package/dist/{chunk-LACBT6NC.js.map → chunk-4J2KJ3ZW.js.map} +1 -1
  8. package/dist/{chunk-45ZVN5XI.js → chunk-CEWTV2TC.js} +63 -17
  9. package/dist/chunk-CEWTV2TC.js.map +1 -0
  10. package/dist/{chunk-L6FG6T4S.js → chunk-NFJQQWG4.js} +2 -2
  11. package/dist/{chunk-MIPNQ7X5.js → chunk-W57TITU4.js} +2 -2
  12. package/dist/{client-Ctas7WCS.d.ts → client-CCSnylou.d.ts} +1 -1
  13. package/dist/{engine-CIy9P7Cq.d.ts → engine-1KlJ_8jK.d.ts} +1 -1
  14. package/dist/hono/index.d.ts +2 -2
  15. package/dist/hono/index.js +2 -2
  16. package/dist/ifood/index.d.ts +15 -2
  17. package/dist/ifood/index.js +188 -118
  18. package/dist/ifood/index.js.map +1 -1
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +2 -2
  21. package/dist/keeta/index.d.ts +2 -2
  22. package/dist/keeta/index.js +2 -2
  23. package/dist/manifest/server.d.ts +2 -2
  24. package/dist/manifest/server.js +2 -2
  25. package/dist/rappi/index.d.ts +1 -1
  26. package/dist/rappi/index.js +1 -1
  27. package/dist/server/index.d.ts +2 -2
  28. package/dist/server/index.js +2 -2
  29. package/package.json +1 -1
  30. package/src/core/adapter.ts +2 -1
  31. package/src/core/connection-stamp.ts +61 -0
  32. package/src/core/fetch-order.ts +54 -12
  33. package/src/core/integration.ts +19 -4
  34. package/src/ifood/fetch-order.ts +103 -0
  35. package/src/ifood/index.ts +5 -1
  36. package/src/ifood/normalize.ts +23 -3
  37. package/dist/chunk-45ZVN5XI.js.map +0 -1
  38. /package/dist/{chunk-L6FG6T4S.js.map → chunk-NFJQQWG4.js.map} +0 -0
  39. /package/dist/{chunk-MIPNQ7X5.js.map → chunk-W57TITU4.js.map} +0 -0
package/ADOPTING.md CHANGED
@@ -443,3 +443,47 @@ ETA are the host's own columns.
443
443
 
444
444
  **Copy.** The engine adds no copy key; every sentence ("Código não confere",
445
445
  "Voltando para a loja") is the host's.
446
+
447
+ ## 11. iFood: the order fetched after PLACED (FUT-5800)
448
+
449
+ iFood's events name an order without carrying it: a PLACED is
450
+ `{ id, code: "PLC", fullCode: "PLACED", orderId, merchantId, createdAt }`, and
451
+ the order itself is `GET /order/v1.0/orders/{orderId}`. The iFood adapter now
452
+ marks a PLACED that carries no items `orderToFetch` and implements
453
+ `fetchOrder`, so a PLACED by id goes through the engine's existing order-fetch
454
+ path, the one 99Food and Keeta already use. A PLACED that does carry the order
455
+ (a replay, an older payload) is ingested from its body as before.
456
+
457
+ **The path is the webhook only.** The software connects to iFood as one
458
+ centralized app that iFood calls back (owner, FUT-5798: "no 30-second
459
+ polling"), so the engine has no events poller, calls neither
460
+ `events:polling` nor `events/acknowledgment`, and asks the host to schedule
461
+ nothing new.
462
+
463
+ **The contract.**
464
+
465
+ | | |
466
+ |---|---|
467
+ | **What the host binds** | Nothing new. The `marketplace.fetch-order` job already arrives with `MARKETPLACE_JOBS` (bind `{ engine }`); the `enqueue` port carries it and the `http` port makes its `GET`. A host that holds the job (its `enqueue` answers "not enqueued") holds every iFood order: each waits PENDING and the reconciliation sweep re-queues it. |
468
+ | **Delivery** | At least once. iFood redelivers a webhook it got no 2xx for; a second copy of an event is expected, never an error. |
469
+ | **Recorded before answered** | The webhook answers 2xx only after the delivery's inbox row is written (PENDING, "order details to fetch"). That 2xx is the acknowledgement: a delivery whose row could not be written answers no 2xx (the write's throw reaches the host's error handler), and iFood delivers it again. |
470
+ | **Dedupe** | By event id, at the inbox's unique `(provider, eventId)`: a redelivered PLACED is `duplicate`, queues nothing and calls nobody. By order id, at ingest's `(provider, externalOrderId)`: a second PLACED for the same order under another event id, or the same order also delivered with its body, fetches at most again and still lands ONE order. |
471
+ | **When iFood is called** | Never in the webhook request. The request queues `marketplace.fetch-order` (`{ clientId, inboxId }`, dedupe key `marketplace.fetch-order:<inboxId>`) after the row is written; the job reads the row, calls `GET /order/v1.0/orders/{id}` with the connection's bearer token (the adapter's token cache, the linked grant for a linked store) and ingests the answer through the one ingest path. The acceptance window counts from when the event arrived, not from when the fetch returned. |
472
+ | **Retry and backoff** | 3 attempts, exponential from 5 s. Retried: 404 (an order iFood has not replicated yet, ESTIMATED), 408, 425, 429, 5xx, a timeout or a network error, and a 2xx whose body is not JSON. Refused at once (row FAILED, no retry): a 2xx naming another order or carrying no items, and any other final 4xx. The last attempt settles the row FAILED (`order fetch failed: …`). The `marketplace.reconcile-inbox` sweep (every 5 min) re-queues a FAILED or still-PENDING row older than 2 minutes, until the row has been tried `maxInboxAttempts` times. |
473
+ | **Terminal state** | The inbox row: PROCESSED (ingested), IGNORED (cancelled before its body arrived), or FAILED with its reason once its attempts are spent. A FAILED row is never re-run past `maxInboxAttempts`; it stays as the evidence. |
474
+ | **401: credentials refused** | A 401 on the order read forgets the cached token and asks for a new one, once, inside the same attempt. A second 401, a 403 (the merchant has not authorized the app), or a token grant iFood refuses with a final 4xx, is our credentials refused, not the order's fault: the job does not retry it, settles the row FAILED (`order fetch failed: refused 401: …`), stamps the connection `status: "FAILED"` (what the connections screen shows) and calls `publishChanged`. The stamp is the engine's, for every adapter whose `fetchOrder` answers an `own` 4xx refusal (99Food and Keeta on a refused token grant too). No tight loop: the next try is the sweep's, at its 5-minute cadence and within the row's attempt bound. Only the credentials the call was made with are judged: a store that entered new ones meanwhile is not stamped. Re-entering the credentials resets the status to UNVERIFIED, and the next fetch that succeeds on credentials stamped FAILED sets them VERIFIED again (`lastVerifiedAt` too); the sweep then ingests what is still within its bound. |
475
+
476
+ **What the host does on the bump.** Nothing to code: confirm the
477
+ `marketplace.fetch-order` job runs on the worker (it was registered with the
478
+ other jobs since 1.x), and that the iFood webhook is registered. An iFood
479
+ order then reaches `order.create` as it did with a body. The outcome the
480
+ webhook answers for a PLACED by id is `{ received: true, outcome: "awaitingOrder" }`.
481
+
482
+ **What the fetched order carries.** The same `NormalizedMarketplaceOrder` a
483
+ PLACED with its body produces (lines with their SKU, name, quantity, unit price
484
+ and note; the buyer; the total, delivery fee, subtotal and discounts; the
485
+ order type, who delivers, the address and the pickup code), plus
486
+ `externalMerchantId` from the order's `merchant.id`: an order naming another
487
+ merchant than the connection's is refused FAILED, as for 99Food. The canonical
488
+ shape has no field for an item's options or for the payment methods; the raw
489
+ order is not stored by the engine.
package/README.md CHANGED
@@ -45,7 +45,7 @@ engine code (`src/__tests__/second-adapter.test.ts`).
45
45
  | **SKU map** | External SKU → host catalog id, every SKU ever seen a row; mapping checks the id is the tenant's. A link may name ONE variation of that id (`variationId`): the host's optional `order.catalogHasVariation` checks it belongs, and ingest hands it on the line as `variationRef` beside `subjectRef`. Without a variation the SKU maps to the item alone, as before. |
46
46
  | **Integration settings** | Enabled, environment, merchant id, auto-accept, acknowledgement window; credentials sealed as one blob by the host's secrets port, never returned. A connection is archived (reversible, audited), never deleted. |
47
47
  | **Outbound engine** | The `marketplace.outbound` job: confirm after accept (with the preparation time where the marketplace takes one), cancellation request with the stored reason code and SKUs. 2xx done; a 4xx other than 408/425/429 refused and final; anything else retried until the last attempt, which ends FAILED whatever went wrong. Stamps `confirmed_at`, `confirm_failed_at`, `cancellation_status` (PENDING, REQUESTED, CONFIRMED, FAILED). Idempotent by the row. Queued BEFORE the host's half runs, and the `marketplace.outbound-sweep` job re-queues every call still owed, so nothing is lost. The same sweep fails a request still waiting (never delivered, or delivered and unanswered) as TIMEOUT once past its answer window, and its retries stop (the adapter's `cancellationAnswerWindowMs`, or the engine's `cancellationWindowMs`), so no request waits forever. |
48
- | **Order fetch** | For a marketplace whose events name an order without carrying it (Open Delivery's `CREATED`), the adapter marks the event `orderToFetch`: the webhook records it PENDING and queues `marketplace.fetch-order`, which calls the adapter's `fetchOrder` and ingests through the same ingest path. No request calls out; the reconciliation sweep re-queues a row still owed, and a host that holds the job holds every fetch. |
48
+ | **Order fetch** | For a marketplace whose events name an order without carrying it (Open Delivery's `CREATED`, iFood's `PLACED`, FUT-5800), the adapter marks the event `orderToFetch`: the webhook records it PENDING and queues `marketplace.fetch-order`, which calls the adapter's `fetchOrder` and ingests through the same ingest path. No request calls out; the reconciliation sweep re-queues a row still owed, and a host that holds the job holds every fetch. A fetch our credentials are refused on (an `own` 4xx) is not retried by the queue and stamps the connection FAILED. Contract: [ADOPTING.md §11](./ADOPTING.md#11-ifood-the-order-fetched-after-placed-fut-5800). |
49
49
  | **Inbound outcomes** | A marketplace CANCELLED confirms a pending request; CANCELLATION_REQUEST_FAILED marks it FAILED; CONFIRMED is terminal. |
50
50
  | **Catalogue publishing** | A store turns a product ON or OFF per connected marketplace, with an optional price for that marketplace. One row per (store, marketplace, product): PUBLISHING → PUBLISHED, WITHDRAWING → WITHDRAWN, FAILED with a failure code (and the marketplace's own words for a refusal). The `marketplace.catalogue` job makes the call; the sweep re-queues what is owed. Push or pull is the adapter's. See [Catalogue publishing](#catalogue-publishing). |
51
51
  | **Adapter port** | `MarketplaceAdapter`: `normalize`, `readSignature`, `verifySignature`, `cancellationReasons`, `confirm`, `requestCancellation`, `appLink`, `capabilities`, and the optional `fetchOrder`, `catalogue` and `catalogueReader`. |
@@ -223,7 +223,17 @@ body fields and reason codes come from the portal's search snippets
223
223
  (2026-11-11). (Its Catalog module's pages were read whole on 2026-11-13: see
224
224
  [Catalogue publishing](#catalogue-publishing).)
225
225
  They live only in `src/ifood/outbound.ts` and `src/ifood/copy.ts`, whose
226
- headers say so, so the homologation run corrects two files. Tests never reach
226
+ headers say so, so the homologation run corrects two files.
227
+
228
+ The order read (FUT-5800) is partly verified. Only the EVENT shape was seen in
229
+ the sandbox (2026-11-27): iFood's events carry only the order id (`{ id, code,
230
+ fullCode, orderId, merchantId, createdAt }`), so a PLACED with no items is
231
+ fetched with `GET /order/v1.0/orders/{id}` by the `marketplace.fetch-order` job
232
+ and ingested like a PLACED carrying its body (`src/ifood/fetch-order.ts`). The
233
+ order body's field names are still the documented ones, not yet checked against
234
+ a real sandbox order. A 404 right after the PLACED is retried (ESTIMATED: not
235
+ yet served). Webhook only: the software is one centralized iFood app, so the
236
+ adapter does not poll iFood's events (FUT-5798). Tests never reach
227
237
  iFood: the HTTP client is the host's port.
228
238
 
229
239
  ## Linking a store through the software's own app (FUT-5613)
@@ -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-nUyZpLzz.js';
2
- import { O as OpenDeliveryApiBaseUrls } from '../client-Ctas7WCS.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-CQ4QiZPi.js';
2
+ import { O as OpenDeliveryApiBaseUrls } from '../client-CCSnylou.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-L6FG6T4S.js";
15
+ } from "../chunk-NFJQQWG4.js";
16
16
  import "../chunk-M2V4RFMA.js";
17
17
  import "../chunk-BD7DS3XM.js";
18
- import "../chunk-LACBT6NC.js";
18
+ import "../chunk-4J2KJ3ZW.js";
19
19
  import {
20
20
  __name
21
21
  } from "../chunk-7QVYU63E.js";
@@ -1059,7 +1059,8 @@ interface MarketplaceAdapter {
1059
1059
  * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a
1060
1060
  * marketplace whose events carry no order body). Called only from the
1061
1061
  * `marketplace.fetch-order` job. An adapter whose events always carry the
1062
- * order (iFood) leaves it out.
1062
+ * order leaves it out. A final `refused` marked `own` with a 4xx status is
1063
+ * our credentials refused: the engine stamps the connection FAILED.
1063
1064
  */
1064
1065
  fetchOrder?(ctx: AdapterCallContext, order: {
1065
1066
  externalOrderId: string;
@@ -1112,4 +1113,4 @@ declare function tokenGrantResultOf(response: MarketplaceHttpResponse): Outbound
1112
1113
  /** A call that never got an answer is a retry, with the reason a log can read. */
1113
1114
  declare function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult>;
1114
1115
 
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 };
1116
+ 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 FetchOrderResult as F, type CatalogueSnapshot as G, type CatalogueSnapshotCategory as H, type CatalogueSnapshotItem as I, type CatalogueSnapshotOption as J, type CatalogueSnapshotOptionGroup as K, type CatalogueStoredImage as L, type MarketplaceAvailability as M, type NormalizedEvent as N, type OutboundResult as O, type PullCatalogue as P, type CatalogueWarningCode as Q, type CourierTrackingCallResult as R, type StorePauseRequest as S, type CourierTrackingResult 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 };
@@ -31,4 +31,4 @@ export {
31
31
  tokenGrantResultOf,
32
32
  answered
33
33
  };
34
- //# sourceMappingURL=chunk-LACBT6NC.js.map
34
+ //# sourceMappingURL=chunk-4J2KJ3ZW.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { MarketplaceCatalogue } from \"./catalogue-port\";\nimport type { MarketplaceCourierApi } from \"./courier-port\";\nimport type { CatalogueReader } from \"./catalogue-read-port\";\nimport type { MarketplaceLinking } from \"./linking-port\";\nimport type { MarketplaceAvailability } from \"./pause-port\";\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceProvider,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n} from \"./types\";\n\n/**\n * The adapter port: everything one marketplace is, behind one shape.\n *\n * The owner's rule, which this file exists to make true: \"the integration\n * engine must be the same for all integrations: iFood, Rappi, 99. Only an\n * adapter is made for each one, to connect to the base engine.\"\n *\n * A marketplace differs from the next in five ways that matter to a store:\n * how its deliveries look and are signed (`normalize`, `readSignature`,\n * `verifySignature`), what it lets a store answer through its API (`confirm`,\n * `requestCancellation`), which reasons a refusal may carry\n * (`cancellationReasons`), and where a person goes when the API cannot do it\n * (`appLink`). Everything else — the inbox, the clock, the SKU map, the\n * outbound bookkeeping and its retries — is the engine's and does not change\n * with the marketplace.\n *\n * What a marketplace CAN do is stated by its adapter as\n * {@link MarketplaceCapabilities} and read by the engine and the host. It is\n * never inferred from the provider's id: a branch on the id outside an adapter\n * would make the next marketplace a code change instead of an adapter.\n *\n * The HTTP client is a host port ({@link MarketplaceHttp}), handed to every\n * outbound call. An adapter never reaches the network on its own, so tests\n * answer the seam and nothing else, and the host owns the timeout, the proxy\n * and the CA.\n */\n\n/** A marketplace's credentials, as the merchant supplies them. Sealed at rest. */\nexport interface MarketplaceCredentials {\n clientId: string;\n clientSecret: string;\n /**\n * The shared secret a delivery's signature is verified against. Separate\n * from the OAuth pair: a merchant rotating their webhook secret has not\n * re-onboarded.\n */\n webhookSecret: string | null;\n}\n\n/** What the host's HTTP client takes. */\nexport interface MarketplaceHttpRequest {\n /**\n * `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it.\n * `DELETE` since FUT-4851: iFood removes an interruption with it.\n */\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: string;\n}\n\n/** What the host's HTTP client answers: any status, never a throw for a 4xx or 5xx. */\nexport interface MarketplaceHttpResponse {\n status: number;\n body: string;\n}\n\n/** The host's HTTP client. It throws only when no answer arrived (a timeout, a network error). */\nexport type MarketplaceHttp = (request: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>;\n\n/** What a marketplace can do, stated by its adapter. */\nexport interface MarketplaceCapabilities {\n /** Accepting is answered through the API. */\n apiConfirm: boolean;\n /** A cancellation can be requested through the API at all. */\n apiCancel: boolean;\n /** …and still once the order was accepted. */\n cancelAfterAccept: boolean;\n /** The cancellation's outcome arrives later as an event rather than in the answer. */\n asyncCancellationOutcome: boolean;\n /** `appLink` names this order, rather than only the marketplace's portal. */\n perOrderAppLink: boolean;\n /** Confirming states a preparation time. */\n confirmTakesPreparationTime: boolean;\n /**\n * OPTIONAL. How long the marketplace takes, at most, to answer a store's\n * cancellation request, in milliseconds: past it the outbound sweep fails\n * the request as TIMEOUT. Absent: only the 24-hour give-up applies.\n */\n cancellationAnswerWindowMs?: number;\n /**\n * OPTIONAL. The steps this marketplace can be told about (`informStatus`).\n * Absent or empty: the engine tells it nothing.\n */\n statusSteps?: readonly StatusStep[];\n}\n\n/**\n * A step of the order the store tells the marketplace about (FUT-4653): the\n * order is ready for pickup, the courier left, the order was handed over.\n */\nexport type StatusStep = \"READY\" | \"DISPATCHED\" | \"HANDED_OVER\";\n\n/** What a status call is told about the order: who carries it (null: a take-out, or unstated). */\nexport interface StatusFacts {\n step: StatusStep;\n deliveredBy: MarketplaceDeliveredBy | null;\n}\n\n/** One reason a store may give for refusing or cancelling an order. */\nexport interface CancellationReason {\n /** The marketplace's own code, sent verbatim. */\n code: string;\n /** The label the host was configured with for this code (a named pack). */\n label: string;\n /** This reason means \"an item is unavailable\": the host preselects it when stock is short. */\n itemUnavailable: boolean;\n /** The marketplace requires the offending SKUs with this reason. */\n needsItems: boolean;\n}\n\n/** The order an outbound call is about, as the engine knows it. */\nexport interface OutboundOrderRef {\n externalOrderId: string;\n externalDisplayId: string | null;\n /** The host's own id for the order. */\n hostOrderCode: string;\n /** When the engine recorded the order. */\n placedAt: Date;\n}\n\n/** A per-engine token cache an adapter reads and fills. Never persisted. */\nexport type AdapterTokenCache = Map<string, { token: string; expiresAt: number }>;\n\n/**\n * A connection LINKED through the software's own app (FUT-5613): the store's\n * access token comes from its refresh token, not from a client-credentials\n * grant. `key` is where the token sits in {@link AdapterTokenCache} (delete it\n * to forget a token the marketplace refused); `accessToken` answers the cached\n * one or refreshes, once per connection however many calls ask at once.\n */\nexport interface AdapterGrant {\n key: string;\n accessToken(): Promise<{ token: string } | OutboundResult>;\n}\n\n/** What one outbound call is handed. */\nexport interface AdapterCallContext {\n http: MarketplaceHttp;\n /** The store's own credentials, or, for a linked connection, the software's app. */\n credentials: MarketplaceCredentials;\n environment: \"SANDBOX\" | \"PRODUCTION\";\n /** Written to no row, log or audit entry: memory only, per process. */\n tokens: AdapterTokenCache;\n now: Date;\n /** Present for a linked connection: the token comes from here, never from a client-credentials grant. */\n grant?: AdapterGrant;\n}\n\n/** One outbound call's answer, in the three shapes the engine acts on. */\nexport type OutboundResult =\n /** 2xx. For a marketplace whose outcome is asynchronous, \"the request was taken\". */\n | { kind: \"accepted\" }\n /**\n * A final 4xx (not 408/425/429): never retried. `own` marks a refusal that\n * is not the marketplace's judgement of the order: our credentials were not\n * accepted, or our request was malformed. A cancellation request that ends\n * so fails as UNREACHABLE, not REFUSED.\n */\n | { kind: \"refused\"; status: number; message: string; own?: true }\n /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */\n | { kind: \"retry\"; reason: string };\n\n/**\n * One order-body fetch's answer: the order, normalized, or the same refusal and\n * retry shapes an outbound call answers with (a 404 for an expired order is a\n * refusal; a 5xx, a timeout or a 429 is a retry).\n */\nexport type FetchOrderResult =\n | { kind: \"order\"; order: NormalizedMarketplaceOrder }\n | Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** What a cancellation request carries. */\nexport interface CancellationRequestInput {\n reason: CancellationReason;\n /** Free text from the store; empty means \"the reason's own label\". */\n text: string;\n mode: \"MANUAL\" | \"AUTO\";\n offendingSkus: readonly string[];\n}\n\n/** One marketplace, in and out. */\nexport interface MarketplaceAdapter {\n readonly provider: MarketplaceProvider;\n readonly capabilities: MarketplaceCapabilities;\n /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */\n normalize(payload: unknown): NormalizedEvent | null;\n /** Which header carries this marketplace's signature, read off the request. */\n readSignature(header: (name: string) => string | null): string | null;\n /** Is this delivery's signature the one this store's secret would produce? */\n verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;\n /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */\n cancellationReasons(): readonly CancellationReason[];\n /** Tell the marketplace the store accepted the order. */\n confirm(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n ): Promise<OutboundResult>;\n /** Ask the marketplace to cancel the order, with one of its own reasons. */\n requestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n ): Promise<OutboundResult>;\n /**\n * OPTIONAL. Whether this marketplace takes this step for this kind of order,\n * answered offline, with no call: the job asks it BEFORE it claims anything\n * (an unsupported step leaves no row). Absent: every step in\n * `capabilities.statusSteps` is taken for every order.\n */\n statusSupported?(facts: StatusFacts): boolean;\n /**\n * OPTIONAL. Tell the marketplace the order reached a step (FUT-4653). Called\n * only from the `marketplace.outbound` job, action `status`. `unsupported`\n * (no endpoint for this step and this kind of order) ends the job with no\n * row. Absent: the marketplace is told nothing.\n */\n informStatus?(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n facts: StatusFacts,\n ): Promise<OutboundResult | { kind: \"unsupported\" }>;\n /**\n * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a\n * marketplace whose events carry no order body). Called only from the\n * `marketplace.fetch-order` job. An adapter whose events always carry the\n * order (iFood) leaves it out.\n */\n fetchOrder?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<FetchOrderResult>;\n /**\n * OPTIONAL. Publishing the store's products to this marketplace's catalogue\n * (FUT-4768): `push` (the adapter writes each item) or `pull` (the\n * marketplace reads a menu document the host serves). Absent: the\n * marketplace cannot be published to, and the host says so.\n */\n readonly catalogue?: MarketplaceCatalogue;\n /**\n * OPTIONAL. Reading the menu the store already keeps on this marketplace,\n * through its own connection, for the host to import (FUT-951). Absent: the\n * menu cannot be read through an API, and the host says so.\n */\n readonly catalogueReader?: CatalogueReader;\n /**\n * OPTIONAL. Closing the store on this marketplace for a while, and opening\n * it again (FUT-4851). Absent: the marketplace cannot be paused through an\n * API, and the host says so.\n */\n readonly availability?: MarketplaceAvailability;\n /**\n * OPTIONAL. Linking a store through the software's own app on this\n * marketplace (FUT-5613). Absent: a store connects with its own credentials only.\n */\n readonly linking?: MarketplaceLinking;\n /**\n * OPTIONAL. The marketplace's own courier (FUT-5665): the pickup-code check\n * and the tracking read. Absent: neither is offered, and the host says so.\n */\n readonly courier?: MarketplaceCourierApi;\n /** Where \"open it on the marketplace\" goes: the order when `perOrderAppLink`, else the portal. Always https. */\n appLink(order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string;\n}\n\n/**\n * The 4xx statuses that are NOT a refusal: a request timeout (408), \"too\n * early\" (425) and a rate limit (429) say \"ask again later\" by HTTP's own\n * semantics, and a marketplace rate-limits its merchant API.\n */\nconst TRANSIENT_CLIENT_STATUSES = new Set([408, 425, 429]);\n\n/**\n * Read one HTTP answer the way the engine acts on it. Shared by every adapter\n * whose API speaks plain status codes, so the rule is one rule rather than one\n * per marketplace: 2xx accepted; a 4xx other than 408/425/429 refused and\n * final; everything else (408, 425, 429, 5xx, anything unexpected) retried.\n */\nexport function outboundResultOf(response: MarketplaceHttpResponse): OutboundResult {\n if (response.status >= 200 && response.status < 300) return { kind: \"accepted\" };\n const message = response.body.slice(0, 300);\n const refusal = response.status >= 400 && response.status < 500 && !TRANSIENT_CLIENT_STATUSES.has(response.status);\n if (refusal) return { kind: \"refused\", status: response.status, message };\n return { kind: \"retry\", reason: `status ${response.status}: ${message}` };\n}\n\n/**\n * {@link outboundResultOf} for a token grant: a final 4xx there says our\n * credentials were not accepted, never a judgement of any order, so it is an\n * `own` refusal.\n */\nexport function tokenGrantResultOf(response: MarketplaceHttpResponse): OutboundResult {\n const result = outboundResultOf(response);\n return result.kind === \"refused\" ? { ...result, own: true } : result;\n}\n\n/** A call that never got an answer is a retry, with the reason a log can read. */\nexport async function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n"],"mappings":";;;;;AAwRA,IAAM,4BAA4B,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAQlD,SAAS,iBAAiB,UAAmD;AAClF,MAAI,SAAS,UAAU,OAAO,SAAS,SAAS,IAAK,QAAO,EAAE,MAAM,WAAW;AAC/E,QAAM,UAAU,SAAS,KAAK,MAAM,GAAG,GAAG;AAC1C,QAAM,UAAU,SAAS,UAAU,OAAO,SAAS,SAAS,OAAO,CAAC,0BAA0B,IAAI,SAAS,MAAM;AACjH,MAAI,QAAS,QAAO,EAAE,MAAM,WAAW,QAAQ,SAAS,QAAQ,QAAQ;AACxE,SAAO,EAAE,MAAM,SAAS,QAAQ,UAAU,SAAS,MAAM,KAAK,OAAO,GAAG;AAC1E;AANgB;AAaT,SAAS,mBAAmB,UAAmD;AACpF,QAAM,SAAS,iBAAiB,QAAQ;AACxC,SAAO,OAAO,SAAS,YAAY,EAAE,GAAG,QAAQ,KAAK,KAAK,IAAI;AAChE;AAHgB;AAMhB,eAAsB,SAAS,MAA8D;AAC3F,MAAI;AACF,WAAO,MAAM,KAAK;AAAA,EACpB,SAAS,OAAO;AACd,WAAO,EAAE,MAAM,SAAS,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE;AAAA,EACzF;AACF;AANsB;","names":[]}
1
+ {"version":3,"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { MarketplaceCatalogue } from \"./catalogue-port\";\nimport type { MarketplaceCourierApi } from \"./courier-port\";\nimport type { CatalogueReader } from \"./catalogue-read-port\";\nimport type { MarketplaceLinking } from \"./linking-port\";\nimport type { MarketplaceAvailability } from \"./pause-port\";\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceProvider,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n} from \"./types\";\n\n/**\n * The adapter port: everything one marketplace is, behind one shape.\n *\n * The owner's rule, which this file exists to make true: \"the integration\n * engine must be the same for all integrations: iFood, Rappi, 99. Only an\n * adapter is made for each one, to connect to the base engine.\"\n *\n * A marketplace differs from the next in five ways that matter to a store:\n * how its deliveries look and are signed (`normalize`, `readSignature`,\n * `verifySignature`), what it lets a store answer through its API (`confirm`,\n * `requestCancellation`), which reasons a refusal may carry\n * (`cancellationReasons`), and where a person goes when the API cannot do it\n * (`appLink`). Everything else — the inbox, the clock, the SKU map, the\n * outbound bookkeeping and its retries — is the engine's and does not change\n * with the marketplace.\n *\n * What a marketplace CAN do is stated by its adapter as\n * {@link MarketplaceCapabilities} and read by the engine and the host. It is\n * never inferred from the provider's id: a branch on the id outside an adapter\n * would make the next marketplace a code change instead of an adapter.\n *\n * The HTTP client is a host port ({@link MarketplaceHttp}), handed to every\n * outbound call. An adapter never reaches the network on its own, so tests\n * answer the seam and nothing else, and the host owns the timeout, the proxy\n * and the CA.\n */\n\n/** A marketplace's credentials, as the merchant supplies them. Sealed at rest. */\nexport interface MarketplaceCredentials {\n clientId: string;\n clientSecret: string;\n /**\n * The shared secret a delivery's signature is verified against. Separate\n * from the OAuth pair: a merchant rotating their webhook secret has not\n * re-onboarded.\n */\n webhookSecret: string | null;\n}\n\n/** What the host's HTTP client takes. */\nexport interface MarketplaceHttpRequest {\n /**\n * `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it.\n * `DELETE` since FUT-4851: iFood removes an interruption with it.\n */\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: string;\n}\n\n/** What the host's HTTP client answers: any status, never a throw for a 4xx or 5xx. */\nexport interface MarketplaceHttpResponse {\n status: number;\n body: string;\n}\n\n/** The host's HTTP client. It throws only when no answer arrived (a timeout, a network error). */\nexport type MarketplaceHttp = (request: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>;\n\n/** What a marketplace can do, stated by its adapter. */\nexport interface MarketplaceCapabilities {\n /** Accepting is answered through the API. */\n apiConfirm: boolean;\n /** A cancellation can be requested through the API at all. */\n apiCancel: boolean;\n /** …and still once the order was accepted. */\n cancelAfterAccept: boolean;\n /** The cancellation's outcome arrives later as an event rather than in the answer. */\n asyncCancellationOutcome: boolean;\n /** `appLink` names this order, rather than only the marketplace's portal. */\n perOrderAppLink: boolean;\n /** Confirming states a preparation time. */\n confirmTakesPreparationTime: boolean;\n /**\n * OPTIONAL. How long the marketplace takes, at most, to answer a store's\n * cancellation request, in milliseconds: past it the outbound sweep fails\n * the request as TIMEOUT. Absent: only the 24-hour give-up applies.\n */\n cancellationAnswerWindowMs?: number;\n /**\n * OPTIONAL. The steps this marketplace can be told about (`informStatus`).\n * Absent or empty: the engine tells it nothing.\n */\n statusSteps?: readonly StatusStep[];\n}\n\n/**\n * A step of the order the store tells the marketplace about (FUT-4653): the\n * order is ready for pickup, the courier left, the order was handed over.\n */\nexport type StatusStep = \"READY\" | \"DISPATCHED\" | \"HANDED_OVER\";\n\n/** What a status call is told about the order: who carries it (null: a take-out, or unstated). */\nexport interface StatusFacts {\n step: StatusStep;\n deliveredBy: MarketplaceDeliveredBy | null;\n}\n\n/** One reason a store may give for refusing or cancelling an order. */\nexport interface CancellationReason {\n /** The marketplace's own code, sent verbatim. */\n code: string;\n /** The label the host was configured with for this code (a named pack). */\n label: string;\n /** This reason means \"an item is unavailable\": the host preselects it when stock is short. */\n itemUnavailable: boolean;\n /** The marketplace requires the offending SKUs with this reason. */\n needsItems: boolean;\n}\n\n/** The order an outbound call is about, as the engine knows it. */\nexport interface OutboundOrderRef {\n externalOrderId: string;\n externalDisplayId: string | null;\n /** The host's own id for the order. */\n hostOrderCode: string;\n /** When the engine recorded the order. */\n placedAt: Date;\n}\n\n/** A per-engine token cache an adapter reads and fills. Never persisted. */\nexport type AdapterTokenCache = Map<string, { token: string; expiresAt: number }>;\n\n/**\n * A connection LINKED through the software's own app (FUT-5613): the store's\n * access token comes from its refresh token, not from a client-credentials\n * grant. `key` is where the token sits in {@link AdapterTokenCache} (delete it\n * to forget a token the marketplace refused); `accessToken` answers the cached\n * one or refreshes, once per connection however many calls ask at once.\n */\nexport interface AdapterGrant {\n key: string;\n accessToken(): Promise<{ token: string } | OutboundResult>;\n}\n\n/** What one outbound call is handed. */\nexport interface AdapterCallContext {\n http: MarketplaceHttp;\n /** The store's own credentials, or, for a linked connection, the software's app. */\n credentials: MarketplaceCredentials;\n environment: \"SANDBOX\" | \"PRODUCTION\";\n /** Written to no row, log or audit entry: memory only, per process. */\n tokens: AdapterTokenCache;\n now: Date;\n /** Present for a linked connection: the token comes from here, never from a client-credentials grant. */\n grant?: AdapterGrant;\n}\n\n/** One outbound call's answer, in the three shapes the engine acts on. */\nexport type OutboundResult =\n /** 2xx. For a marketplace whose outcome is asynchronous, \"the request was taken\". */\n | { kind: \"accepted\" }\n /**\n * A final 4xx (not 408/425/429): never retried. `own` marks a refusal that\n * is not the marketplace's judgement of the order: our credentials were not\n * accepted, or our request was malformed. A cancellation request that ends\n * so fails as UNREACHABLE, not REFUSED.\n */\n | { kind: \"refused\"; status: number; message: string; own?: true }\n /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */\n | { kind: \"retry\"; reason: string };\n\n/**\n * One order-body fetch's answer: the order, normalized, or the same refusal and\n * retry shapes an outbound call answers with (a 404 for an expired order is a\n * refusal; a 5xx, a timeout or a 429 is a retry).\n */\nexport type FetchOrderResult =\n | { kind: \"order\"; order: NormalizedMarketplaceOrder }\n | Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** What a cancellation request carries. */\nexport interface CancellationRequestInput {\n reason: CancellationReason;\n /** Free text from the store; empty means \"the reason's own label\". */\n text: string;\n mode: \"MANUAL\" | \"AUTO\";\n offendingSkus: readonly string[];\n}\n\n/** One marketplace, in and out. */\nexport interface MarketplaceAdapter {\n readonly provider: MarketplaceProvider;\n readonly capabilities: MarketplaceCapabilities;\n /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */\n normalize(payload: unknown): NormalizedEvent | null;\n /** Which header carries this marketplace's signature, read off the request. */\n readSignature(header: (name: string) => string | null): string | null;\n /** Is this delivery's signature the one this store's secret would produce? */\n verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;\n /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */\n cancellationReasons(): readonly CancellationReason[];\n /** Tell the marketplace the store accepted the order. */\n confirm(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n ): Promise<OutboundResult>;\n /** Ask the marketplace to cancel the order, with one of its own reasons. */\n requestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n ): Promise<OutboundResult>;\n /**\n * OPTIONAL. Whether this marketplace takes this step for this kind of order,\n * answered offline, with no call: the job asks it BEFORE it claims anything\n * (an unsupported step leaves no row). Absent: every step in\n * `capabilities.statusSteps` is taken for every order.\n */\n statusSupported?(facts: StatusFacts): boolean;\n /**\n * OPTIONAL. Tell the marketplace the order reached a step (FUT-4653). Called\n * only from the `marketplace.outbound` job, action `status`. `unsupported`\n * (no endpoint for this step and this kind of order) ends the job with no\n * row. Absent: the marketplace is told nothing.\n */\n informStatus?(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n facts: StatusFacts,\n ): Promise<OutboundResult | { kind: \"unsupported\" }>;\n /**\n * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a\n * marketplace whose events carry no order body). Called only from the\n * `marketplace.fetch-order` job. An adapter whose events always carry the\n * order leaves it out. A final `refused` marked `own` with a 4xx status is\n * our credentials refused: the engine stamps the connection FAILED.\n */\n fetchOrder?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<FetchOrderResult>;\n /**\n * OPTIONAL. Publishing the store's products to this marketplace's catalogue\n * (FUT-4768): `push` (the adapter writes each item) or `pull` (the\n * marketplace reads a menu document the host serves). Absent: the\n * marketplace cannot be published to, and the host says so.\n */\n readonly catalogue?: MarketplaceCatalogue;\n /**\n * OPTIONAL. Reading the menu the store already keeps on this marketplace,\n * through its own connection, for the host to import (FUT-951). Absent: the\n * menu cannot be read through an API, and the host says so.\n */\n readonly catalogueReader?: CatalogueReader;\n /**\n * OPTIONAL. Closing the store on this marketplace for a while, and opening\n * it again (FUT-4851). Absent: the marketplace cannot be paused through an\n * API, and the host says so.\n */\n readonly availability?: MarketplaceAvailability;\n /**\n * OPTIONAL. Linking a store through the software's own app on this\n * marketplace (FUT-5613). Absent: a store connects with its own credentials only.\n */\n readonly linking?: MarketplaceLinking;\n /**\n * OPTIONAL. The marketplace's own courier (FUT-5665): the pickup-code check\n * and the tracking read. Absent: neither is offered, and the host says so.\n */\n readonly courier?: MarketplaceCourierApi;\n /** Where \"open it on the marketplace\" goes: the order when `perOrderAppLink`, else the portal. Always https. */\n appLink(order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string;\n}\n\n/**\n * The 4xx statuses that are NOT a refusal: a request timeout (408), \"too\n * early\" (425) and a rate limit (429) say \"ask again later\" by HTTP's own\n * semantics, and a marketplace rate-limits its merchant API.\n */\nconst TRANSIENT_CLIENT_STATUSES = new Set([408, 425, 429]);\n\n/**\n * Read one HTTP answer the way the engine acts on it. Shared by every adapter\n * whose API speaks plain status codes, so the rule is one rule rather than one\n * per marketplace: 2xx accepted; a 4xx other than 408/425/429 refused and\n * final; everything else (408, 425, 429, 5xx, anything unexpected) retried.\n */\nexport function outboundResultOf(response: MarketplaceHttpResponse): OutboundResult {\n if (response.status >= 200 && response.status < 300) return { kind: \"accepted\" };\n const message = response.body.slice(0, 300);\n const refusal = response.status >= 400 && response.status < 500 && !TRANSIENT_CLIENT_STATUSES.has(response.status);\n if (refusal) return { kind: \"refused\", status: response.status, message };\n return { kind: \"retry\", reason: `status ${response.status}: ${message}` };\n}\n\n/**\n * {@link outboundResultOf} for a token grant: a final 4xx there says our\n * credentials were not accepted, never a judgement of any order, so it is an\n * `own` refusal.\n */\nexport function tokenGrantResultOf(response: MarketplaceHttpResponse): OutboundResult {\n const result = outboundResultOf(response);\n return result.kind === \"refused\" ? { ...result, own: true } : result;\n}\n\n/** A call that never got an answer is a retry, with the reason a log can read. */\nexport async function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n"],"mappings":";;;;;AAyRA,IAAM,4BAA4B,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAQlD,SAAS,iBAAiB,UAAmD;AAClF,MAAI,SAAS,UAAU,OAAO,SAAS,SAAS,IAAK,QAAO,EAAE,MAAM,WAAW;AAC/E,QAAM,UAAU,SAAS,KAAK,MAAM,GAAG,GAAG;AAC1C,QAAM,UAAU,SAAS,UAAU,OAAO,SAAS,SAAS,OAAO,CAAC,0BAA0B,IAAI,SAAS,MAAM;AACjH,MAAI,QAAS,QAAO,EAAE,MAAM,WAAW,QAAQ,SAAS,QAAQ,QAAQ;AACxE,SAAO,EAAE,MAAM,SAAS,QAAQ,UAAU,SAAS,MAAM,KAAK,OAAO,GAAG;AAC1E;AANgB;AAaT,SAAS,mBAAmB,UAAmD;AACpF,QAAM,SAAS,iBAAiB,QAAQ;AACxC,SAAO,OAAO,SAAS,YAAY,EAAE,GAAG,QAAQ,KAAK,KAAK,IAAI;AAChE;AAHgB;AAMhB,eAAsB,SAAS,MAA8D;AAC3F,MAAI;AACF,WAAO,MAAM,KAAK;AAAA,EACpB,SAAS,OAAO;AACd,WAAO,EAAE,MAAM,SAAS,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE;AAAA,EACzF;AACF;AANsB;","names":[]}
@@ -484,21 +484,26 @@ async function markMarketplaceEventSeen(db, clientId, provider, at) {
484
484
  }
485
485
  __name(markMarketplaceEventSeen, "markMarketplaceEventSeen");
486
486
  async function readOutboundConnection(ctx, clientId, provider) {
487
+ return (await readSealedOutboundConnection(ctx, clientId, provider))?.connection ?? null;
488
+ }
489
+ __name(readOutboundConnection, "readOutboundConnection");
490
+ async function readSealedOutboundConnection(ctx, clientId, provider) {
487
491
  const db = await ctx.ports.db();
488
492
  const row = await db.marketplaceIntegration.findUnique({
489
493
  where: { clientId_provider: { clientId, provider } },
490
494
  select: { environment: true, credentials: true, authMode: true }
491
495
  });
492
496
  if (!row || row.credentials === "") return null;
497
+ const sealed = row.credentials;
493
498
  const environment = environmentOf(row.environment);
494
- if (row.authMode !== "LINKED") return { environment, credentials: openCredentials(ctx, row.credentials) };
499
+ if (row.authMode !== "LINKED") return { connection: { environment, credentials: openCredentials(ctx, sealed) }, sealed };
495
500
  const app = await appCredentialsOf(ctx, provider, environment);
496
501
  if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
497
- const refreshToken = openLinkRefreshToken(ctx, row.credentials);
498
- const link = { clientId, provider, environment, refreshToken, app, sealed: row.credentials };
499
- return { environment, credentials: app, grant: linkGrant(ctx, link) };
502
+ const refreshToken = openLinkRefreshToken(ctx, sealed);
503
+ const link = { clientId, provider, environment, refreshToken, app, sealed };
504
+ return { connection: { environment, credentials: app, grant: linkGrant(ctx, link) }, sealed };
500
505
  }
501
- __name(readOutboundConnection, "readOutboundConnection");
506
+ __name(readSealedOutboundConnection, "readSealedOutboundConnection");
502
507
 
503
508
  // src/core/catalogue-store.ts
504
509
  var CATALOGUE_ROW_SELECT = {
@@ -1027,6 +1032,32 @@ async function ingestMarketplaceOrder(ctx, input) {
1027
1032
  }
1028
1033
  __name(ingestMarketplaceOrder, "ingestMarketplaceOrder");
1029
1034
 
1035
+ // src/core/connection-stamp.ts
1036
+ async function markCredentialsRefused(ctx, input) {
1037
+ await stampConnection(ctx, input, { archivedAt: null }, { status: "FAILED" });
1038
+ }
1039
+ __name(markCredentialsRefused, "markCredentialsRefused");
1040
+ async function markCredentialsAccepted(ctx, input) {
1041
+ await stampConnection(ctx, input, { status: "FAILED" }, { status: "VERIFIED", lastVerifiedAt: ctx.ports.clock.now() });
1042
+ }
1043
+ __name(markCredentialsAccepted, "markCredentialsAccepted");
1044
+ async function stampConnection(ctx, input, where, data) {
1045
+ const { clientId, provider, sealed } = input;
1046
+ try {
1047
+ const db = await ctx.ports.db();
1048
+ const { count } = await db.marketplaceIntegration.updateMany({
1049
+ where: { clientId, provider, credentials: sealed, ...where },
1050
+ data
1051
+ });
1052
+ if (count > 0) ctx.ports.publishChanged(clientId);
1053
+ } catch (error) {
1054
+ ctx.ports.logger.error(
1055
+ `marketplace: ${provider} connection of ${clientId} not stamped ${String(data.status)}: ` + (error instanceof Error ? error.message : String(error))
1056
+ );
1057
+ }
1058
+ }
1059
+ __name(stampConnection, "stampConnection");
1060
+
1030
1061
  // src/core/cancellation-outcome.ts
1031
1062
  async function tell(ctx, what, orderId, call2) {
1032
1063
  try {
@@ -1357,22 +1388,23 @@ async function owedFetch(ctx, payload) {
1357
1388
  __name(owedFetch, "owedFetch");
1358
1389
  async function fetchThroughAdapter(ctx, clientId, provider, externalOrderId) {
1359
1390
  const adapter = ctx.registry.get(provider);
1360
- if (!adapter?.fetchOrder) return { kind: "refused", status: 0, message: `${provider} cannot fetch an order` };
1361
- let connection;
1391
+ if (!adapter?.fetchOrder) return { result: { kind: "refused", status: 0, message: `${provider} cannot fetch an order` }, sealed: null };
1392
+ let opened;
1362
1393
  try {
1363
- connection = await readOutboundConnection(ctx, clientId, provider);
1394
+ opened = await readSealedOutboundConnection(ctx, clientId, provider);
1364
1395
  } catch (error) {
1365
1396
  const reason = error instanceof Error ? error.message : String(error);
1366
- return { kind: "refused", status: 0, message: `credentials do not open: ${reason}` };
1397
+ return { result: { kind: "refused", status: 0, message: `credentials do not open: ${reason}` }, sealed: null };
1367
1398
  }
1368
- if (!connection) return { kind: "refused", status: 0, message: "no credentials on file" };
1399
+ if (!opened) return { result: { kind: "refused", status: 0, message: "no credentials on file" }, sealed: null };
1369
1400
  try {
1370
- return await adapter.fetchOrder(
1371
- { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
1401
+ const result = await adapter.fetchOrder(
1402
+ { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...opened.connection },
1372
1403
  { externalOrderId }
1373
1404
  );
1405
+ return { result, sealed: opened.sealed };
1374
1406
  } catch (error) {
1375
- return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
1407
+ return { result: { kind: "retry", reason: error instanceof Error ? error.message : String(error) }, sealed: opened.sealed };
1376
1408
  }
1377
1409
  }
1378
1410
  __name(fetchThroughAdapter, "fetchThroughAdapter");
@@ -1412,6 +1444,10 @@ async function ingestFetched(ctx, row, clientId, order, target) {
1412
1444
  return { kind: "ingested", orderId: ingested.orderId, unmappedSkus: ingested.unmappedSkus };
1413
1445
  }
1414
1446
  __name(ingestFetched, "ingestFetched");
1447
+ function credentialsRefused(result) {
1448
+ return result.kind === "refused" && result.own === true && result.status >= 400 && result.status < 500;
1449
+ }
1450
+ __name(credentialsRefused, "credentialsRefused");
1415
1451
  async function runFetchOrder(ctx, payload, attempt) {
1416
1452
  const owed = await owedFetch(ctx, payload);
1417
1453
  if (typeof owed === "string") return { kind: "skipped", reason: owed };
@@ -1421,17 +1457,27 @@ async function runFetchOrder(ctx, payload, attempt) {
1421
1457
  await deferInboxEvent(ctx, row.id, "integration is not enabled");
1422
1458
  return { kind: "skipped", reason: "integration is not enabled" };
1423
1459
  }
1424
- const result = await fetchThroughAdapter(ctx, payload.clientId, event.provider, event.externalOrderId ?? "");
1425
- if (result.kind === "order") return ingestFetched(ctx, row, payload.clientId, result.order, target);
1460
+ const { result, sealed } = await fetchThroughAdapter(ctx, payload.clientId, event.provider, event.externalOrderId ?? "");
1461
+ const stamp = sealed === null ? null : { clientId: payload.clientId, provider: event.provider, sealed };
1462
+ if (result.kind === "order") {
1463
+ if (stamp) await markCredentialsAccepted(ctx, stamp);
1464
+ return ingestFetched(ctx, row, payload.clientId, result.order, target);
1465
+ }
1466
+ return endUnfetched(ctx, { row, event, result, attempt, stamp });
1467
+ }
1468
+ __name(runFetchOrder, "runFetchOrder");
1469
+ async function endUnfetched(ctx, input) {
1470
+ const { row, event, result, attempt } = input;
1426
1471
  const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
1427
1472
  if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
1428
1473
  throw new FetchOrderRetryError(`fetch of ${event.externalOrderId ?? "?"} (inbox ${row.id}): ${reason}`);
1429
1474
  }
1475
+ if (input.stamp && credentialsRefused(result)) await markCredentialsRefused(ctx, input.stamp);
1430
1476
  await settleInboxEvent(ctx, row.id, "FAILED", `order fetch failed: ${reason}`);
1431
1477
  ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} failed: ${reason}`);
1432
1478
  return { kind: "failed", reason };
1433
1479
  }
1434
- __name(runFetchOrder, "runFetchOrder");
1480
+ __name(endUnfetched, "endUnfetched");
1435
1481
 
1436
1482
  // src/core/catalogue-sweep.ts
1437
1483
  var CATALOGUE_STALE_MS = 10 * 6e4;
@@ -2480,4 +2526,4 @@ export {
2480
2526
  AvailabilityRetryError,
2481
2527
  runAvailability
2482
2528
  };
2483
- //# sourceMappingURL=chunk-45ZVN5XI.js.map
2529
+ //# sourceMappingURL=chunk-CEWTV2TC.js.map