@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/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export { A as AcceptanceDecision, a as AcceptanceStatus, b as AvailabilityJobPayload, c as AvailabilityOutcome, d as AvailabilityRetryError, e as AvailabilitySweepResult, B as BulkProblem, f as BulkProblemCode, g as BulkResult, C as CancellationFailureReason, h as CancellationStatus, i as CatalogueAction, j as CatalogueActionResult, k as CatalogueDocumentResult, l as CatalogueFailedAction, m as CatalogueFailureCode, n as CatalogueJobPayload, o as CatalogueOutcome, p as CataloguePublicationView, q as CataloguePublishInput, r as CatalogueRefusalCode, s as CatalogueRetryError, t as CatalogueStatus, u as CatalogueTarget, D as DecideManyResult, v as DecidedRow, w as DecisionInput, x as DecisionProblem, y as DecisionProblemCode, z as DecisionResult, E as DeliveryOutcome, F as ExpirySweepResult, G as FetchOrderJobPayload, H as FetchOrderOutcome, I as FetchOrderRetryError, J as InformStatusInput, K as IngestResult, L as IngestSettings, M as IngestionTarget, N as IntegrationRowInput, O as LinkFailure, P as LinkFinished, Q as LinkPendingView, R as LinkRefusalCode, S as MARKETPLACE_AVAILABILITY_JOB, T as MARKETPLACE_CATALOGUE_JOB, U as MARKETPLACE_FETCH_ORDER_JOB, V as MARKETPLACE_OUTBOUND_JOB, W as MarketplaceAdmission, X as MarketplaceAdmissionRequest, Y as MarketplaceAdmissionResult, Z as MarketplaceAuditEntry, _ as MarketplaceAuditPort, $ as MarketplaceAuthMode, a0 as MarketplaceCataloguePort, a1 as MarketplaceClockPort, a2 as MarketplaceDb, a3 as MarketplaceEngine, a4 as MarketplaceEngineConfig, a5 as MarketplaceEnqueuePort, a6 as MarketplaceIntegrationView, a7 as MarketplaceLifecycleAnswer, a8 as MarketplaceLifecycleFacts, a9 as MarketplaceLogger, aa as MarketplaceMenuLinkView, ab as MarketplaceOrderPort, ac as MarketplaceOrderState, ad as MarketplaceOrderSummary, ae as MarketplacePorts, af as MarketplaceRefusal, ag as MarketplaceSecretsPort, ah as MenuLinkRowInput, ai as OUTBOUND_GIVE_UP_MS, aj as OUTBOUND_STALE_MS, ak as OutboundAction, al as OutboundAttempt, am as OutboundJobPayload, an as OutboundOutcome, ao as OutboundRetryError, ap as OutboundSweepResult, aq as PauseOutcome, ar as PauseStoreInput, as as PauseStoreResult, at as PendingAcceptance, au as PendingInboxEvent, av as ResolvedOrderLine, aw as ResumeOutcome, ax as STORE_PAUSE_LEASE_MS, ay as SaveMarketplaceIntegrationInput, az as StoreAvailabilityView, aA as StorePauseFailureCode, aB as StorePauseState, aC as StorePauseWanted, aD as availabilityDedupeKey, aE as catalogueDedupeKey, aF as createMarketplaceEngine, aG as outboundDedupeKey } from './engine-CIy9P7Cq.js';
2
- import { c as MarketplaceAdapter, l as MarketplaceProvider, m as CancellationReason } from './adapter-nUyZpLzz.js';
3
- export { A as AdapterCallContext, n as AdapterGrant, o as AdapterTokenCache, p as CancellationOutcome, q as CancellationRequestInput, r as CatalogueCallContext, s as CatalogueFailure, t as CatalogueImage, u as CatalogueItem, e as CatalogueItemOut, v as CatalogueItemRef, C as CatalogueMenuEntry, b as CatalogueMenuOptions, w as CataloguePublishResult, x as CatalogueReadContext, y as CatalogueReadNotice, z as CatalogueReadRefusalCode, B as CatalogueReadResult, D as CatalogueReadWarning, E as CatalogueReadWarningCode, f as CatalogueReader, F as CatalogueSnapshot, G as CatalogueSnapshotCategory, H as CatalogueSnapshotItem, I as CatalogueSnapshotOption, J as CatalogueSnapshotOptionGroup, K as CatalogueStoredImage, L as CatalogueWarningCode, Q as CourierTrackingCallResult, R as CourierTrackingResult, T as FetchOrderResult, U as LinkCallContext, V as LinkCode, W as LinkGrant, X as LinkResult, Y as LinkedMerchant, Z as MarketplaceAppCredentialsPort, M as MarketplaceAvailability, _ as MarketplaceCapabilities, $ as MarketplaceCatalogue, a0 as MarketplaceCourier, a1 as MarketplaceCourierAnswer, h as MarketplaceCourierApi, a2 as MarketplaceCourierEngine, a3 as MarketplaceCourierFacts, a4 as MarketplaceCourierStep, a5 as MarketplaceCourierTracking, a6 as MarketplaceCourierVehicle, a7 as MarketplaceCredentials, a8 as MarketplaceDeliveredBy, a9 as MarketplaceDiscountSponsor, aa as MarketplaceHttp, ab as MarketplaceHttpRequest, ac as MarketplaceHttpResponse, ad as MarketplaceLifecycle, ae as MarketplaceLinkAttemptDelegate, g as MarketplaceLinking, af as MarketplaceOrderType, ag as NormalizedAddress, ah as NormalizedBuyer, i as NormalizedCourierEvent, N as NormalizedEvent, a as NormalizedMarketplaceOrder, ai as NormalizedOrderDiscount, aj as NormalizedOrderLine, ak as OutboundOrderRef, O as OutboundResult, al as PROVIDER_ID_PATTERN, am as PickupCodeCallResult, an as PickupCodeValidation, P as PullCatalogue, d as PushCatalogue, ao as StatusFacts, ap as StatusStep, k as StorePauseRef, S as StorePauseRequest, j as StorePauseResult, aq as ValidatePickupCodeInput, ar as answered, as as centsFromMajor, at as outboundResultOf, au as tokenGrantResultOf } from './adapter-nUyZpLzz.js';
1
+ export { A as AcceptanceDecision, a as AcceptanceStatus, b as AvailabilityJobPayload, c as AvailabilityOutcome, d as AvailabilityRetryError, e as AvailabilitySweepResult, B as BulkProblem, f as BulkProblemCode, g as BulkResult, C as CancellationFailureReason, h as CancellationStatus, i as CatalogueAction, j as CatalogueActionResult, k as CatalogueDocumentResult, l as CatalogueFailedAction, m as CatalogueFailureCode, n as CatalogueJobPayload, o as CatalogueOutcome, p as CataloguePublicationView, q as CataloguePublishInput, r as CatalogueRefusalCode, s as CatalogueRetryError, t as CatalogueStatus, u as CatalogueTarget, D as DecideManyResult, v as DecidedRow, w as DecisionInput, x as DecisionProblem, y as DecisionProblemCode, z as DecisionResult, E as DeliveryOutcome, F as ExpirySweepResult, G as FetchOrderJobPayload, H as FetchOrderOutcome, I as FetchOrderRetryError, J as InformStatusInput, K as IngestResult, L as IngestSettings, M as IngestionTarget, N as IntegrationRowInput, O as LinkFailure, P as LinkFinished, Q as LinkPendingView, R as LinkRefusalCode, S as MARKETPLACE_AVAILABILITY_JOB, T as MARKETPLACE_CATALOGUE_JOB, U as MARKETPLACE_FETCH_ORDER_JOB, V as MARKETPLACE_OUTBOUND_JOB, W as MarketplaceAdmission, X as MarketplaceAdmissionRequest, Y as MarketplaceAdmissionResult, Z as MarketplaceAuditEntry, _ as MarketplaceAuditPort, $ as MarketplaceAuthMode, a0 as MarketplaceCataloguePort, a1 as MarketplaceClockPort, a2 as MarketplaceDb, a3 as MarketplaceEngine, a4 as MarketplaceEngineConfig, a5 as MarketplaceEnqueuePort, a6 as MarketplaceIntegrationView, a7 as MarketplaceLifecycleAnswer, a8 as MarketplaceLifecycleFacts, a9 as MarketplaceLogger, aa as MarketplaceMenuLinkView, ab as MarketplaceOrderPort, ac as MarketplaceOrderState, ad as MarketplaceOrderSummary, ae as MarketplacePorts, af as MarketplaceRefusal, ag as MarketplaceSecretsPort, ah as MenuLinkRowInput, ai as OUTBOUND_GIVE_UP_MS, aj as OUTBOUND_STALE_MS, ak as OutboundAction, al as OutboundAttempt, am as OutboundJobPayload, an as OutboundOutcome, ao as OutboundRetryError, ap as OutboundSweepResult, aq as PauseOutcome, ar as PauseStoreInput, as as PauseStoreResult, at as PendingAcceptance, au as PendingInboxEvent, av as ResolvedOrderLine, aw as ResumeOutcome, ax as STORE_PAUSE_LEASE_MS, ay as SaveMarketplaceIntegrationInput, az as StoreAvailabilityView, aA as StorePauseFailureCode, aB as StorePauseState, aC as StorePauseWanted, aD as availabilityDedupeKey, aE as catalogueDedupeKey, aF as createMarketplaceEngine, aG as outboundDedupeKey } from './engine-1KlJ_8jK.js';
2
+ import { c as MarketplaceAdapter, l as MarketplaceProvider, m as CancellationReason } from './adapter-CQ4QiZPi.js';
3
+ export { A as AdapterCallContext, n as AdapterGrant, o as AdapterTokenCache, p as CancellationOutcome, q as CancellationRequestInput, r as CatalogueCallContext, s as CatalogueFailure, t as CatalogueImage, u as CatalogueItem, e as CatalogueItemOut, v as CatalogueItemRef, C as CatalogueMenuEntry, b as CatalogueMenuOptions, w as CataloguePublishResult, x as CatalogueReadContext, y as CatalogueReadNotice, z as CatalogueReadRefusalCode, B as CatalogueReadResult, D as CatalogueReadWarning, E as CatalogueReadWarningCode, f as CatalogueReader, G as CatalogueSnapshot, H as CatalogueSnapshotCategory, I as CatalogueSnapshotItem, J as CatalogueSnapshotOption, K as CatalogueSnapshotOptionGroup, L as CatalogueStoredImage, Q as CatalogueWarningCode, R as CourierTrackingCallResult, T as CourierTrackingResult, F as FetchOrderResult, U as LinkCallContext, V as LinkCode, W as LinkGrant, X as LinkResult, Y as LinkedMerchant, Z as MarketplaceAppCredentialsPort, M as MarketplaceAvailability, _ as MarketplaceCapabilities, $ as MarketplaceCatalogue, a0 as MarketplaceCourier, a1 as MarketplaceCourierAnswer, h as MarketplaceCourierApi, a2 as MarketplaceCourierEngine, a3 as MarketplaceCourierFacts, a4 as MarketplaceCourierStep, a5 as MarketplaceCourierTracking, a6 as MarketplaceCourierVehicle, a7 as MarketplaceCredentials, a8 as MarketplaceDeliveredBy, a9 as MarketplaceDiscountSponsor, aa as MarketplaceHttp, ab as MarketplaceHttpRequest, ac as MarketplaceHttpResponse, ad as MarketplaceLifecycle, ae as MarketplaceLinkAttemptDelegate, g as MarketplaceLinking, af as MarketplaceOrderType, ag as NormalizedAddress, ah as NormalizedBuyer, i as NormalizedCourierEvent, N as NormalizedEvent, a as NormalizedMarketplaceOrder, ai as NormalizedOrderDiscount, aj as NormalizedOrderLine, ak as OutboundOrderRef, O as OutboundResult, al as PROVIDER_ID_PATTERN, am as PickupCodeCallResult, an as PickupCodeValidation, P as PullCatalogue, d as PushCatalogue, ao as StatusFacts, ap as StatusStep, k as StorePauseRef, S as StorePauseRequest, j as StorePauseResult, aq as ValidatePickupCodeInput, ar as answered, as as centsFromMajor, at as outboundResultOf, au as tokenGrantResultOf } from './adapter-CQ4QiZPi.js';
4
4
 
