@12-apps/marketplace 1.19.0 → 1.20.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.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export { A as AcceptanceDecision, a as AcceptanceStatus, b as AcknowledgeJobPayload, c as AcknowledgeOutcome, d as AcknowledgeRetryError, e as AnswerDisputeResult, f as AvailabilityJobPayload, g as AvailabilityOutcome, h as AvailabilityRetryError, i as AvailabilitySweepResult, B as BulkProblem, j as BulkProblemCode, k as BulkResult, C as CancellationFailureReason, l as CancellationReasonsJobPayload, m as CancellationReasonsOutcome, n as CancellationReasonsRetryError, o as CancellationStatus, p as CatalogueAction, q as CatalogueActionResult, r as CatalogueDocumentResult, s as CatalogueFailedAction, t as CatalogueFailureCode, u as CatalogueJobPayload, v as CatalogueOutcome, w as CataloguePublicationView, x as CataloguePublishInput, y as CatalogueRefusalCode, z as CatalogueRetryError, D as CatalogueStatus, E as CatalogueTarget, F as DecideManyResult, G as DecidedRow, H as DecisionInput, I as DecisionProblem, J as DecisionProblemCode, K as DecisionResult, L as DeliveryOutcome, M as DisputeAnswerInput, N as DisputeAnswerJobPayload, O as DisputeAnswerOutcome, P as DisputeAnswerRetryError, Q as DisputeAnswerView, R as DisputeRefusalCode, S as DisputeRow, T as DisputeStatus, U as ExpirySweepResult, V as FetchOrderJobPayload, W as FetchOrderOutcome, X as FetchOrderRetryError, Y as InformStatusInput, Z as IngestResult, _ as IngestSettings, $ as IngestionTarget, a0 as IntegrationRowInput, a1 as LinkFailure, a2 as LinkFinished, a3 as LinkPendingView, a4 as LinkRefusalCode, a5 as LinkTargetOrderPort, a6 as MARKETPLACE_ACKNOWLEDGE_JOB, a7 as MARKETPLACE_AVAILABILITY_JOB, a8 as MARKETPLACE_CANCELLATION_REASONS_JOB, a9 as MARKETPLACE_CATALOGUE_JOB, aa as MARKETPLACE_DISPUTE_ANSWER_JOB, ab as MARKETPLACE_FETCH_ORDER_JOB, ac as MARKETPLACE_OUTBOUND_JOB, ad as MarketplaceAdmission, ae as MarketplaceAdmissionRequest, af as MarketplaceAdmissionResult, ag as MarketplaceAuditEntry, ah as MarketplaceAuditPort, ai as MarketplaceAuthMode, aj as MarketplaceCataloguePort, ak as MarketplaceClockPort, al as MarketplaceConformityEngine, am as MarketplaceDb, an as MarketplaceDeliveryCodeEngine, ao as MarketplaceDisputeEngine, ap as MarketplaceDisputeView, aq as MarketplaceEngine, ar as MarketplaceEngineConfig, as as MarketplaceEnqueuePort, at as MarketplaceIntegrationView, au as MarketplaceLifecycleAnswer, av as MarketplaceLifecycleFacts, aw as MarketplaceLinkTarget, ax as MarketplaceLogger, ay as MarketplaceMenuLinkView, az as MarketplaceOrderPort, aA as MarketplaceOrderState, aB as MarketplaceOrderSummary, aC as MarketplacePorts, aD as MarketplaceRefusal, aE as MarketplaceSecretsPort, aF as MenuLinkRowInput, aG as OUTBOUND_GIVE_UP_MS, aH as OUTBOUND_STALE_MS, aI as OutboundAction, aJ as OutboundAttempt, aK as OutboundJobPayload, aL as OutboundOutcome, aM as OutboundRetryError, aN as OutboundSweepResult, aO as PauseOutcome, aP as PauseStoreInput, aQ as PauseStoreResult, aR as PendingAcceptance, aS as PendingInboxEvent, aT as ResolvedOrderLine, aU as ResumeOutcome, aV as STORE_PAUSE_LEASE_MS, aW as SaveMarketplaceIntegrationInput, aX as StoreAvailabilityView, aY as StorePauseFailureCode, aZ as StorePauseState, a_ as StorePauseWanted, a$ as VerifyDeliveryCodeInput, b0 as availabilityDedupeKey, b1 as catalogueDedupeKey, b2 as createMarketplaceEngine, b3 as disputeView, b4 as outboundDedupeKey } from './engine-CaiVufoP.js';
2
- import { c as MarketplaceAdapter, n as MarketplaceProvider, o as CancellationReason } from './adapter-ZpAWKoCk.js';
3
- export { A as AdapterCallContext, p as AdapterGrant, q as AdapterTokenCache, r as AppLinkCallContext, s as CancellationOutcome, t as CancellationRequestInput, u as CatalogueCallContext, v as CatalogueFailure, w as CatalogueImage, x as CatalogueItem, e as CatalogueItemOut, y as CatalogueItemRef, C as CatalogueMenuEntry, b as CatalogueMenuOptions, z as CataloguePublishResult, B as CatalogueReadContext, D as CatalogueReadNotice, E as CatalogueReadRefusalCode, G as CatalogueReadResult, H as CatalogueReadWarning, I as CatalogueReadWarningCode, f as CatalogueReader, J as CatalogueSnapshot, K as CatalogueSnapshotCategory, L as CatalogueSnapshotItem, Q as CatalogueSnapshotOption, R as CatalogueSnapshotOptionGroup, T as CatalogueStoredImage, U as CatalogueWarningCode, V as CourierTrackingCallResult, W as CourierTrackingResult, X as DeliveryCodeAnswer, Y as DisputeAlternative, Z as DisputeAlternativeType, _ as DisputeAnswer, $ as DisputeAnswerResult, a0 as DisputeFailureCode, a1 as DisputeItem, a2 as DisputeOutcome, a3 as DisputeReason, F as FetchOrderResult, a4 as InformLogisticsInput, a5 as LOGISTICS_STEPS, a6 as LinkCallContext, a7 as LinkCode, a8 as LinkGrant, a9 as LinkResult, aa as LinkedMerchant, ab as LogisticsDriver, ac as LogisticsStep, ad as LogisticsVehicle, ae as MarketplaceAcknowledgement, af as MarketplaceAppCredentialsPort, h as MarketplaceAppLinking, M as MarketplaceAvailability, ag as MarketplaceCapabilities, ah as MarketplaceCatalogue, ai as MarketplaceCourier, aj as MarketplaceCourierAnswer, i as MarketplaceCourierApi, ak as MarketplaceCourierEngine, al as MarketplaceCourierFacts, am as MarketplaceCourierStep, an as MarketplaceCourierTracking, ao as MarketplaceCourierVehicle, ap as MarketplaceCredentials, aq as MarketplaceDeliveredBy, ar as MarketplaceDiscountSponsor, as as MarketplaceDisputeApi, at as MarketplaceDisputeChange, au as MarketplaceDisputeDelegate, av as MarketplaceHttp, aw as MarketplaceHttpRequest, ax as MarketplaceHttpResponse, ay as MarketplaceLifecycle, az as MarketplaceLinkAttemptDelegate, g as MarketplaceLinking, m as MarketplaceLogistics, aA as MarketplaceOrderType, aB as MarketplacePaymentMethod, aC as NormalizedAddress, aD as NormalizedBuyer, j as NormalizedCourierEvent, aE as NormalizedDisputeEvent, aF as NormalizedDisputeOpened, aG as NormalizedDisputeSettled, N as NormalizedEvent, aH as NormalizedLineOption, a as NormalizedMarketplaceOrder, aI as NormalizedOrderDiscount, aJ as NormalizedOrderFee, aK as NormalizedOrderLine, aL as NormalizedPaymentMethod, aM as NormalizedPayments, aN as OrderCancellationReason, aO as OrderCancellationReasonsResult, aP as OutboundOrderRef, O as OutboundResult, aQ as PROVIDER_ID_PATTERN, aR as PickupCodeCallResult, aS as PickupCodeValidation, aT as PresenceProbe, P as PullCatalogue, d as PushCatalogue, aU as StatusFacts, aV as StatusStep, l as StorePauseRef, S as StorePauseRequest, k as StorePauseResult, aW as ValidatePickupCodeInput, aX as answered, aY as centsFromMajor, aZ as normalizedLineTotalCents, a_ as outboundResultOf, a$ as tokenGrantResultOf } from './adapter-ZpAWKoCk.js';
1
+ export { A as AcceptanceDecision, a as AcceptanceStatus, b as AcknowledgeJobPayload, c as AcknowledgeOutcome, d as AcknowledgeRetryError, e as AnswerDisputeResult, f as AvailabilityJobPayload, g as AvailabilityOutcome, h as AvailabilityRetryError, i as AvailabilitySweepResult, B as BulkProblem, j as BulkProblemCode, k as BulkResult, C as CancellationFailureReason, l as CancellationReasonsJobPayload, m as CancellationReasonsOutcome, n as CancellationReasonsRetryError, o as CancellationStatus, p as CatalogueAction, q as CatalogueActionResult, r as CatalogueDocumentResult, s as CatalogueFailedAction, t as CatalogueFailureCode, u as CatalogueJobPayload, v as CatalogueOutcome, w as CataloguePublicationView, x as CataloguePublishInput, y as CatalogueRefusalCode, z as CatalogueRetryError, D as CatalogueStatus, E as CatalogueTarget, F as DecideManyResult, G as DecidedRow, H as DecisionInput, I as DecisionProblem, J as DecisionProblemCode, K as DecisionResult, L as DeliveryOutcome, M as DisputeAnswerInput, N as DisputeAnswerJobPayload, O as DisputeAnswerOutcome, P as DisputeAnswerRetryError, Q as DisputeAnswerView, R as DisputeRefusalCode, S as DisputeRow, T as DisputeStatus, U as ExpirySweepResult, V as FetchOrderJobPayload, W as FetchOrderOutcome, X as FetchOrderRetryError, Y as InformStatusInput, Z as IngestResult, _ as IngestSettings, $ as IngestionTarget, a0 as IntegrationRowInput, a1 as LinkFailure, a2 as LinkFinished, a3 as LinkPendingView, a4 as LinkRefusalCode, a5 as LinkTargetOrderPort, a6 as MARKETPLACE_ACKNOWLEDGE_JOB, a7 as MARKETPLACE_AVAILABILITY_JOB, a8 as MARKETPLACE_CANCELLATION_REASONS_JOB, a9 as MARKETPLACE_CATALOGUE_JOB, aa as MARKETPLACE_DISPUTE_ANSWER_JOB, ab as MARKETPLACE_FETCH_ORDER_JOB, ac as MARKETPLACE_OUTBOUND_JOB, ad as MarketplaceAdmission, ae as MarketplaceAdmissionRequest, af as MarketplaceAdmissionResult, ag as MarketplaceAuditEntry, ah as MarketplaceAuditPort, ai as MarketplaceAuthMode, aj as MarketplaceCataloguePort, ak as MarketplaceClockPort, al as MarketplaceConformityEngine, am as MarketplaceDb, an as MarketplaceDeliveryCodeEngine, ao as MarketplaceDisputeEngine, ap as MarketplaceDisputeView, aq as MarketplaceEngine, ar as MarketplaceEngineConfig, as as MarketplaceEnqueuePort, at as MarketplaceIntegrationView, au as MarketplaceLifecycleAnswer, av as MarketplaceLifecycleFacts, aw as MarketplaceLinkTarget, ax as MarketplaceLogger, ay as MarketplaceMenuLinkView, az as MarketplaceOrderPort, aA as MarketplaceOrderState, aB as MarketplaceOrderSummary, aC as MarketplacePorts, aD as MarketplaceRefusal, aE as MarketplaceSecretsPort, aF as MenuLinkRowInput, aG as OUTBOUND_GIVE_UP_MS, aH as OUTBOUND_STALE_MS, aI as OutboundAction, aJ as OutboundAttempt, aK as OutboundJobPayload, aL as OutboundOutcome, aM as OutboundRetryError, aN as OutboundSweepResult, aO as PauseOutcome, aP as PauseStoreInput, aQ as PauseStoreResult, aR as PendingAcceptance, aS as PendingInboxEvent, aT as ResolvedOrderLine, aU as ResumeOutcome, aV as STORE_PAUSE_LEASE_MS, aW as SaveMarketplaceIntegrationInput, aX as StoreAvailabilityView, aY as StorePauseFailureCode, aZ as StorePauseState, a_ as StorePauseWanted, a$ as VerifyDeliveryCodeInput, b0 as availabilityDedupeKey, b1 as catalogueDedupeKey, b2 as createMarketplaceEngine, b3 as disputeView, b4 as outboundDedupeKey } from './engine-DH7H8m0B.js';
2
+ import { c as MarketplaceAdapter, p as MarketplaceProvider, q as CancellationReason } from './adapter-lXWwuQQh.js';
3
+ export { A as AdapterCallContext, r as AdapterGrant, s as AdapterTokenCache, t as AppLinkCallContext, u as CancellationOutcome, v as CancellationRequestInput, w as CatalogueCallContext, x as CatalogueFailure, y as CatalogueImage, z as CatalogueItem, e as CatalogueItemOut, B as CatalogueItemRef, C as CatalogueMenuEntry, b as CatalogueMenuOptions, D as CataloguePublishResult, E as CatalogueReadContext, G as CatalogueReadNotice, H as CatalogueReadRefusalCode, I as CatalogueReadResult, J as CatalogueReadWarning, K as CatalogueReadWarningCode, f as CatalogueReader, L as CatalogueSnapshot, Q as CatalogueSnapshotCategory, R as CatalogueSnapshotItem, T as CatalogueSnapshotOption, U as CatalogueSnapshotOptionGroup, V as CatalogueStoredImage, W as CatalogueWarningCode, X as CourierTrackingCallResult, Y as CourierTrackingResult, Z as DeliveryCodeAnswer, _ as DisputeAlternative, $ as DisputeAlternativeType, a0 as DisputeAnswer, a1 as DisputeAnswerResult, a2 as DisputeFailureCode, a3 as DisputeItem, a4 as DisputeOutcome, a5 as DisputeReason, F as FetchOrderResult, a6 as InformLogisticsInput, a7 as LOGISTICS_STEPS, a8 as LinkCallContext, a9 as LinkCode, aa as LinkGrant, ab as LinkResult, ac as LinkedMerchant, ad as LogisticsDriver, ae as LogisticsStep, af as LogisticsVehicle, ag as MarketplaceAcknowledgement, ah as MarketplaceAppCredentialsPort, h as MarketplaceAppLinking, M as MarketplaceAvailability, ai as MarketplaceCapabilities, aj as MarketplaceCatalogue, ak as MarketplaceCourier, al as MarketplaceCourierAnswer, i as MarketplaceCourierApi, am as MarketplaceCourierEngine, an as MarketplaceCourierFacts, ao as MarketplaceCourierStep, n as MarketplaceCourierTracking, ap as MarketplaceCourierVehicle, aq as MarketplaceCredentials, ar as MarketplaceDeliveredBy, as as MarketplaceDiscountSponsor, at as MarketplaceDisputeApi, au as MarketplaceDisputeChange, av as MarketplaceDisputeDelegate, aw as MarketplaceHttp, ax as MarketplaceHttpRequest, ay as MarketplaceHttpResponse, az as MarketplaceLifecycle, aA as MarketplaceLinkAttemptDelegate, g as MarketplaceLinking, m as MarketplaceLogistics, aB as MarketplaceOrderType, aC as MarketplacePaymentMethod, aD as NormalizedAddress, aE as NormalizedBuyer, j as NormalizedCourierEvent, aF as NormalizedDisputeEvent, aG as NormalizedDisputeOpened, aH as NormalizedDisputeSettled, N as NormalizedEvent, aI as NormalizedLineOption, a as NormalizedMarketplaceOrder, aJ as NormalizedOrderDiscount, aK as NormalizedOrderFee, aL as NormalizedOrderLine, aM as NormalizedPaymentMethod, aN as NormalizedPayments, o as OrderCancellationReason, aO as OrderCancellationReasonsResult, aP as OutboundOrderRef, O as OutboundResult, aQ as PROVIDER_ID_PATTERN, aR as PickupCodeCallResult, aS as PickupCodeValidation, aT as PresenceProbe, P as PullCatalogue, d as PushCatalogue, aU as StatusFacts, aV as StatusStep, l as StorePauseRef, S as StorePauseRequest, k as StorePauseResult, aW as ValidatePickupCodeInput, aX as answered, aY as centsFromMajor, aZ as normalizedLineTotalCents, a_ as outboundResultOf, a$ as tokenGrantResultOf } from './adapter-lXWwuQQh.js';
4
4
 
