@12-apps/marketplace 1.16.0 → 1.18.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/ADOPTING.md +185 -0
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +2 -2
- package/dist/{adapter-CjVdMhZ2.d.ts → adapter-ZpAWKoCk.d.ts} +300 -3
- package/dist/{chunk-TRUK5ZBE.js → chunk-3B5EULS6.js} +2 -2
- package/dist/{chunk-DJIMUEHT.js → chunk-BLHZ3MRB.js} +79 -7
- package/dist/chunk-BLHZ3MRB.js.map +1 -0
- package/dist/{chunk-SGOTN5PX.js → chunk-LO7OKO6V.js} +45 -4
- package/dist/chunk-LO7OKO6V.js.map +1 -0
- package/dist/{chunk-TICWLBSA.js → chunk-MDEIRGNL.js} +1372 -823
- package/dist/chunk-MDEIRGNL.js.map +1 -0
- package/dist/{chunk-H2VQRD3B.js → chunk-Q5RMVNU5.js} +1 -1
- package/dist/chunk-Q5RMVNU5.js.map +1 -0
- package/dist/{chunk-BTKVZAJI.js → chunk-ZT6TZTLD.js} +1 -1
- package/dist/chunk-ZT6TZTLD.js.map +1 -0
- package/dist/{client-DgzCkl8u.d.ts → client-DpEq0yXb.d.ts} +1 -1
- package/dist/{engine-DSRj7qnC.d.ts → engine-DRRhAjZK.d.ts} +566 -293
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +4 -4
- package/dist/ifood/index.d.ts +14 -2
- package/dist/ifood/index.js +406 -120
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +21 -4
- package/dist/index.js +453 -43
- package/dist/index.js.map +1 -1
- package/dist/keeta/index.d.ts +2 -2
- package/dist/keeta/index.js +2 -2
- package/dist/manifest/index.d.ts +78 -0
- package/dist/manifest/index.js +1 -1
- package/dist/manifest/server.d.ts +6 -2
- package/dist/manifest/server.js +4 -4
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +1 -1
- package/dist/server/index.d.ts +93 -7
- package/dist/server/index.js +4 -4
- package/package.json +1 -1
- package/prisma/marketplace.prisma +70 -2
- package/prisma/migrations/20261203180000_marketplace_app_link_check/migration.sql +14 -0
- package/prisma/migrations/20261203190000_marketplace_disputes/migration.sql +96 -0
- package/prisma/migrations/20261203200000_marketplace_status_logistics_steps/migration.sql +12 -0
- package/src/core/adapter.ts +14 -2
- package/src/core/app-linking.ts +396 -0
- package/src/core/delivery-code.ts +119 -0
- package/src/core/dispute-engine.ts +32 -0
- package/src/core/dispute-job.ts +142 -0
- package/src/core/dispute-port.ts +133 -0
- package/src/core/dispute-store.ts +203 -0
- package/src/core/disputes.ts +263 -0
- package/src/core/engine.ts +12 -55
- package/src/core/integration.ts +3 -1
- package/src/core/link-engine.ts +176 -0
- package/src/core/link-store.ts +15 -0
- package/src/core/linking-port.ts +35 -1
- package/src/core/linking.ts +8 -0
- package/src/core/logistics.ts +388 -0
- package/src/core/outbound-queue.ts +6 -1
- package/src/core/outbound-sweep.ts +19 -6
- package/src/core/outbound.ts +4 -5
- package/src/core/pipeline.ts +14 -4
- package/src/core/ports.ts +20 -2
- package/src/core/status-job.ts +3 -0
- package/src/core/status-store.ts +2 -1
- package/src/core/types.ts +10 -0
- package/src/ifood/app-linking.ts +119 -0
- package/src/ifood/disputes.ts +209 -0
- package/src/ifood/index.ts +15 -1
- package/src/ifood/logistics.ts +38 -0
- package/src/ifood/normalize.ts +14 -1
- package/src/index.ts +44 -0
- package/src/server/jobs.ts +51 -3
- package/src/server/link-routes.ts +56 -4
- package/src/server/mcp-link.ts +44 -2
- package/src/server/mcp.ts +2 -1
- package/dist/chunk-BTKVZAJI.js.map +0 -1
- package/dist/chunk-DJIMUEHT.js.map +0 -1
- package/dist/chunk-H2VQRD3B.js.map +0 -1
- package/dist/chunk-SGOTN5PX.js.map +0 -1
- package/dist/chunk-TICWLBSA.js.map +0 -1
- /package/dist/{chunk-TRUK5ZBE.js.map → chunk-3B5EULS6.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/types.ts"],"sourcesContent":["import type { NormalizedDisputeEvent } from \"./dispute-port\";\n\n/**\n * The canonical shape every marketplace adapter normalizes INTO.\n *\n * This type is the seam. The engine below it knows no marketplace by name: a\n * marketplace is an adapter registered with the engine (`./adapter`), and the\n * provider id is whatever that adapter says it is. A second marketplace is a\n * second adapter, never a second pipeline, a second acceptance clock or a\n * second idea of what an order is.\n *\n * Deliberately POORER than any marketplace's own payload. Everything a store\n * operates on is here; everything else stays in the inbox row's raw `payload`,\n * which is where a normalization bug is reconstructed from.\n */\n\n/**\n * A marketplace's id, as its adapter declares it (`\"IFOOD\"`). Uppercase\n * letters, digits and underscores; the migration's CHECK holds the same shape.\n * A string rather than a closed union, because the set of marketplaces is the\n * set of registered adapters, and a union would make a new one a code change\n * in the engine.\n */\nexport type MarketplaceProvider = string;\n\n/** The shape a provider id must have. Shared by the registry and the CHECK. */\nexport const PROVIDER_ID_PATTERN = /^[A-Z][A-Z0-9_]*$/u;\n\n/** One line of an incoming order, before it is resolved against the catalog. */\nexport interface NormalizedOrderLine {\n /** The marketplace's own SKU — the key the SKU map is matched on. */\n externalSku: string;\n /** What the marketplace called it. Snapshotted, and the fallback line text. */\n name: string;\n quantity: number;\n /**\n * Unit price in the smallest currency unit AS THE MARKETPLACE STATES IT. A\n * marketplace's menu carries its own prices, and the buyer's receipt is the\n * marketplace's one: re-pricing from the host's catalog would produce a\n * total nobody was charged.\n */\n unitPriceCents: number;\n /** The buyer's note on this line, when they left one. */\n note: string | null;\n /**\n * OPTIONAL (FUT-5803). The options the buyer chose on this line (a\n * complemento: \"borda recheada\", \"sem cebola\"), each priced on its own. When\n * present, `unitPriceCents` is the item ALONE and the line costs\n * `unitPriceCents × quantity + Σ options[].totalCents`\n * ({@link normalizedLineTotalCents}). Absent: none is itemized. Open\n * Delivery and Rappi then fold the options' price into `unitPriceCents`;\n * iFood does not, so an iFood item that states `optionsPrice` but lists no\n * `options[]` is priced as the item alone. Never an empty array.\n */\n options?: NormalizedLineOption[];\n}\n\n/** One option on an order line, as the marketplace priced it (FUT-5803). */\nexport interface NormalizedLineOption {\n /** The marketplace's own code for the option, when it gives one. */\n externalCode: string | null;\n name: string;\n /** The group the marketplace shows it under (\"Borda\", \"Adicionais\"), when it says. */\n groupName: string | null;\n /** How many, for the WHOLE line (never per unit of it). */\n quantity: number;\n unitPriceCents: number;\n /**\n * Always exactly `unitPriceCents × quantity`. A stated price that does not\n * divide by its count arrives as two rows of the same option (the floor,\n * then one unit carrying the remainder), whose counts sum to the stated one.\n */\n totalCents: number;\n}\n\n/** What a line costs: the item times its quantity, plus each of its options. */\nexport function normalizedLineTotalCents(line: Pick<NormalizedOrderLine, \"unitPriceCents\" | \"quantity\" | \"options\">): number {\n return line.unitPriceCents * line.quantity + (line.options ?? []).reduce((sum, option) => sum + option.totalCents, 0);\n}\n\n/** The buyer, as much of them as the marketplace discloses. */\nexport interface NormalizedBuyer {\n /** The marketplace's own stable id for this customer, when it gives one. */\n externalId: string | null;\n name: string | null;\n phone: string | null;\n /**\n * OPTIONAL (FUT-5803). The buyer's tax id for the invoice (a CPF or a CNPJ),\n * digits only. Absent: the marketplace states none.\n */\n document?: string | null;\n /**\n * OPTIONAL (FUT-5803). The extension that reaches the buyer through the\n * marketplace's masked number in `phone` (iFood's `phone.localizer`). Absent: none.\n */\n phoneLocalizer?: string | null;\n}\n\n/** Where a delivery goes, as much of it as the marketplace states. */\nexport interface NormalizedAddress {\n street: string;\n number: string;\n neighborhood: string;\n complement: string | null;\n /** The sentence that finds the door. */\n reference: string | null;\n postalCode: string | null;\n city: string | null;\n state: string | null;\n}\n\n/**\n * How the order reaches the buyer: brought to the door (`DELIVERY`), collected\n * (`TAKEOUT`), eaten at the store (`DINE_IN`), or ordered from inside it, at a\n * table or a spot the buyer names (`INDOOR`, FUT-5803).\n */\nexport type MarketplaceOrderType = \"DELIVERY\" | \"TAKEOUT\" | \"DINE_IN\" | \"INDOOR\";\n\n/** WHO carries a delivery: the merchant's own courier, or the marketplace's fleet. */\nexport type MarketplaceDeliveredBy = \"MERCHANT\" | \"MARKETPLACE\";\n\n/** WHO pays for a discount: the store, the marketplace's own campaign, or someone else (a card issuer, a voucher). */\nexport type MarketplaceDiscountSponsor = \"MERCHANT\" | \"MARKETPLACE\" | \"OTHER\";\n\n/** One discount on an order, as the part one sponsor pays. */\nexport interface NormalizedOrderDiscount {\n /** The discount's value in the smallest currency unit. */\n cents: number;\n sponsor: MarketplaceDiscountSponsor;\n /** What the marketplace called the campaign, when it says. */\n name?: string;\n}\n\n/**\n * How a buyer paid, as a closed set a host has words for. `OTHER`: stated,\n * and none of these (the marketplace's own word is in `statedMethod`).\n */\nexport type MarketplacePaymentMethod =\n | \"CREDIT\"\n | \"DEBIT\"\n | \"MEAL_VOUCHER\"\n | \"FOOD_VOUCHER\"\n | \"PIX\"\n | \"CASH\"\n | \"DIGITAL_WALLET\"\n | \"OTHER\";\n\n/** One way the buyer pays an order (FUT-5803). */\nexport interface NormalizedPaymentMethod {\n method: MarketplacePaymentMethod;\n /** The marketplace's own word for the method, verbatim; null when it states none. */\n statedMethod: string | null;\n /**\n * True: already paid on the marketplace. False: to collect from the buyer at\n * the door or the counter. Null: unstated.\n */\n prepaid: boolean | null;\n /** What this method pays, in the smallest currency unit. */\n valueCents: number;\n /** The card's brand as the marketplace names it (\"VISA\"), when it does. */\n cardBrand: string | null;\n /** On cash: the note the buyer pays with, so the courier brings the change. Null: no change asked, or unstated. */\n changeForCents: number | null;\n}\n\n/** The order's payment, as the marketplace states it (FUT-5803). */\nexport interface NormalizedPayments {\n /** What the marketplace already collected. Null: unstated. */\n prepaidCents: number | null;\n /** What is still to collect from the buyer. Null: unstated. */\n pendingCents: number | null;\n methods: NormalizedPaymentMethod[];\n}\n\n/** A fee the marketplace charged the buyer besides delivery (FUT-5803), such as a small-order fee. */\nexport interface NormalizedOrderFee {\n /** The marketplace's own kind, verbatim (`SMALL_ORDER_FEE`). */\n kind: string;\n cents: number;\n /** What the marketplace called it, when it says. */\n name?: string;\n}\n\n/** An incoming marketplace order, normalized. */\nexport interface NormalizedMarketplaceOrder {\n provider: MarketplaceProvider;\n /** The marketplace's order id — THE idempotency key for the whole pipeline. */\n externalOrderId: string;\n /** The short code the courier and the buyer say out loud. */\n externalDisplayId: string | null;\n buyer: NormalizedBuyer;\n lines: NormalizedOrderLine[];\n /**\n * What the buyer paid, gross. NOT derived from the lines when the\n * marketplace states it: its total carries fees, promotions and rounding the\n * line sum does not, and the number that must match the receipt is this one.\n */\n totalCents: number;\n /** The marketplace's cut, when it states one. NULL is \"did not say\", not 0. */\n commissionCents: number | null;\n /** The marketplace's own promise to the buyer. */\n deliveryDueAt: Date | null;\n /** When the marketplace says the order was placed. */\n placedAt: Date;\n /** Null when the payload does not say. */\n orderType?: MarketplaceOrderType | null;\n /** Null on a take-out and when unstated. */\n deliveredBy?: MarketplaceDeliveredBy | null;\n /** Null on a take-out and when unstated. */\n deliveryAddress?: NormalizedAddress | null;\n /**\n * OPTIONAL. The delivery fee the buyer was charged, in the smallest currency\n * unit. 0 is a free delivery; null or absent is \"did not say\".\n */\n deliveryFeeCents?: number | null;\n /** OPTIONAL. The items' sum as the marketplace states it, before fees and discounts. Null or absent is \"did not say\". */\n subtotalCents?: number | null;\n /**\n * OPTIONAL. The discounts on the order, one entry per sponsor's share, so a\n * host can tell what the store gave from what the marketplace paid for.\n * Absent is \"did not say\"; an empty array is \"no discount\".\n */\n discounts?: NormalizedOrderDiscount[];\n /**\n * OPTIONAL. The merchant the order names, when its body says (Open\n * Delivery's `merchant.id`). A fetched order naming another merchant than\n * the connection's is refused.\n */\n externalMerchantId?: string | null;\n /**\n * OPTIONAL (FUT-5665). The code the marketplace's courier states at the\n * counter to collect the bag (iFood's `delivery.pickupCode`), for the host\n * to check locally at the hand-over. Null or absent: the marketplace asks\n * none for this order (the check is off for the store, or the store carries\n * the bag itself).\n */\n pickupCode?: string | null;\n /**\n * OPTIONAL (FUT-5803). How the buyer pays: each method, what is prepaid and\n * what is still to collect, and the change a cash buyer asks for. Absent:\n * the marketplace states none.\n */\n payments?: NormalizedPayments;\n /**\n * OPTIONAL (FUT-5803). The fees besides delivery, inside `totalCents`.\n * Absent is \"did not say\"; an empty array is \"none\".\n */\n additionalFees?: NormalizedOrderFee[];\n}\n\n/**\n * What an event says about the STORE's own cancellation request: `CONFIRMED`\n * when the marketplace cancelled the order (a pending request is answered),\n * `FAILED` when it refused the request.\n */\nexport type CancellationOutcome = \"CONFIRMED\" | \"FAILED\";\n\n/**\n * A step of the order's life a marketplace announces about an order it\n * already has (FUT-4653): the courier left (`DISPATCHED`), the marketplace's\n * courier has the bag (`COLLECTED`, FUT-5665: for a fleet bag it is the same\n * hand-over as `DISPATCHED`) or the order is finished (`CONCLUDED`). An event\n * that names one moves nothing by itself; the engine asks the host to move the\n * order forward (`onLifecycle`).\n */\nexport type MarketplaceLifecycle = \"DISPATCHED\" | \"COLLECTED\" | \"CONCLUDED\";\n\n/**\n * Where the marketplace's own courier is with a bag (FUT-5665), provider-\n * neutral: named (`ASSIGNED`), on the way to the store (`GOING_TO_ORIGIN`),\n * at the counter (`ARRIVED_AT_ORIGIN`), holding the bag (`COLLECTED`), or\n * bringing it back (`RETURNING_TO_ORIGIN`, then `RETURNED_TO_ORIGIN`).\n */\nexport type MarketplaceCourierStep =\n | \"ASSIGNED\"\n | \"GOING_TO_ORIGIN\"\n | \"ARRIVED_AT_ORIGIN\"\n | \"COLLECTED\"\n | \"RETURNING_TO_ORIGIN\"\n | \"RETURNED_TO_ORIGIN\";\n\n/** What the courier rides, as a closed set the host has words for. `OTHER`: stated, and none of these. */\nexport type MarketplaceCourierVehicle = \"MOTORCYCLE\" | \"BICYCLE\" | \"CAR\" | \"OTHER\";\n\n/** Who the marketplace sent, as much as it says. */\nexport interface MarketplaceCourier {\n name: string | null;\n /** An https URL of the courier's photo, or null (any other scheme is dropped). */\n photoUrl: string | null;\n vehicle: MarketplaceCourierVehicle | null;\n}\n\n/** One courier event, normalized (FUT-5665). */\nexport interface NormalizedCourierEvent {\n step: MarketplaceCourierStep;\n /** When the marketplace says it happened; null when it does not (the engine then hands the host its clock). */\n at: Date | null;\n /** Who is coming: on `ASSIGNED`, when the marketplace names them; null otherwise. */\n courier: MarketplaceCourier | null;\n /** The bag is coming back (`RETURNING`) or is back (`RETURNED`); null on every other step. */\n returning: \"RETURNING\" | \"RETURNED\" | null;\n}\n\n/** What an adapter makes of one inbound delivery. */\nexport interface NormalizedEvent {\n provider: MarketplaceProvider;\n /** The delivery's own id — the inbox dedup key, paired with the provider. */\n eventId: string;\n /** The provider's event type verbatim, kept for the inbox row and the log. */\n eventType: string;\n /** The merchant this event names, used to attribute it to a tenant. */\n externalMerchantId: string | null;\n externalOrderId: string | null;\n /**\n * The order this event carries, or null when the event is one the engine\n * understands and does not ingest. A null here is an IGNORED inbox row (or a\n * cancellation, below), never a failure.\n */\n order: NormalizedMarketplaceOrder | null;\n /** The marketplace has CANCELLED the order. */\n cancelled: boolean;\n /**\n * The answer to the store's own cancellation request, when this event is\n * one. A `cancelled: true` event reads as `CONFIRMED` when this is absent.\n */\n cancellationOutcome?: CancellationOutcome | null;\n /**\n * OPTIONAL. This event announces an order whose body the marketplace serves\n * separately (Open Delivery's `CREATED` carries only the order's id): the\n * engine fetches it through the adapter's `fetchOrder`, in the\n * `marketplace.fetch-order` job, never inside the request that delivered\n * the event. Ignored when `order` is present.\n */\n orderToFetch?: boolean;\n /**\n * OPTIONAL. The lifecycle step this event announces about an order the\n * engine already has. Absent or null: the event names none. An event that\n * names one carries no order body.\n */\n lifecycle?: MarketplaceLifecycle | null;\n /**\n * OPTIONAL (FUT-5665). Where the marketplace's courier is, when this event\n * says. A `COLLECTED` names the lifecycle too. Absent or null: the event\n * names no courier step.\n */\n courier?: NormalizedCourierEvent | null;\n /**\n * OPTIONAL (FUT-5653). The store accepted the order in the marketplace's own\n * app (iFood's `CFM`): an order still AWAITING here is accepted through the\n * host's admit, with no confirm sent back. Carries no order body.\n */\n marketplaceConfirmed?: boolean;\n /** The marketplace asked the customer's delivery code for the order (FUT-6167). */\n deliveryCodeRequested?: boolean;\n /**\n * OPTIONAL (FUT-6099). A dispute the marketplace opened or closed on this\n * order (iFood's HSD / HSS). Carries no order body, and never moves the\n * order or its acceptance.\n */\n dispute?: NormalizedDisputeEvent | null;\n}\n"],"mappings":";;;;;AA0BO,IAAM,sBAAsB;AAkD5B,SAAS,yBAAyB,MAAoF;AAC3H,SAAO,KAAK,iBAAiB,KAAK,YAAY,KAAK,WAAW,CAAC,GAAG,OAAO,CAAC,KAAK,WAAW,MAAM,OAAO,YAAY,CAAC;AACtH;AAFgB;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { MarketplaceCatalogue } from \"./catalogue-port\";\nimport type { MarketplaceCourierApi } from \"./courier-port\";\nimport type { MarketplaceDisputeApi } from \"./dispute-port\";\nimport type { CatalogueReader } from \"./catalogue-read-port\";\nimport type { MarketplaceAppLinking, MarketplaceLinking } from \"./linking-port\";\nimport type { LogisticsAdapter } from \"./logistics\";\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 * OPTIONAL. The HTTP status a recorded delivery is answered with (FUT-5984:\n * iFood wants `202 Accepted`). Absent: 200. Refusals and failures keep theirs.\n */\n webhookAnswerStatus?: 200 | 202;\n /**\n * OPTIONAL. The marketplace announces that the store accepted an order in the\n * marketplace's own app (`NormalizedEvent.marketplaceConfirmed`, FUT-5653).\n * Its ingest then applies a confirmation that arrived before the order.\n */\n marketplaceConfirms?: boolean;\n /**\n * OPTIONAL. A status step is told only after the marketplace took the\n * store's confirm (`confirmedAt`, FUT-5673: iFood refuses a step of an order\n * it has not confirmed). Absent: steps never wait on the confirm.\n */\n statusAfterConfirm?: boolean;\n /** OPTIONAL (FUT-6099). The buyer's disputes arrive as events and are answered through `disputes`. */\n disputes?: boolean;\n}\n\n/**\n * A marketplace's presence heartbeat (FUT-5984: iFood's `KEEPALIVE`), read off\n * a delivery: `merchantIds` when it asks about named merchants (its\n * per-merchant mode), null when it asks about the whole app.\n */\nexport interface PresenceProbe {\n merchantIds: readonly string[] | null;\n}\n\n/** Acknowledging recorded events to the marketplace (FUT-5984: iFood's `events/acknowledgment`). */\nexport interface MarketplaceAcknowledgement {\n /** At most this many event ids per call. */\n batchSize: number;\n /** How long the marketplace keeps an event: an older one is never acknowledged. */\n retentionMs: number;\n /** Acknowledge these event ids, in one call. */\n send(ctx: AdapterCallContext, eventIds: readonly string[]): Promise<OutboundResult>;\n}\n\n/** One cancellation reason the marketplace lists for one order: its code and its own words. */\nexport interface OrderCancellationReason {\n code: string;\n description: string;\n}\n\n/** One order's reasons read from the marketplace, or the refusal / retry of the read. */\nexport type OrderCancellationReasonsResult =\n | { kind: \"reasons\"; reasons: OrderCancellationReason[] }\n | Exclude<OutboundResult, { kind: \"accepted\" }>;\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 extends LogisticsAdapter {\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 /**\n * The marketplace's documented reasons, static and offline: a dialog never\n * waits on the network. With `orderCancellationReasons`, the fallback of an\n * order whose own list could not be read.\n */\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. The step that must be told before this one for this kind of\n * order (FUT-5984: iFood's dispatch of a merchant bag follows its\n * `readyToPickup`), or null. The status job sends it first when it is not\n * told yet.\n */\n statusPrerequisite?(facts: StatusFacts): StatusStep | null;\n /**\n * OPTIONAL. A delivery that is the marketplace's presence heartbeat, not an\n * event (FUT-5984: iFood's `KEEPALIVE`), or null. Answered 202 once its\n * signature is proved, with nothing recorded.\n */\n presence?(payload: unknown): PresenceProbe | null;\n /** OPTIONAL. Acknowledging recorded events (FUT-5984). Absent: nothing is acknowledged. */\n readonly acknowledgement?: MarketplaceAcknowledgement;\n /**\n * OPTIONAL. Read the reasons the marketplace accepts for cancelling THIS\n * order (FUT-5984: iFood's `GET /orders/{id}/cancellationReasons`). Called\n * only from the `marketplace.cancellation-reasons` job. Absent: the static\n * `cancellationReasons()` are every order's.\n */\n orderCancellationReasons?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<OrderCancellationReasonsResult>;\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. Linking a store through the software's CENTRALIZED app (FUT-5798):\n * the store authorizes the app on the portal and picks its store from the\n * app's list; no code, no token of its own. Wins over `linking` when both are set.\n */\n readonly appLinking?: MarketplaceAppLinking;\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 /** OPTIONAL (FUT-6099). Answering the buyer's disputes; present with `capabilities.disputes`. */\n readonly disputes?: MarketplaceDisputeApi;\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":";;;;;AA8WA,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":[]}
|