5
5
  /**
6
6
  * The adapter registry: the ONE place a provider id becomes a marketplace.
package/dist/index.js CHANGED
@@ -81,7 +81,7 @@ import {
81
81
  upsertLink,
82
82
  validatePickupCode,
83
83
  viewOf
84
- } from "./chunk-45ZVN5XI.js";
84
+ } from "./chunk-CEWTV2TC.js";
85
85
  import {
86
86
  centsFromMajor
87
87
  } from "./chunk-WN2EK4KX.js";
@@ -92,7 +92,7 @@ import {
92
92
  answered,
93
93
  outboundResultOf,
94
94
  tokenGrantResultOf
95
- } from "./chunk-LACBT6NC.js";
95
+ } from "./chunk-4J2KJ3ZW.js";
96
96
  import {
97
97
  __name
98
98
  } from "./chunk-7QVYU63E.js";
@@ -1,5 +1,5 @@
1
- import { A as AdapterCallContext, N as NormalizedEvent, a as NormalizedMarketplaceOrder, c as MarketplaceAdapter } from '../adapter-nUyZpLzz.js';
2
- import { a as OpenDeliveryStop, O as OpenDeliveryApiBaseUrls } from '../client-Ctas7WCS.js';
1
+ import { A as AdapterCallContext, N as NormalizedEvent, a as NormalizedMarketplaceOrder, c as MarketplaceAdapter } from '../adapter-CQ4QiZPi.js';
2
+ import { a as OpenDeliveryStop, O as OpenDeliveryApiBaseUrls } from '../client-CCSnylou.js';
3
3
 
4
4
  /**
5
5
  * Keeta's MERCHANT AUTHORIZATION, automated from the software (Keeta's
@@ -13,7 +13,7 @@ import {
13
13
  openDeliveryRequestCancellation,
14
14
  openDeliveryStatus,
15
15
  openDeliverySwitchAvailability
16
- } from "../chunk-L6FG6T4S.js";
16
+ } from "../chunk-NFJQQWG4.js";
17
17
  import "../chunk-M2V4RFMA.js";
18
18
  import {
19
19
  asString,
@@ -23,7 +23,7 @@ import {
23
23
  } from "../chunk-BD7DS3XM.js";
24
24
  import {
25
25
  outboundResultOf
26
- } from "../chunk-LACBT6NC.js";
26
+ } from "../chunk-4J2KJ3ZW.js";
27
27
  import {
28
28
  __name
29
29
  } from "../chunk-7QVYU63E.js";
@@ -1,7 +1,7 @@
1
- import { am as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-CIy9P7Cq.js';
1
+ import { am as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-1KlJ_8jK.js';
2
2
  import * as _12_apps_wiring from '@12-apps/wiring';
3
3
  import { createApiMarketplace, MarketplaceJobDeps } from '../server/index.js';
4
- import '../adapter-nUyZpLzz.js';
4
+ import '../adapter-CQ4QiZPi.js';
5
5
  import 'zod';
6
6
 
7
7
  declare const marketplaceServerManifest: {
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  MARKETPLACE_JOBS,
3
3
  createApiMarketplace
4
- } from "../chunk-MIPNQ7X5.js";
4
+ } from "../chunk-W57TITU4.js";
5
5
  import "../chunk-SGOTN5PX.js";
6
- import "../chunk-45ZVN5XI.js";
6
+ import "../chunk-CEWTV2TC.js";
7
7
  import "../chunk-7QVYU63E.js";
8
8
 
9
9
  // src/manifest/server.ts
@@ -1,4 +1,4 @@
1
- import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-nUyZpLzz.js';
1
+ import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CQ4QiZPi.js';
2
2
 
3
3
  /**
4
4
  * The words the Rappi adapter needs from its host, and nothing else.
@@ -9,7 +9,7 @@ import {
9
9
  answered,
10
10
  outboundResultOf,
11
11
  tokenGrantResultOf
12
- } from "../chunk-LACBT6NC.js";
12
+ } from "../chunk-4J2KJ3ZW.js";
13
13
  import {
14
14
  __name
15
15
  } from "../chunk-7QVYU63E.js";
@@ -1,7 +1,7 @@
1
- import { y as DecisionProblemCode, f as BulkProblemCode, R as LinkRefusalCode, a3 as MarketplaceEngine, a9 as MarketplaceLogger, am as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-CIy9P7Cq.js';
1
+ import { y as DecisionProblemCode, f as BulkProblemCode, R as LinkRefusalCode, a3 as MarketplaceEngine, a9 as MarketplaceLogger, am as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-1KlJ_8jK.js';
2
2
  import { WireRoute, WireJobBlueprint } from '@12-apps/wiring';
3
3
  import { z } from 'zod';
4
- import '../adapter-nUyZpLzz.js';
4
+ import '../adapter-CQ4QiZPi.js';
5
5
 
6
6
  /**
7
7
  * Every problem code a route words from `problems`, decisions and bulk writes
@@ -6,7 +6,7 @@ import {
6
6
  MARKETPLACE_SWEEP_QUEUE,
7
7
  ORDER_NOT_PENDING_CODE,
8
8
  createApiMarketplace
9
- } from "../chunk-MIPNQ7X5.js";
9
+ } from "../chunk-W57TITU4.js";
10
10
  import {
11
11
  MARKETPLACE_DECIDE,
12
12
  MARKETPLACE_MANAGE,
@@ -20,7 +20,7 @@ import {
20
20
  upsertMarketplaceIntegrationsBody,
21
21
  upsertMarketplaceMenuLinksBody
22
22
  } from "../chunk-SGOTN5PX.js";
23
- import "../chunk-45ZVN5XI.js";
23
+ import "../chunk-CEWTV2TC.js";
24
24
  import "../chunk-7QVYU63E.js";
25
25
  export {
26
26
  MARKETPLACE_AVAILABILITY_ATTEMPTS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/marketplace",
3
- "version": "1.12.0",
3
+ "version": "1.13.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "One marketplace integration engine for every marketplace: the durable inbox, the ingest pipeline, the acceptance clock and its sweep, the SKU map, the integration settings with sealed credentials, and the outbound engine (confirm, cancellation request, retries), behind an adapter port. Each marketplace is an adapter at its own subpath (./ifood, ./99food and ./keeta on Open Delivery, ./rappi). Framework-neutral wiring route descriptors (./server) with a Hono adapter (./hono), dep-free job blueprints, MCP tools and the package-owned Prisma partial + migrations.",
@@ -237,7 +237,8 @@ export interface MarketplaceAdapter {
237
237
  * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a
238
238
  * marketplace whose events carry no order body). Called only from the
239
239
  * `marketplace.fetch-order` job. An adapter whose events always carry the
240
- * order (iFood) leaves it out.
240
+ * order leaves it out. A final `refused` marked `own` with a 4xx status is
241
+ * our credentials refused: the engine stamps the connection FAILED.
241
242
  */