5
5
  /**
6
6
  * The adapter registry: the ONE place a provider id becomes a marketplace.
@@ -1,5 +1,5 @@
1
- import { A as AdapterCallContext, N as NormalizedEvent, a as NormalizedMarketplaceOrder, c as MarketplaceAdapter } from '../adapter-ZpAWKoCk.js';
2
- import { a as OpenDeliveryStop, O as OpenDeliveryApiBaseUrls } from '../client-DpEq0yXb.js';
1
+ import { A as AdapterCallContext, N as NormalizedEvent, a as NormalizedMarketplaceOrder, c as MarketplaceAdapter } from '../adapter-lXWwuQQh.js';
2
+ import { a as OpenDeliveryStop, O as OpenDeliveryApiBaseUrls } from '../client-CSHcYu3w.js';
3
3
 
4
4
  /**
5
5
  * Keeta's MERCHANT AUTHORIZATION, automated from the software (Keeta's
@@ -1,7 +1,7 @@
1
- import { aK as OutboundJobPayload, V as FetchOrderJobPayload, b as AcknowledgeJobPayload, l as CancellationReasonsJobPayload, u as CatalogueJobPayload, f as AvailabilityJobPayload, N as DisputeAnswerJobPayload } from '../engine-CaiVufoP.js';
1
+ import { aK as OutboundJobPayload, V as FetchOrderJobPayload, b as AcknowledgeJobPayload, l as CancellationReasonsJobPayload, u as CatalogueJobPayload, f as AvailabilityJobPayload, N as DisputeAnswerJobPayload } from '../engine-DH7H8m0B.js';
2
2
  import * as _12_apps_wiring from '@12-apps/wiring';
3
3
  import { createApiMarketplace, MarketplaceJobDeps } from '../server/index.js';
4
- import '../adapter-ZpAWKoCk.js';
4
+ import '../adapter-lXWwuQQh.js';
5
5
  import 'zod';
6
6
 
7
7
  declare const marketplaceServerManifest: {
@@ -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-ZpAWKoCk.js';
1
+ import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-lXWwuQQh.js';
2
2
 
3
3
  /**
4
4
  * The words the Rappi adapter needs from its host, and nothing else.
@@ -1,7 +1,7 @@
1
- import { J as DecisionProblemCode, j as BulkProblemCode, a4 as LinkRefusalCode, aq as MarketplaceEngine, ax as MarketplaceLogger, aK as OutboundJobPayload, V as FetchOrderJobPayload, b as AcknowledgeJobPayload, l as CancellationReasonsJobPayload, u as CatalogueJobPayload, f as AvailabilityJobPayload, N as DisputeAnswerJobPayload } from '../engine-CaiVufoP.js';
1
+ import { J as DecisionProblemCode, j as BulkProblemCode, a4 as LinkRefusalCode, aq as MarketplaceEngine, ax as MarketplaceLogger, aK as OutboundJobPayload, V as FetchOrderJobPayload, b as AcknowledgeJobPayload, l as CancellationReasonsJobPayload, u as CatalogueJobPayload, f as AvailabilityJobPayload, N as DisputeAnswerJobPayload } from '../engine-DH7H8m0B.js';
2
2
  import { WireRoute, WireJobBlueprint } from '@12-apps/wiring';
3
3
  import { z } from 'zod';
4
- import '../adapter-ZpAWKoCk.js';
4
+ import '../adapter-lXWwuQQh.js';
5
5
 
6
6
  /**
7
7
  * Every problem code a route words from `problems`, decisions and bulk writes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/marketplace",
3
- "version": "1.19.0",
3
+ "version": "1.20.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.",
@@ -7,13 +7,18 @@
7
7
  * "no Route matched with those values").
8
8
  *
9
9
  * The catalog is the one whose `context` holds `DEFAULT` (delivery), as the
10
- * Fundamentals page names the contexts (DEFAULT, WHITELABEL, INDOOR).
10
+ * Fundamentals page names the contexts (DEFAULT, WHITELABEL, INDOOR). When
11
+ * more than one does, the first with `status: "AVAILABLE"` wins, else the
12
+ * first of them (FUT-6257; no answer with two has been seen, this is hardening).
11
13
  * Reproduced live against iFood's sandbox on 2026-12-03 (FUT-6146): the list
12
14
  * answered `[{ catalogId, context: ["DEFAULT"], status: "AVAILABLE", … }]`
13
15
  * and `…/catalogs/{catalogId}/categories` answered the categories.
14
16
  */