242
243
  fetchOrder?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<FetchOrderResult>;
243
244
  /**
@@ -0,0 +1,61 @@
1
+ import type { EngineContext } from "./ports";
2
+ import type { MarketplaceProvider } from "./types";
3
+
4
+ /**
5
+ * What a call no person made says about a connection's credentials (the order
6
+ * fetch, FUT-5800): refused, or working again. Each stamp is guarded on the
7
+ * sealed credentials the call was made with, as `./link-store.ts`'s
8
+ * `markLinkFailed` is, so a call made with credentials since replaced never
9
+ * judges the new ones.
10
+ */
11
+
12
+ /**
13
+ * The marketplace refused this connection's credentials on a call no person
14
+ * made (the order fetch, FUT-5800): the connection reads FAILED, which is what
15
+ * the connections screen shows, and the staff surfaces are told. Only the
16
+ * credentials the call was made with (`sealed`) are judged: a store that
17
+ * entered new ones meanwhile is left alone. Re-entering the credentials resets
18
+ * it to UNVERIFIED; the next fetch that succeeds, to VERIFIED
19
+ * ({@link markCredentialsAccepted}). Best-effort: never throws.
20
+ */
21
+ export async function markCredentialsRefused(
22
+ ctx: EngineContext,
23
+ input: { clientId: string; provider: MarketplaceProvider; sealed: string },
24
+ ): Promise<void> {
25
+ await stampConnection(ctx, input, { archivedAt: null }, { status: "FAILED" });
26
+ }
27
+
28
+ /**
29
+ * A call with these credentials (`sealed`) succeeded: a connection that read
30
+ * FAILED for them reads VERIFIED again. Any other status is left as it is.
31
+ * Best-effort: never throws.
32
+ */
33
+ export async function markCredentialsAccepted(
34
+ ctx: EngineContext,
35
+ input: { clientId: string; provider: MarketplaceProvider; sealed: string },
36
+ ): Promise<void> {
37
+ await stampConnection(ctx, input, { status: "FAILED" }, { status: "VERIFIED", lastVerifiedAt: ctx.ports.clock.now() });
38
+ }
39
+
40
+ /** One guarded status write on the connection the call was made with; tells the staff surfaces when it moved. */
41
+ async function stampConnection(
42
+ ctx: EngineContext,
43
+ input: { clientId: string; provider: MarketplaceProvider; sealed: string },
44
+ where: Record<string, unknown>,
45
+ data: Record<string, unknown>,
46
+ ): Promise<void> {
47
+ const { clientId, provider, sealed } = input;
48
+ try {
49
+ const db = await ctx.ports.db();
50
+ const { count } = await db.marketplaceIntegration.updateMany({
51
+ where: { clientId, provider, credentials: sealed, ...where },
52
+ data,
53
+ });
54
+ if (count > 0) ctx.ports.publishChanged(clientId);
55
+ } catch (error) {
56
+ ctx.ports.logger.error(
57
+ `marketplace: ${provider} connection of ${clientId} not stamped ${String(data.status)}: ` +
58
+ (error instanceof Error ? error.message : String(error)),
59
+ );
60
+ }
61
+ }
@@ -1,6 +1,7 @@
1
1
  import { deferInboxEvent, settleInboxEvent } from "./inbox";
2
2
  import { ingestMarketplaceOrder } from "./ingest";
3
- import { readOutboundConnection, resolveIngestionTarget } from "./integration";
3
+ import { markCredentialsAccepted, markCredentialsRefused } from "./connection-stamp";
4
+ import { readSealedOutboundConnection, resolveIngestionTarget } from "./integration";
4
5
  import type { FetchOrderResult } from "./adapter";
5
6
  import { cancelAcceptance } from "./acceptance";
6
7
  import { CANCELLED_BEFORE_INGEST_REASON, cancelledBeforeIngest } from "./order-fetch-marks";
@@ -131,30 +132,37 @@ async function owedFetch(
131
132
  return { row, event };
132
133
  }
133
134
 
135
+ /** What one call to the adapter answered, and the sealed credentials it was made with (null: no call). */
136
+ interface AdapterFetch {
137
+ result: FetchOrderResult;
138
+ sealed: string | null;
139
+ }
140
+
134
141
  /** One call to the adapter, or the refusal that stands in for it. */
135
142
  async function fetchThroughAdapter(
136
143
  ctx: EngineContext,
137
144
  clientId: string,
138
145
  provider: MarketplaceProvider,
139
146
  externalOrderId: string,
140
- ): Promise<FetchOrderResult> {
147
+ ): Promise<AdapterFetch> {
141
148
  const adapter = ctx.registry.get(provider);
142
- if (!adapter?.fetchOrder) return { kind: "refused", status: 0, message: `${provider} cannot fetch an order` };
143
- let connection;
149
+ if (!adapter?.fetchOrder) return { result: { kind: "refused", status: 0, message: `${provider} cannot fetch an order` }, sealed: null };
150
+ let opened;
144
151
  try {
145
- connection = await readOutboundConnection(ctx, clientId, provider);
152
+ opened = await readSealedOutboundConnection(ctx, clientId, provider);
146
153
  } catch (error) {
147
154
  const reason = error instanceof Error ? error.message : String(error);
148
- return { kind: "refused", status: 0, message: `credentials do not open: ${reason}` };
155
+ return { result: { kind: "refused", status: 0, message: `credentials do not open: ${reason}` }, sealed: null };
149
156
  }
150
- if (!connection) return { kind: "refused", status: 0, message: "no credentials on file" };
157
+ if (!opened) return { result: { kind: "refused", status: 0, message: "no credentials on file" }, sealed: null };
151
158
  try {
152
- return await adapter.fetchOrder(
153
- { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
159
+ const result = await adapter.fetchOrder(
160
+ { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...opened.connection },
154
161
  { externalOrderId },
155
162
  );
163
+ return { result, sealed: opened.sealed };
156
164
  } catch (error) {
157
- return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
165
+ return { result: { kind: "retry", reason: error instanceof Error ? error.message : String(error) }, sealed: opened.sealed };
158
166
  }
159
167
  }
160
168
 
@@ -222,6 +230,11 @@ async function ingestFetched(
222
230
  return { kind: "ingested", orderId: ingested.orderId, unmappedSkus: ingested.unmappedSkus };
223
231
  }
224
232
 
233
+ /** A final refusal of our own credentials by the marketplace (a 4xx, not a local "no credentials"). */
234
+ function credentialsRefused(result: FetchOrderResult): boolean {
235
+ return result.kind === "refused" && result.own === true && result.status >= 400 && result.status < 500;
236
+ }
237
+
225
238
  /**
226
239
  * Run one queued fetch. Returns what it did; throws {@link FetchOrderRetryError}
227
240
  * for an answer worth retrying before the last attempt. A refusal, or the last
@@ -241,12 +254,41 @@ export async function runFetchOrder(
241
254
  await deferInboxEvent(ctx, row.id, "integration is not enabled");
242
255
  return { kind: "skipped", reason: "integration is not enabled" };
243
256
  }
244
- const result = await fetchThroughAdapter(ctx, payload.clientId, event.provider, event.externalOrderId ?? "");
245
- if (result.kind === "order") return ingestFetched(ctx, row, payload.clientId, result.order, target);
257
+ const { result, sealed } = await fetchThroughAdapter(ctx, payload.clientId, event.provider, event.externalOrderId ?? "");
258
+ const stamp = sealed === null ? null : { clientId: payload.clientId, provider: event.provider, sealed };
259
+ if (result.kind === "order") {
260
+ // The credentials worked: a FAILED stamp left by an earlier refusal of these same ones is lifted.
261
+ if (stamp) await markCredentialsAccepted(ctx, stamp);
262
+ return ingestFetched(ctx, row, payload.clientId, result.order, target);
263
+ }
264
+ return endUnfetched(ctx, { row, event, result, attempt, stamp });
265
+ }
266
+
267
+ /**
268
+ * A fetch that brought no order: rethrown for the queue while a retry is worth
269
+ * it, else the row settles FAILED. Our credentials refused (a 401 that a fresh
270
+ * token did not cure, a refused token grant) are never retried by the queue:
271
+ * the connection reads FAILED, and the reconciliation sweep's next pass,
272
+ * minutes away and within the row's attempt bound, is the only re-try, so a
273
+ * revoked app never loops.
274
+ */
275
+ async function endUnfetched(
276
+ ctx: EngineContext,
277
+ input: {
278
+ row: InboxRow;
279
+ event: NormalizedEvent;
280
+ result: Exclude<FetchOrderResult, { kind: "order" }>;
281
+ attempt: { attempt: number; maxAttempts: number };
282
+ /** The connection and the sealed credentials the call was made with; null when no call was made. */
283
+ stamp: { clientId: string; provider: MarketplaceProvider; sealed: string } | null;
284
+ },
285
+ ): Promise<FetchOrderOutcome> {
286
+ const { row, event, result, attempt } = input;
246
287
  const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
247
288
  if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
248
289
  throw new FetchOrderRetryError(`fetch of ${event.externalOrderId ?? "?"} (inbox ${row.id}): ${reason}`);
249
290
  }
291
+ if (input.stamp && credentialsRefused(result)) await markCredentialsRefused(ctx, input.stamp);
250
292
  await settleInboxEvent(ctx, row.id, "FAILED", `order fetch failed: ${reason}`);
251
293
  ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} failed: ${reason}`);
252
294
  return { kind: "failed", reason };
@@ -357,18 +357,33 @@ export async function readOutboundConnection(
357
357
  clientId: string,
358
358
  provider: MarketplaceProvider,
359
359
  ): Promise<OutboundConnection | null> {
360
+ return (await readSealedOutboundConnection(ctx, clientId, provider))?.connection ?? null;
361
+ }
362
+
363
+ /**
364
+ * {@link readOutboundConnection}, with the sealed blob it was opened from: a
365
+ * caller that stamps the connection afterwards (`./fetch-order.ts`) guards
366
+ * the stamp on it, so a call made with credentials since replaced never
367
+ * judges the new ones. The blob never reaches an adapter.
368
+ */
369
+ export async function readSealedOutboundConnection(
370
+ ctx: EngineContext,
371
+ clientId: string,
372
+ provider: MarketplaceProvider,
373
+ ): Promise<{ connection: OutboundConnection; sealed: string } | null> {
360
374
  const db = await ctx.ports.db();
361
375
  const row = (await db.marketplaceIntegration.findUnique({
362
376
  where: { clientId_provider: { clientId, provider } },
363
377
  select: { environment: true, credentials: true, authMode: true },
364
378
  })) as { environment: string; credentials: string; authMode?: string } | null;
365
379
  if (!row || row.credentials === "") return null;
380
+ const sealed = row.credentials;
366
381
  const environment = environmentOf(row.environment);
367
- if (row.authMode !== "LINKED") return { environment, credentials: openCredentials(ctx, row.credentials) };
382
+ if (row.authMode !== "LINKED") return { connection: { environment, credentials: openCredentials(ctx, sealed) }, sealed };
368
383
  // Linked: the software's app speaks for the store, with the store's refresh token.
369
384
  const app = await appCredentialsOf(ctx, provider, environment);
370
385
  if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
371
- const refreshToken = openLinkRefreshToken(ctx, row.credentials);
372
- const link = { clientId, provider, environment, refreshToken, app, sealed: row.credentials };
373
- return { environment, credentials: app, grant: linkGrant(ctx, link) };
386
+ const refreshToken = openLinkRefreshToken(ctx, sealed);
387
+ const link = { clientId, provider, environment, refreshToken, app, sealed };
388
+ return { connection: { environment, credentials: app, grant: linkGrant(ctx, link) }, sealed };
374
389
  }
@@ -0,0 +1,103 @@
1
+ import {
2
+ outboundResultOf,
3
+ type AdapterCallContext,
4
+ type FetchOrderResult,
5
+ type MarketplaceHttpResponse,
6
+ } from "../core/adapter";
7
+ import { firstString } from "../core/payload-read";
8
+ import { readIfoodOrder } from "./normalize";
9
+ import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
10
+
11
+ /**
12
+ * The iFood adapter's order read (FUT-5800): `GET /order/v1.0/orders/{id}`.
13
+ *
14
+ * iFood's events carry only the order id, so a PLACED with no items is marked
15
+ * `orderToFetch` (`./normalize.ts`) and the engine's `marketplace.fetch-order`
16
+ * job calls this, after the webhook's row is committed, never inside the
17
+ * request. The order iFood serves has the fields the event's `order` would
18
+ * have carried, so it is normalized by the same reader: a fetched order and a
19
+ * carried one land identically.
20
+ *
21
+ * How an answer is read:
22
+ * - 2xx with an order: the order, with the merchant its `merchant.id` names
23
+ * (the engine refuses one naming another merchant than the connection's).
24
+ * - 2xx that is not JSON: retried. 2xx naming another order, or no items: refused.
25
+ * - 401: the cached token is forgotten and a new one asked for, ONCE, in the
26
+ * same call. A second 401 is our credentials refused (`own`), as is a 403
27
+ * (the merchant has not authorized this app) and a token grant iFood refuses.
28
+ * - 404: retried. ESTIMATED: an order read right after its PLACED may not be
29
+ * served yet; the job's attempt bound ends it.
30
+ * - Everything else: the engine's one rule (`outboundResultOf`).
31
+ */
32
+
33
+ const orderResourceUrl = (externalOrderId: string): string =>
34
+ `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}`;
35
+
36
+ /** One authenticated GET, or the token's refusal or retry in its place. */
37
+ async function getOrder(
38
+ ctx: AdapterCallContext,
39
+ externalOrderId: string,
40
+ ): Promise<{ response: MarketplaceHttpResponse } | Exclude<FetchOrderResult, { kind: "order" }>> {
41
+ const auth = await bearer(ctx);
42
+ if (!("token" in auth)) {
43
+ return auth.kind === "accepted" ? { kind: "retry", reason: "iFood answered the token grant without a token" } : auth;
44
+ }
45
+ const response = await ctx.http({
46
+ method: "GET",
47
+ url: orderResourceUrl(externalOrderId),
48
+ headers: { Authorization: `Bearer ${auth.token}`, Accept: "application/json" },
49
+ });
50
+ return { response };
51
+ }
52
+
53
+ /** The order in a 2xx answer, or why it is not one. */
54
+ function orderOf(body: string, externalOrderId: string, missingStreetNumber: string): FetchOrderResult {
55
+ let parsed: unknown;
56
+ try {
57
+ parsed = JSON.parse(body) as unknown;
58
+ } catch {
59
+ return { kind: "retry", reason: "iFood answered the order read with a body that is not JSON" };
60
+ }
61
+ const named = firstString(parsed, [["id"]]);
62
+ if (named !== null && named !== externalOrderId) {
63
+ return { kind: "refused", status: 200, message: `iFood answered order ${named} for ${externalOrderId}` };
64
+ }
65
+ const order = readIfoodOrder(parsed, externalOrderId, missingStreetNumber);
66
+ if (!order) return { kind: "refused", status: 200, message: "iFood answered an order with no items" };
67
+ return { kind: "order", order: { ...order, externalMerchantId: firstString(parsed, [["merchant", "id"]]) } };
68
+ }
69
+
70
+ /** What a non-2xx answer means for the fetch. */
71
+ function failureOf(response: MarketplaceHttpResponse): Exclude<FetchOrderResult, { kind: "order" }> {
72
+ const message = response.body.slice(0, 300);
73
+ if (response.status === 401 || response.status === 403) {
74
+ return { kind: "refused", status: response.status, message, own: true };
75
+ }
76
+ if (response.status === 404) return { kind: "retry", reason: `status 404: ${message}` };
77
+ const result = outboundResultOf(response);
78
+ return result.kind === "accepted" ? { kind: "retry", reason: `status ${response.status}` } : result;
79
+ }
80
+
81
+ /** Fetch one order iFood's event only named. Never throws: no answer is a retry. */
82
+ export async function ifoodFetchOrder(
83
+ ctx: AdapterCallContext,
84
+ ref: { externalOrderId: string },
85
+ options: { missingStreetNumber: string },
86
+ ): Promise<FetchOrderResult> {
87
+ try {
88
+ let answer = await getOrder(ctx, ref.externalOrderId);
89
+ if ("response" in answer && answer.response.status === 401) {
90
+ // A token that went stale under us: forget it and try once with a new one.
91
+ ctx.tokens.delete(ifoodTokenKey(ctx));
92
+ answer = await getOrder(ctx, ref.externalOrderId);
93
+ }
94
+ if (!("response" in answer)) return answer;
95
+ const { response } = answer;
96
+ if (response.status >= 200 && response.status < 300) {
97
+ return orderOf(response.body, ref.externalOrderId, options.missingStreetNumber);
98
+ }
99
+ return failureOf(response);
100
+ } catch (error) {
101
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
102
+ }
103
+ }
@@ -3,6 +3,7 @@ import { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from
3
3
  import { IFOOD_CATALOGUE } from "./catalogue";
4
4
  import { IFOOD_CATALOGUE_READER } from "./catalogue-read";
5
5
  import { IFOOD_COURIER } from "./courier";
6
+ import { ifoodFetchOrder } from "./fetch-order";
6
7
  import { IFOOD_LINKING } from "./linking";
7
8
  import { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
8
9
  import { IFOOD_PORTAL_URL, ifoodConfirm, ifoodInformStatus, ifoodRequestCancellation, ifoodStatusSupported } from "./outbound";
@@ -77,6 +78,8 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
77
78
  catalogueReader: IFOOD_CATALOGUE_READER,
78
79
  confirm: (ctx, order) => ifoodConfirm(ctx, order),
79
80
  requestCancellation: ifoodRequestCancellation,
81
+ // iFood's events carry only the order id: a PLACED with no items is fetched (FUT-5800).
82
+ fetchOrder: (ctx, order) => ifoodFetchOrder(ctx, order, normalizeOptions),
80
83
  statusSupported: ifoodStatusSupported,
81
84
  informStatus: ifoodInformStatus,
82
85
  // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
@@ -92,7 +95,8 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
92
95
  }
93
96
 
94
97
  export { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from "./copy";
95
- export { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
98
+ export { normalizeIfoodEvent, readIfoodOrder, verifyIfoodSignature } from "./normalize";
99
+ export { ifoodFetchOrder } from "./fetch-order";
96
100
  export { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from "./catalogue";
97
101
  export { IFOOD_CATALOGUE_READER } from "./catalogue-read";
98
102
  export { IFOOD_LINKING } from "./linking";
@@ -202,8 +202,12 @@ function optional<K extends string, V>(key: K, value: V | undefined): { [P in K]
202
202
  return value === undefined ? {} : ({ [key]: value } as { [P in K]?: V });
203
203
  }
204
204
 
205
- /** The order body of a placed-order event, or null when it carries none. */
206
- function readOrder(
205
+ /**
206
+ * The order body of a placed-order event, or null when it carries none. Also
207
+ * reads the order iFood serves at `GET /order/v1.0/orders/{id}` (`./fetch-order.ts`),
208
+ * whose fields are the same ones the event's `order` would carry.
209
+ */
210
+ export function readIfoodOrder(
207
211
  payload: unknown,
208
212
  externalOrderId: string,
209
213
  missingStreetNumber: string,
@@ -246,6 +250,22 @@ function readOrder(
246
250
  };
247
251
  }
248
252
 
253
+ /**
254
+ * The order a PLACED carries, or, when it carries none, the mark that has it
255
+ * fetched: iFood's events carry only the order id (sandbox, 2026-11-27), so the
256
+ * `marketplace.fetch-order` job reads it (FUT-5800). Any other event: no order.
257
+ */
258
+ function placedOrder(
259
+ payload: unknown,
260
+ placed: boolean,
261
+ externalOrderId: string,
262
+ missingStreetNumber: string,
263
+ ): Pick<NormalizedEvent, "order" | "orderToFetch"> {
264
+ if (!placed) return { order: null };
265
+ const order = readIfoodOrder(payload, externalOrderId, missingStreetNumber);
266
+ return order ? { order } : { order: null, orderToFetch: true };
267
+ }
268
+
249
269
  /**
250
270
  * Normalize one iFood delivery.
251
271
  *
@@ -276,7 +296,7 @@ export function normalizeIfoodEvent(
276
296
  eventType,
277
297
  externalMerchantId: firstString(payload, [["merchantId"], ["merchant", "id"]]),
278
298
  externalOrderId,
279
- order: placed ? readOrder(payload, externalOrderId, options.missingStreetNumber) : null,
299
+ ...placedOrder(payload, placed, externalOrderId, options.missingStreetNumber),
280
300
  cancelled,
281
301
  cancellationOutcome: cancelled ? "CONFIRMED" : refusedRequest ? "FAILED" : null,
282
302
  ...(LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}),