15
17
 
16
- /** The DEFAULT catalog's id in a `GET /catalogs` answer, or null when the answer names none. */
18
+ /**
19
+ * The DEFAULT catalog's id in a `GET /catalogs` answer: the first AVAILABLE
20
+ * one, else the first one; null when the answer names none.
21
+ */
17
22
  export function defaultCatalogIdIn(body: string): string | null {
18
23
  let parsed: unknown;
19
24
  try {
@@ -22,12 +27,16 @@ export function defaultCatalogIdIn(body: string): string | null {
22
27
  return null;
23
28
  }
24
29
  if (!Array.isArray(parsed)) return null;
25
- for (const entry of parsed as unknown[]) {
26
- if (typeof entry !== "object" || entry === null) continue;
27
- const { catalogId, context } = entry as { catalogId?: unknown; context?: unknown };
28
- if (typeof catalogId === "string" && catalogId !== "" && Array.isArray(context) && context.includes("DEFAULT")) return catalogId;
29
- }
30
- return null;
30
+ const defaults = (parsed as unknown[]).map(defaultEntryOf).filter((entry) => entry !== null);
31
+ return (defaults.find((entry) => entry.available) ?? defaults[0])?.catalogId ?? null;
32
+ }
33
+
34
+ /** A `GET /catalogs` entry whose `context` holds DEFAULT, with whether iFood answers it AVAILABLE; null otherwise. */
35
+ function defaultEntryOf(entry: unknown): { catalogId: string; available: boolean } | null {
36
+ if (typeof entry !== "object" || entry === null) return null;
37
+ const { catalogId, context, status } = entry as { catalogId?: unknown; context?: unknown; status?: unknown };
38
+ if (typeof catalogId !== "string" || catalogId === "" || !Array.isArray(context) || !context.includes("DEFAULT")) return null;
39
+ return { catalogId, available: status === "AVAILABLE" };
31
40
  }
32
41
 
33
42
  /** The categories path of a catalog, relative to the merchant's base. */
@@ -135,36 +135,35 @@ async function findCategoryIn(ctx: CatalogueCallContext, catalogId: string, name
135
135
  return { id: categoryIdIn(listed.body, name) };
136
136
  }
137
137
 
138
- /** The category named `name` in the merchant's DEFAULT catalog, or null; the failure otherwise. */
139
- async function findCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string | null } | Failure> {
140
- const catalog = await catalogOf(ctx);
141
- return "kind" in catalog ? catalog : findCategoryIn(ctx, catalog.catalogId, name);
142
- }
143
-
144
138
  /**
145
139
  * Find the category by name, else create it, then read the list again and
146
140
  * adopt the first of that name: a POST whose answer was lost and was retried
147
141
  * is found rather than created twice. The engine runs this once per
148
- * (connection, name) at a time and stores the id (`ctx.category`).
142
+ * (connection, name) at a time and stores the id (`ctx.category`). A
143
+ * `catalogId` this publish already read is reused rather than read again.
149
144
  */
150
- async function findOrCreateCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string } | Failure> {
151
- const catalog = await catalogOf(ctx);
145
+ async function findOrCreateCategory(ctx: CatalogueCallContext, name: string, catalogId?: string): Promise<{ id: string } | Failure> {
146
+ const catalog = catalogId === undefined ? await catalogOf(ctx) : { catalogId };
152
147
  if ("kind" in catalog) return catalog;
153
148
  const found = await findCategoryIn(ctx, catalog.catalogId, name);
154
149
  if ("kind" in found) return found;
155
- if (found.id) return { id: found.id };
156
- const created = await call(ctx, "POST", categoriesPath(catalog.catalogId), { name, status: "AVAILABLE", template: "DEFAULT" });
150
+ return found.id ? { id: found.id } : createCategoryIn(ctx, catalog.catalogId, name);
151
+ }
152
+
153
+ /** Create the category in the catalog, then adopt the first of that name the list answers. */
154
+ async function createCategoryIn(ctx: CatalogueCallContext, catalogId: string, name: string): Promise<{ id: string } | Failure> {
155
+ const created = await call(ctx, "POST", categoriesPath(catalogId), { name, status: "AVAILABLE", template: "DEFAULT" });
157
156
  if ("kind" in created) return created;
158
157
  if (!ok(created)) return failureOf(created);
159
158
  const id = (parse(created.body) as { id?: unknown } | null)?.id;
160
159
  if (typeof id !== "string") return { kind: "retry", reason: "iFood created the category without an id" };
161
160
  // ESTIMATED: the list answers categories in creation order, so the first match is the oldest.
162
- const again = await findCategoryIn(ctx, catalog.catalogId, name);
161
+ const again = await findCategoryIn(ctx, catalogId, name);
163
162
  return "id" in again && again.id ? { id: again.id } : { id };
164
163
  }
165
164
 
166
- const categoryId = (ctx: CatalogueCallContext, name: string): Promise<{ id: string } | Failure> =>
167
- ctx.category(name, () => findOrCreateCategory(ctx, name));
165
+ const categoryId = (ctx: CatalogueCallContext, name: string, catalogId?: string): Promise<{ id: string } | Failure> =>
166
+ ctx.category(name, () => findOrCreateCategory(ctx, name, catalogId));
168
167
 
169
168
  /** The photo the item goes out with, and what the publish could not do about it. */
170
169
  interface PhotoOutcome {
@@ -239,13 +238,21 @@ export function ifoodItemBody(item: CatalogueItemOut, category: string, image: s
239
238
  * Whether a refused PUT was refused because the stored category is gone (the
240
239
  * store deleted it on iFood's portal): iFood's 400 and 404 do not say which id
241
240
  * was unknown, so the list is read again, and a category of that name with
242
- * another id, or none at all, means the stored one is stale. ESTIMATED that a
243
- * deleted category answers 400 or 404.
241
+ * another id, or none at all, means the stored one is stale. Answers the
242
+ * catalog it read when it is, so the find again reads no second `/catalogs`
243
+ * (FUT-6257); null otherwise. ESTIMATED that a deleted category answers 400 or 404.
244
244
  */
245
- async function categoryWentStale(ctx: CatalogueCallContext, put: MarketplaceHttpResponse, name: string, used: string): Promise<boolean> {
246
- if (put.status !== 400 && put.status !== 404) return false;
247
- const found = await findCategory(ctx, name);
248
- return !("kind" in found) && found.id !== used;
245
+ async function categoryWentStale(
246
+ ctx: CatalogueCallContext,
247
+ put: MarketplaceHttpResponse,
248
+ name: string,
249
+ used: string,
250
+ ): Promise<{ catalogId: string } | null> {
251
+ if (put.status !== 400 && put.status !== 404) return null;
252
+ const catalog = await catalogOf(ctx);
253
+ if ("kind" in catalog) return null;
254
+ const found = await findCategoryIn(ctx, catalog.catalogId, name);
255
+ return !("kind" in found) && found.id !== used ? catalog : null;
249
256
  }
250
257
 
251
258
  /** `PUT /items`, once more with the category found or created again when the stored one went stale. */
@@ -253,9 +260,11 @@ async function putItem(ctx: CatalogueCallContext, item: CatalogueItemOut, image:
253
260
  const category = await categoryId(ctx, item.categoryName);
254
261
  if ("kind" in category) return category;
255
262
  const put = await call(ctx, "PUT", "items", ifoodItemBody(item, category.id, image));
256
- if ("kind" in put || ok(put) || !(await categoryWentStale(ctx, put, item.categoryName, category.id))) return put;
263
+ if ("kind" in put || ok(put)) return put;
264
+ const stale = await categoryWentStale(ctx, put, item.categoryName, category.id);
265
+ if (stale === null) return put;
257
266
  await ctx.forgetCategory(item.categoryName);
258
- const again = await categoryId(ctx, item.categoryName);
267
+ const again = await categoryId(ctx, item.categoryName, stale.catalogId);
259
268
  if ("kind" in again) return again;
260
269
  return call(ctx, "PUT", "items", ifoodItemBody(item, again.id, image));
261
270
  }
@@ -176,9 +176,10 @@ function plusSeconds(base: Date, seconds: number | null): Date | null {
176
176
  * The tracking body. Confirmed: latitude, longitude, `expectedDelivery`,
177
177
  * `trackDate`, and seconds to the pickup and to the delivery. ESTIMATED: the
178
178
  * names of the two second counts (`pickupEtaStart`, `deliveryEtaEnd`, or
179
- * `pickupEta`, `deliveryEta`), counted from `trackDate`.
179
+ * `pickupEta`, `deliveryEta`), counted from `trackDate`. The Shipping
180
+ * module's tracking (`./shipping.ts`) documents the same body, so it reads it too.
180
181
  */
181
- function readTracking(body: unknown, now: Date): MarketplaceCourierTracking {
182
+ export function readIfoodTracking(body: unknown, now: Date): MarketplaceCourierTracking {
182
183
  const trackedAt = firstDate(body, [["trackDate"]]);
183
184
  const base = trackedAt ?? now;
184
185
  const pickupSeconds = numberAt(body, "pickupEtaStart") ?? numberAt(body, "pickupEta");
@@ -200,7 +201,7 @@ async function tracking(ctx: AdapterCallContext, order: OutboundOrderRef): Promi
200
201
  if (response.status === 404) return { kind: "notYet" };
201
202
  const read = outboundResultOf(response);
202
203
  if (read.kind !== "accepted") return read;
203
- return { kind: "tracking", tracking: readTracking(parsed(response.body), ctx.now) };
204
+ return { kind: "tracking", tracking: readIfoodTracking(parsed(response.body), ctx.now) };
204
205
  } catch (error) {
205
206
  return retryOf(error);
206
207
  }
@@ -153,3 +153,52 @@ export {
153
153
  type IfoodLogisticsStep,
154
154
  type IfoodLogisticsVehicle,
155
155
  } from "./logistics";
156
+ // iFood Shipping, "Entrega Sob Demanda" (FUT-5667, FUT-5666): wire calls the host's jobs make.
157
+ export {
158
+ IFOOD_SHIPPING_API,
159
+ IFOOD_SHIPPING_ERROR_CODES,
160
+ IFOOD_SHIPPING_TOKEN_REFRESH_AHEAD_MS,
161
+ ifoodCancelRequestDriver,
162
+ ifoodRequestDriver,
163
+ ifoodShippingQuoteForAddress,
164
+ ifoodShippingQuoteForOrder,
165
+ ifoodShippingRetryDelayMs,
166
+ ifoodShippingTracking,
167
+ type IfoodShippingErrorCode,
168
+ type IfoodShippingFailure,
169
+ type IfoodShippingInvalid,
170
+ type IfoodShippingPaymentMethod,
171
+ type IfoodShippingQuote,
172
+ type IfoodShippingQuoteRef,
173
+ type IfoodShippingQuoteResult,
174
+ type IfoodShippingRequested,
175
+ type IfoodShippingTrackingResult,
176
+ } from "./shipping";
177
+ export {
178
+ ifoodShippingCancel,
179
+ ifoodShippingCancellationReasons,
180
+ ifoodShippingCreateOrder,
181
+ type IfoodShippingCreateResult,
182
+ type IfoodShippingItem,
183
+ type IfoodShippingOrderInput,
184
+ type IfoodShippingReasonsResult,
185
+ } from "./shipping-orders";
186
+ export {
187
+ IFOOD_SHIPPING_ADDRESS_CHANGE_MAX_METERS,
188
+ ifoodShippingAcceptAddressChange,
189
+ ifoodShippingConfirmAddress,
190
+ ifoodShippingDenyAddressChange,
191
+ ifoodShippingRequestAddressChange,
192
+ ifoodShippingSafeDelivery,
193
+ type IfoodAddressChangeResult,
194
+ type IfoodSafeDeliveryResult,
195
+ type IfoodSafeDeliveryScore,
196
+ type IfoodShippingAddress,
197
+ } from "./shipping-address";
198
+ export {
199
+ IFOOD_SHIPPING_EVENT_TYPES,
200
+ readIfoodShippingEvent,
201
+ type IfoodShippingEvent,
202
+ type IfoodShippingEventAddress,
203
+ type IfoodShippingEventType,
204
+ } from "./shipping-events";
@@ -0,0 +1,190 @@
1
+ import type { AdapterCallContext } from "../core/adapter";
2
+ import { pick } from "../core/payload-read";
3
+ import {
4
+ IFOOD_SHIPPING_API,
5
+ coordinatesValid,
6
+ parsedBody,
7
+ shippingCall,
8
+ shippingPost,
9
+ type IfoodShippingErrorCode,
10
+ type IfoodShippingFailure,
11
+ type IfoodShippingRequested,
12
+ } from "./shipping-wire";
13
+
14
+ /**
15
+ * The address half of an order on demand (FUT-5667): the address an order
16
+ * carries, the customer's address flow (confirm, change, accept, deny) and the
17
+ * safe-delivery score, per the `outside` guide (sources in `./shipping-wire.ts`).
18
+ */
19
+
20
+ const orderUrl = (orderId: string, action: string): string => `${IFOOD_SHIPPING_API}/orders/${encodeURIComponent(orderId)}/${action}`;
21
+
22
+ /** A delivery address, as the order and an address change carry it. */
23
+ export interface IfoodShippingAddress {
24
+ /** 8 digits once sent; anything else in it is dropped. Not sent with a change request. */
25
+ postalCode: string;
26
+ /** Required on an order; optional on a change request. */
27
+ streetNumber: string;
28
+ /** At most 50 characters. */
29
+ streetName: string;
30
+ /** At most 50 characters. */
31
+ complement?: string;
32
+ /** At most 70 characters. */
33
+ reference?: string;
34
+ /** At most 50 characters. */
35
+ neighborhood: string;
36
+ /** 2 to 50 characters. */
37
+ city: string;
38
+ /** Two letters, e.g. SP. */
39
+ state: string;
40
+ /** Two letters, e.g. BR. */
41
+ country: string;
42
+ latitude: number;
43
+ longitude: number;
44
+ }
45
+
46
+ const trimmed = (value: string | undefined): string => (value ?? "").trim();
47
+
48
+ /** Every field within the `outside` guide's documented lengths. Never cut: a cut street can send the courier elsewhere. */
49
+ function withinLengths(address: IfoodShippingAddress): boolean {
50
+ const max: [string | undefined, number][] = [
51
+ [address.streetName, 50],
52
+ [address.neighborhood, 50],
53
+ [address.city, 50],
54
+ [address.complement, 50],
55
+ [address.reference, 70],
56
+ ];
57
+ return max.every(([value, limit]) => trimmed(value).length <= limit) && trimmed(address.city).length !== 1;
58
+ }
59
+
60
+ /** The fields both kinds require, in range: street, neighbourhood, city, state, country and the point. */
61
+ function requiredValid(address: IfoodShippingAddress): boolean {
62
+ const present = [address.streetName, address.neighborhood, address.city].every((v) => trimmed(v) !== "");
63
+ const letters = /^[A-Za-z]{2}$/.test(address.state) && /^[A-Za-z]{2}$/.test(address.country);
64
+ return present && letters && withinLengths(address) && coordinatesValid(address);
65
+ }
66
+
67
+ /** Only the fields that hold something. */
68
+ function optionalFields(address: IfoodShippingAddress): Record<string, string> {
69
+ const fields: Record<string, string> = {};
70
+ for (const key of ["streetNumber", "complement", "reference"] as const) {
71
+ const value = trimmed(address[key]);
72
+ if (value !== "") fields[key] = value;
73
+ }
74
+ return fields;
75
+ }
76
+
77
+ /**
78
+ * The address body, or null when iFood would refuse it. `order`: the order's
79
+ * `deliveryAddress` (postal code and street number required). `change`: the
80
+ * change request's body (`streetNumber` optional, no postal code).
81
+ */
82
+ export function ifoodShippingAddressBody(address: IfoodShippingAddress, kind: "order" | "change"): Record<string, unknown> | null {
83
+ const postalCode = address.postalCode.replace(/\D/g, "");
84
+ const orderValid = postalCode.length === 8 && trimmed(address.streetNumber) !== "";
85
+ if ((kind === "order" && !orderValid) || !requiredValid(address)) return null;
86
+ return {
87
+ ...(kind === "order" ? { postalCode } : {}),
88
+ ...optionalFields(address),
89
+ streetName: trimmed(address.streetName),
90
+ neighborhood: trimmed(address.neighborhood),
91
+ city: trimmed(address.city),
92
+ state: address.state.toUpperCase(),
93
+ country: address.country.toUpperCase(),
94
+ coordinates: { latitude: address.latitude, longitude: address.longitude },
95
+ };
96
+ }
97
+
98
+ /** An address answer iFood refused: no change pending, another pending, too far, or another region. */
99
+ export type IfoodAddressChangeResult =
100
+ | IfoodShippingRequested
101
+ | { kind: "address-change-refused"; status: number; code: IfoodShippingErrorCode }
102
+ | IfoodShippingFailure;
103
+
104
+ const ADDRESS_REFUSALS: ReadonlySet<string> = new Set([
105
+ "ChangeAddressOperationConflict",
106
+ "ChangeAddressOperationNotStarted",
107
+ "MaxDistanceHigherThanAllowed",
108
+ "RegionMismatch",
109
+ ]);
110
+
111
+ async function addressPost(ctx: AdapterCallContext, url: string, idempotencyKey: string, body?: unknown): Promise<IfoodAddressChangeResult> {
112
+ const result = await shippingPost(ctx, url, idempotencyKey, body);
113
+ if (result.kind === "unavailable" && ADDRESS_REFUSALS.has(result.code)) {
114
+ return { kind: "address-change-refused", status: result.status, code: result.code };
115
+ }
116
+ return result;
117
+ }
118
+
119
+ /** `POST …/userConfirmAddress`: the customer confirmed the original address. */
120
+ export function ifoodShippingConfirmAddress(ctx: AdapterCallContext, orderId: string, idempotencyKey: string): Promise<IfoodAddressChangeResult> {
121
+ return addressPost(ctx, orderUrl(orderId, "userConfirmAddress"), idempotencyKey);
122
+ }
123
+
124
+ /** iFood's limit on a changed address: "máximo 500m da coordenada original". */
125
+ export const IFOOD_SHIPPING_ADDRESS_CHANGE_MAX_METERS = 500;
126
+
127
+ /** Great-circle distance in metres. */
128
+ function metersBetween(a: { latitude: number; longitude: number }, b: { latitude: number; longitude: number }): number {
129
+ const rad = Math.PI / 180;
130
+ const dLat = (b.latitude - a.latitude) * rad;
131
+ const dLon = (b.longitude - a.longitude) * rad;
132
+ const h = Math.sin(dLat / 2) ** 2 + Math.cos(a.latitude * rad) * Math.cos(b.latitude * rad) * Math.sin(dLon / 2) ** 2;
133
+ return 2 * 6_371_000 * Math.asin(Math.sqrt(h));
134
+ }
135
+
136
+ /**
137
+ * `POST …/deliveryAddressChangeRequest`: a change asked through the
138
+ * integrator's own screen. Its body has no postal code and an optional street
139
+ * number. Given the `original` point, a move past 500 m is refused here,
140
+ * before iFood would (`MaxDistanceHigherThanAllowed`).
141
+ */
142
+ export function ifoodShippingRequestAddressChange(
143
+ ctx: AdapterCallContext,
144
+ orderId: string,
145
+ address: IfoodShippingAddress,
146
+ idempotencyKey: string,
147
+ original?: { latitude: number; longitude: number },
148
+ ): Promise<IfoodAddressChangeResult> {
149
+ const body = ifoodShippingAddressBody(address, "change");
150
+ if (body === null) return Promise.resolve({ kind: "invalid", reason: "ADDRESS" });
151
+ if (original && metersBetween(original, address) > IFOOD_SHIPPING_ADDRESS_CHANGE_MAX_METERS) {
152
+ return Promise.resolve({ kind: "invalid", reason: "ADDRESS_TOO_FAR" });
153
+ }
154
+ return addressPost(ctx, orderUrl(orderId, "deliveryAddressChangeRequest"), idempotencyKey, body);
155
+ }
156
+
157
+ /** `POST …/acceptDeliveryAddressChange` (200): within 15 minutes of the request, or iFood rejects it. */
158
+ export function ifoodShippingAcceptAddressChange(ctx: AdapterCallContext, orderId: string, idempotencyKey: string): Promise<IfoodAddressChangeResult> {
159
+ return addressPost(ctx, orderUrl(orderId, "acceptDeliveryAddressChange"), idempotencyKey);
160
+ }
161
+
162
+ /** `POST …/denyDeliveryAddressChange` (202). */
163
+ export function ifoodShippingDenyAddressChange(ctx: AdapterCallContext, orderId: string, idempotencyKey: string): Promise<IfoodAddressChangeResult> {
164
+ return addressPost(ctx, orderUrl(orderId, "denyDeliveryAddressChange"), idempotencyKey);
165
+ }
166
+
167
+ /** iFood's confidence in the delivery. */
168
+ export type IfoodSafeDeliveryScore = "LOW" | "MODERATE" | "HIGH" | "VERY_HIGH";
169
+ const SCORES: readonly string[] = ["LOW", "MODERATE", "HIGH", "VERY_HIGH"];
170
+
171
+ export type IfoodSafeDeliveryResult =
172
+ | { kind: "score"; score: IfoodSafeDeliveryScore; rules: Record<string, boolean> }
173
+ /** 400 `OrderWithoutSafeDelivery`: the order has no score. */
174
+ | { kind: "none" }
175
+ | IfoodShippingFailure;
176
+
177
+ /** `GET /shipping/v1.0/orders/{orderId}/safeDelivery`. */
178
+ export async function ifoodShippingSafeDelivery(ctx: AdapterCallContext, orderId: string): Promise<IfoodSafeDeliveryResult> {
179
+ const answer = await shippingCall(ctx, { method: "GET", url: orderUrl(orderId, "safeDelivery") });
180
+ if (answer.kind === "unavailable" && answer.code === "OrderWithoutSafeDelivery") return { kind: "none" };
181
+ if (answer.kind !== "answer") return answer;
182
+ const parsed = parsedBody(answer.body);
183
+ const score = pick(parsed, "score");
184
+ if (typeof score !== "string" || !SCORES.includes(score)) return { kind: "retry", reason: "iFood Shipping answered no score" };
185
+ const rawRules = pick(parsed, "rules");
186
+ const rules = Object.fromEntries(
187
+ Object.entries(rawRules !== null && typeof rawRules === "object" ? rawRules : {}).filter((entry): entry is [string, boolean] => typeof entry[1] === "boolean"),
188
+ );
189
+ return { kind: "score", score: score as IfoodSafeDeliveryScore, rules };
190
+ }
@@ -0,0 +1,126 @@
1
+ import { firstDate, firstString, pick } from "../core/payload-read";
2
+ import type { NormalizedCourierEvent } from "../core/types";
3
+ import { readIfoodCourierEvent } from "./courier";
4
+
5
+ /**
6
+ * The Shipping events iFood's stream carries (FUT-5667, FUT-5666), read off
7
+ * the `inside` and `outside` Shipping guides and the Order module's events page
8
+ * (https://developer.ifood.com.br/pt-BR/docs/food/guides/modules/order/events),
9
+ * 2026-12-04. The stream, its polling every 30 s, the acknowledgement and the
10
+ * deduplication by event id are the engine's existing ones; this only reads an
11
+ * event the host already has.
12
+ *
13
+ * `salesChannel` tells the two kinds apart: `POS` for an order placed off the
14
+ * platform, `IFOOD` for one placed on it. It is returned as it came; the host
15
+ * filters.
16
+ *
17
+ * `DELIVERY_DROP_CODE_REQUESTED` carries the customer's code in
18
+ * `metadata.CODE`; it is NOT read: the code stays on iFood's tracking page,
19
+ * and never reaches a result a log could print.
20
+ */
21
+
22
+ /** The Shipping events that carry nothing past the order and the time. */
23
+ export const IFOOD_SHIPPING_EVENT_TYPES = [
24
+ "REQUEST_DRIVER",
25
+ "REQUEST_DRIVER_SUCCESS",
26
+ "REQUEST_DRIVER_FAILED",
27
+ "DELIVERY_DROP_CODE_REQUESTED",
28
+ "DELIVERY_IN_TRANSIT",
29
+ "DELIVERY_CONCLUDED",
30
+ "DELIVERY_CANCELLED",
31
+ "DELIVERY_CANCELLATION_REQUESTED",
32
+ "DELIVERY_CANCELLATION_REQUEST_ACCEPTED",
33
+ "DELIVERY_CANCELLATION_REQUEST_REJECTED",
34
+ "CANCELLATION_REQUESTED",
35
+ "CANCELLED",
36
+ "DELIVERY_ADDRESS_CHANGE_USER_CONFIRMED",
37
+ "DELIVERY_ADDRESS_CHANGE_ACCEPTED",
38
+ ] as const;
39
+
40
+ export type IfoodShippingEventType = (typeof IFOOD_SHIPPING_EVENT_TYPES)[number];
41
+
42
+ /** The address a change request names. */
43
+ export interface IfoodShippingEventAddress {
44
+ streetName: string | null;
45
+ streetNumber: string | null;
46
+ complement: string | null;
47
+ reference: string | null;
48
+ neighborhood: string | null;
49
+ city: string | null;
50
+ state: string | null;
51
+ country: string | null;
52
+ latitude: number | null;
53
+ longitude: number | null;
54
+ }
55
+
56
+ interface EventBase {
57
+ eventId: string;
58
+ orderId: string;
59
+ salesChannel: string | null;
60
+ at: Date | null;
61
+ }
62
+
63
+ export type IfoodShippingEvent =
64
+ | (EventBase & { type: IfoodShippingEventType })
65
+ | (EventBase & { type: "DELIVERY_ADDRESS_CHANGE_REQUESTED"; address: IfoodShippingEventAddress })
66
+ /**
67
+ * The order's cancel failed; `reason` is iFood's code from
68
+ * `metadata.CANCELLATION_REQUEST_FAILED_REASON` (e.g.
69
+ * `ACCOUNT_IS_NOT_LINKED_TO_THE_STORE`), a code, never customer data.
70
+ */
71
+ | (EventBase & { type: "CANCELLATION_REQUEST_FAILED"; reason: string | null })
72
+ /** `action` is `region-mismatch` when iFood denied it itself. */
73
+ | (EventBase & { type: "DELIVERY_ADDRESS_CHANGE_DENIED"; action: string | null })
74
+ /** The `ASSIGN_DRIVER` family, read by the courier reader (FUT-5665). */
75
+ | (EventBase & { type: "COURIER"; courier: NormalizedCourierEvent });
76
+
77
+ const SIMPLE: ReadonlySet<string> = new Set(IFOOD_SHIPPING_EVENT_TYPES);
78
+
79
+ function metadataOf(payload: unknown): unknown {
80
+ const raw = pick(payload, "metadata");
81
+ if (typeof raw !== "string") return raw;
82
+ try {
83
+ return JSON.parse(raw) as unknown;
84
+ } catch {
85
+ return null;
86
+ }
87
+ }
88
+
89
+ function numberAt(source: unknown, ...path: string[]): number | null {
90
+ const value = pick(source, ...path);
91
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
92
+ }
93
+
94
+ function addressOf(metadata: unknown): IfoodShippingEventAddress {
95
+ const address = pick(metadata, "address");
96
+ const field = (key: string): string | null => firstString(address, [[key]]);
97
+ return {
98
+ streetName: field("streetName"),
99
+ streetNumber: field("streetNumber"),
100
+ complement: field("complement"),
101
+ reference: field("reference"),
102
+ neighborhood: field("neighborhood"),
103
+ city: field("city"),
104
+ state: field("state"),
105
+ country: field("country"),
106
+ latitude: numberAt(address, "coordinates", "latitude"),
107
+ longitude: numberAt(address, "coordinates", "longitude"),
108
+ };
109
+ }
110
+
111
+ /** A Shipping event, or null for any other event, or one with no id or order. */
112
+ export function readIfoodShippingEvent(payload: unknown): IfoodShippingEvent | null {
113
+ const type = (firstString(payload, [["fullCode"], ["code"]]) ?? "").toUpperCase();
114
+ const eventId = firstString(payload, [["id"], ["eventId"]]);
115
+ const orderId = firstString(payload, [["orderId"]]);
116
+ if (eventId === null || orderId === null) return null;
117
+ const base: EventBase = { eventId, orderId, salesChannel: firstString(payload, [["salesChannel"]]), at: firstDate(payload, [["createdAt"]]) };
118
+ if (SIMPLE.has(type)) return { ...base, type: type as IfoodShippingEventType };
119
+ if (type === "DELIVERY_ADDRESS_CHANGE_REQUESTED") return { ...base, type, address: addressOf(metadataOf(payload)) };
120
+ if (type === "CANCELLATION_REQUEST_FAILED") {
121
+ return { ...base, type, reason: firstString(metadataOf(payload), [["CANCELLATION_REQUEST_FAILED_REASON"]]) };
122
+ }
123
+ if (type === "DELIVERY_ADDRESS_CHANGE_DENIED") return { ...base, type, action: firstString(metadataOf(payload), [["action"]]) };
124
+ const courier = readIfoodCourierEvent(payload, type);
125
+ return courier ? { ...base, type: "COURIER", courier } : null;
126
+ }