@12-apps/marketplace 1.7.0 → 1.9.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 +17 -0
- package/README.md +153 -3
- package/dist/99food/index.d.ts +30 -52
- package/dist/99food/index.js +62 -391
- package/dist/99food/index.js.map +1 -1
- package/dist/{adapter-DOjTak1H.d.ts → adapter-CYJzu1c9.d.ts} +45 -1
- package/dist/{chunk-YVUZHXUF.js → chunk-6N2HEV3U.js} +4 -4
- package/dist/chunk-6N2HEV3U.js.map +1 -0
- package/dist/{chunk-SJUKBCVO.js → chunk-BMCERPQX.js} +198 -12
- package/dist/chunk-BMCERPQX.js.map +1 -0
- package/dist/{chunk-L3DCOZUU.js → chunk-HEXLCTOG.js} +1 -1
- package/dist/chunk-HEXLCTOG.js.map +1 -0
- package/dist/{chunk-UYFYGGCS.js → chunk-NP4EYKPO.js} +3 -1
- package/dist/chunk-NP4EYKPO.js.map +1 -0
- package/dist/chunk-PYHNM47K.js +478 -0
- package/dist/chunk-PYHNM47K.js.map +1 -0
- package/dist/client-B4EQCRD_.d.ts +20 -0
- package/dist/{engine-DG1fg43Y.d.ts → engine-wmW-VuBL.d.ts} +107 -4
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +3 -3
- package/dist/ifood/index.d.ts +1 -1
- package/dist/ifood/index.js +29 -3
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +104 -7
- package/dist/index.js.map +1 -1
- package/dist/keeta/en-US.d.ts +19 -0
- package/dist/keeta/en-US.js +23 -0
- package/dist/keeta/en-US.js.map +1 -0
- package/dist/keeta/index.d.ts +253 -0
- package/dist/keeta/index.js +388 -0
- package/dist/keeta/index.js.map +1 -0
- package/dist/keeta/pt-BR.d.ts +23 -0
- package/dist/keeta/pt-BR.js +23 -0
- package/dist/keeta/pt-BR.js.map +1 -0
- package/dist/manifest/index.d.ts +3 -0
- package/dist/manifest/index.js +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/manifest/server.js +3 -3
- package/dist/rappi/index.d.ts +7 -1
- package/dist/rappi/index.js +20 -3
- package/dist/rappi/index.js.map +1 -1
- package/dist/server/index.d.ts +6 -2
- package/dist/server/index.js +3 -3
- package/package.json +14 -2
- package/prisma/marketplace.prisma +45 -1
- package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
- package/src/99food/catalogue.ts +19 -89
- package/src/99food/copy.ts +4 -19
- package/src/99food/index.ts +29 -28
- package/src/99food/normalize.ts +11 -247
- package/src/99food/outbound.ts +29 -215
- package/src/99food/pause.ts +7 -22
- package/src/core/adapter.ts +41 -1
- package/src/core/bulk.ts +1 -1
- package/src/core/engine.ts +9 -0
- package/src/core/ingest.ts +6 -0
- package/src/core/integration.ts +17 -0
- package/src/core/lifecycle-port.ts +16 -0
- package/src/core/lifecycle.ts +133 -0
- package/src/core/outbound-queue.ts +24 -4
- package/src/core/outbound-sweep.ts +49 -5
- package/src/core/outbound.ts +11 -0
- package/src/core/pipeline.ts +22 -2
- package/src/core/ports.ts +39 -3
- package/src/core/status-inform.ts +51 -0
- package/src/core/status-job.ts +207 -0
- package/src/core/status-store.ts +85 -0
- package/src/core/types.ts +14 -0
- package/src/ifood/index.ts +7 -1
- package/src/ifood/normalize.ts +17 -0
- package/src/ifood/outbound.ts +35 -0
- package/src/index.ts +8 -1
- package/src/keeta/authorization.ts +226 -0
- package/src/keeta/copy.ts +27 -0
- package/src/keeta/en-US.ts +19 -0
- package/src/keeta/index.ts +162 -0
- package/src/keeta/merchant.ts +70 -0
- package/src/keeta/normalize.ts +131 -0
- package/src/keeta/outbound.ts +55 -0
- package/src/keeta/pt-BR.ts +23 -0
- package/src/keeta/signature.ts +85 -0
- package/src/open-delivery/client.ts +185 -0
- package/src/open-delivery/merchant.ts +126 -0
- package/src/open-delivery/normalize.ts +269 -0
- package/src/open-delivery/orders.ts +241 -0
- package/src/open-delivery/reasons.ts +26 -0
- package/src/rappi/index.ts +6 -1
- package/src/rappi/normalize.ts +6 -0
- package/src/rappi/outbound.ts +31 -2
- package/src/server/mcp.ts +2 -0
- package/src/server/webhook.ts +3 -1
- package/dist/chunk-L3DCOZUU.js.map +0 -1
- package/dist/chunk-SJUKBCVO.js.map +0 -1
- package/dist/chunk-UYFYGGCS.js.map +0 -1
- package/dist/chunk-YVUZHXUF.js.map +0 -1
package/dist/99food/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/99food/copy.ts","../../src/99food/normalize.ts","../../src/99food/outbound.ts","../../src/99food/catalogue.ts","../../src/99food/pause.ts","../../src/99food/index.ts"],"sourcesContent":["/**\n * The words the 99Food adapter needs from its host, and nothing else.\n *\n * Required and defaultless, like every copy port in this repo: the adapter\n * ships no language of its own. Two packs sit beside it (`./pt-BR`,\n * `./en-US`); a host passes one by hand, or its own.\n */\n\n/**\n * The cancellation codes a merchant may send, verbatim from Open Delivery\n * v1.7.1 (`RequestCancelled.code`). Pinned by the spec, not estimated. The two\n * codes only the marketplace sends (`CONSUMER_CANCELLATION_REQUESTED`,\n * `OTHER_CANCELLATION_REASON`) are not a store's to choose and are left out.\n */\nexport const NINETY_NINE_FOOD_REASON_CODES = [\n \"SYSTEMIC_ISSUES\",\n \"DUPLICATE_APPLICATION\",\n \"UNAVAILABLE_ITEM\",\n \"RESTAURANT_WITHOUT_DELIVERY_PERSON\",\n \"OUTDATED_MENU\",\n \"ORDER_OUTSIDE_THE_DELIVERY_AREA\",\n \"BLOCKED_CUSTOMER\",\n \"OUTSIDE_DELIVERY_HOURS\",\n \"INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT\",\n \"RISK_AREA\",\n \"DELIVERY_PROBLEM\",\n] as const;\n\nexport type NinetyNineFoodReasonCode = (typeof NINETY_NINE_FOOD_REASON_CODES)[number];\n\nexport interface NinetyNineFoodAdapterCopy {\n /** One label per reason code. Sent as the request's `reason` text when the store wrote none. */\n reasonLabels: Readonly<Record<NinetyNineFoodReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import {\n asString,\n firstCents,\n firstDate,\n firstString,\n pick,\n toCents,\n verifyHmacSha256Hex,\n} from \"../core/payload-read\";\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceOrderType,\n NormalizedAddress,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n NormalizedOrderLine,\n} from \"../core/types\";\n\n/**\n * The 99Food adapter's INBOUND half, on Open Delivery v1.7.1 (Abrasel).\n *\n * Open Delivery splits what iFood sends at once: the webhook's `Event` names\n * an order (`eventId`, `eventType`, `orderId`, `orderURL`, `createdAt`) and\n * carries no body, and `GET /v1/orders/{orderId}` answers the `Order`. So\n * there are two readers here: {@link normalizeOpenDeliveryEvent} for the\n * webhook (a `CREATED` becomes `orderToFetch`), and\n * {@link normalizeOpenDeliveryOrder} for what the engine's fetch job reads.\n *\n * Every shape below is the spec's (`components/schemas/Event`, `Order`,\n * `Price`, `Address`), and every fixture in the tests is the spec's own\n * example. Read defensively all the same: a missing field produces null, and\n * only a missing order id refuses an event (it is the idempotency key).\n */\n\n/** The provider id 99Food is registered under. Uppercase: the column's CHECK holds that shape. */\nexport const NINETY_NINE_FOOD_PROVIDER = \"NINETY_NINE_FOOD\";\n\n/** The order exists and its body must be fetched. */\nconst CREATED = \"CREATED\";\n/** The order is cancelled: the store's request was granted, or a mandatory cancellation. */\nconst CANCELLED = \"CANCELLED\";\n/** The marketplace refused the store's own cancellation request. */\nconst CANCELLATION_REQUEST_DENIED = \"CANCELLATION_REQUEST_DENIED\";\n\n/**\n * Verify a delivery: Open Delivery's `X-App-Signature` is \"a lowercased\n * hexadecimal HMAC signature of the webhook HTTP request body, using the\n * client secret as a key and SHA256 as the hash function\". The key is the\n * merchant app's CLIENT SECRET, so a store's connection keeps that same value\n * as its webhook secret.\n *\n * Unlike iFood (whose secret is issued after certification), the key exists\n * from the moment the store connects, so an unset secret REFUSES: an unsigned\n * CANCELLED for a known order id would otherwise cancel it.\n */\nexport function verifyOpenDeliverySignature(\n rawBody: string,\n signature: string | null,\n webhookSecret: string | null,\n): boolean {\n if (!webhookSecret) return false;\n return verifyHmacSha256Hex(rawBody, signature, webhookSecret);\n}\n\n/**\n * Normalize one webhook `Event`. Null only when it names no order.\n *\n * - `CREATED` announces an order: `orderToFetch`, the body is the fetch job's.\n * - `CANCELLED` is a cancellation, whether the store asked for it or not.\n * - `CANCELLATION_REQUEST_DENIED` refuses the store's request.\n * - Everything else (`CONFIRMED`, `CANCELLATION_REQUESTED`, `DISPATCHED`, the\n * consumer's `ORDER_CANCELLATION_REQUEST` handshake…) is understood and\n * recorded, and acts on nothing: an IGNORED inbox row.\n *\n * The merchant is named by the `X-App-MerchantId` HEADER, not the body; the\n * engine attributes a delivery by its URL's store slug, so it reads none.\n */\nexport function normalizeOpenDeliveryEvent(payload: unknown): NormalizedEvent | null {\n const externalOrderId = firstString(payload, [[\"orderId\"]]);\n if (!externalOrderId) return null;\n const eventType = (firstString(payload, [[\"eventType\"]]) ?? \"UNKNOWN\").toUpperCase();\n const cancelled = eventType === CANCELLED;\n const denied = eventType === CANCELLATION_REQUEST_DENIED;\n return {\n provider: NINETY_NINE_FOOD_PROVIDER,\n // The spec's own event id. The fallback is deterministic so a redelivery\n // still collides on the inbox's unique index.\n eventId: firstString(payload, [[\"eventId\"]]) ?? `${externalOrderId}:${eventType}`,\n eventType,\n externalMerchantId: null,\n externalOrderId,\n order: null,\n orderToFetch: eventType === CREATED,\n cancelled,\n cancellationOutcome: cancelled ? \"CONFIRMED\" : denied ? \"FAILED\" : null,\n };\n}\n\n/** A `Price` object (`{ value, currency }`) in cents. */\nfunction priceCents(source: unknown, ...path: string[]): number | null {\n return toCents(pick(source, ...path, \"value\"));\n}\n\n/**\n * The note a kitchen reads: the chosen options (a pizza's halves are options)\n * and the buyer's own instructions. The normalized line has no options of its\n * own, and a flavour dropped from the ticket is food made wrong.\n */\nfunction lineNote(item: unknown, fraction: string | null): string | null {\n const rawOptions = pick(item, \"options\");\n const options = (Array.isArray(rawOptions) ? rawOptions : [])\n .map((option) => {\n const name = asString(pick(option, \"name\"));\n const quantity = Number(pick(option, \"quantity\") ?? 1);\n return name && quantity > 1 ? `${quantity}x ${name}` : name;\n })\n .filter((name): name is string => name !== null);\n const parts = [fraction, options.join(\", \") || null, firstString(item, [[\"specialInstructions\"]])];\n const note = parts.filter((part): part is string => part !== null).join(\" · \");\n return note === \"\" ? null : note;\n}\n\n/**\n * What the buyer paid for the whole line, in cents. The spec's `totalPrice`\n * (\"quantity * (unitPrice + optionsPrice)\") is the figure the order's\n * `itemsPrice` is built from, and it wins whenever it is stated — its own\n * example does not add up otherwise (unit 43, options 50, total 50).\n *\n * Without it: `unitPrice × quantity + optionsPrice`. ESTIMATED: the spec calls\n * `optionsPrice` \"the sum of the total prices of all options of the item\", a\n * LINE figure, so it is added once, never multiplied by the quantity or by a\n * weight.\n */\nfunction lineTotalCents(item: unknown, quantity: number): number {\n const total = priceCents(item, \"totalPrice\");\n if (total !== null) return total;\n const unit = priceCents(item, \"unitPrice\") ?? 0;\n return Math.round(unit * quantity) + (priceCents(item, \"optionsPrice\") ?? 0);\n}\n\n/** The stated quantity (decimal for weighed units), 1 when absent or nonsense. */\nfunction quantityOf(item: unknown): number {\n const stated = Number(pick(item, \"quantity\") ?? 1);\n return Number.isFinite(stated) && stated > 0 ? stated : 1;\n}\n\n/**\n * Split a line total over a whole quantity so the lines add up to it EXACTLY:\n * one row at `total / quantity` when it divides; otherwise `quantity - 1`\n * units at the floor and one unit carrying the remainder, under the same SKU\n * (R$ 10.00 over 3 is 3.33 × 2 + 3.34).\n */\nfunction splitWhole(total: number, quantity: number): { quantity: number; unitPriceCents: number }[] {\n const floor = Math.floor(total / quantity);\n const remainder = total - floor * quantity;\n if (remainder === 0) return [{ quantity, unitPriceCents: floor }];\n const rest = quantity === 1 ? [] : [{ quantity: quantity - 1, unitPriceCents: floor }];\n return [...rest, { quantity: 1, unitPriceCents: floor + remainder }];\n}\n\n/**\n * One `Order.items[]` entry → its lines, which always add up to the line's\n * total ({@link lineTotalCents}). A whole quantity is split by\n * {@link splitWhole}; a fractional one (500 g as `0.5 KG`) is one line at its\n * total, the weight in the note.\n *\n * A line with no `externalCode` keys on the item id, then the name: an\n * unmapped line is recoverable, a dropped one is not. ESTIMATED: whether the\n * item id is stable across orders is not pinned by the spec; if it is per\n * order, each such order adds an unmapped SKU row.\n */\nfunction readLines(item: unknown): NormalizedOrderLine[] {\n const name = firstString(item, [[\"name\"]]);\n const sku = firstString(item, [[\"externalCode\"], [\"id\"]]) ?? name;\n if (!sku) return [];\n const quantity = quantityOf(item);\n const whole = Number.isInteger(quantity);\n const fraction = whole ? null : `${quantity} ${firstString(item, [[\"unit\"]]) ?? \"\"}`.trim();\n const total = lineTotalCents(item, quantity);\n const parts = whole ? splitWhole(total, quantity) : [{ quantity: 1, unitPriceCents: total }];\n const note = lineNote(item, fraction);\n return parts.map((part) => ({ externalSku: sku, name: name ?? sku, ...part, note }));\n}\n\n/** `DELIVERY` or `TAKEOUT`; `INDOOR` (eaten at the store) is neither, so unstated. */\nfunction readOrderType(order: unknown): MarketplaceOrderType | null {\n const stated = firstString(order, [[\"type\"]])?.toUpperCase();\n return stated === \"DELIVERY\" || stated === \"TAKEOUT\" ? stated : null;\n}\n\nfunction readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {\n const stated = firstString(order, [[\"delivery\", \"deliveredBy\"]])?.toUpperCase();\n return stated === \"MERCHANT\" || stated === \"MARKETPLACE\" ? stated : null;\n}\n\n/**\n * `delivery.deliveryAddress`. The spec's schema says `street`, `number`,\n * `district`; its own (commented) order example says `streetName`,\n * `streetNumber`, `neighborhood`. Both are read. The state is ISO 3166-2 by\n * recommendation (`BR-SP`), so the country prefix is dropped.\n */\nfunction readAddress(order: unknown, missingStreetNumber: string): NormalizedAddress | null {\n const raw = pick(order, \"delivery\", \"deliveryAddress\");\n const street = firstString(raw, [[\"street\"], [\"streetName\"]]);\n if (street === null) return null;\n return {\n street,\n number: firstString(raw, [[\"number\"], [\"streetNumber\"]]) ?? missingStreetNumber,\n neighborhood: firstString(raw, [[\"district\"], [\"neighborhood\"]]) ?? \"\",\n complement: firstString(raw, [[\"complement\"]]),\n reference: firstString(raw, [[\"reference\"]]),\n postalCode: firstString(raw, [[\"postalCode\"]])?.replace(/\\D/g, \"\") || null,\n city: firstString(raw, [[\"city\"]]),\n state: firstString(raw, [[\"state\"]])?.replace(/^[A-Z]{2}-/u, \"\") ?? null,\n };\n}\n\n/**\n * Normalize one `Order` (the answer of `GET /v1/orders/{orderId}`). Null when\n * it carries no id or no line.\n *\n * The total is `total.orderAmount`, \"the final value of the order (itemsPrice\n * + otherFees - discounts)\": the buyer's receipt, gross. Open Delivery's\n * `Order` states NO commission field, so `commissionCents` is null (\"did not\n * say\"), never 0; the marketplace's cut arrives with its statement.\n */\nexport function normalizeOpenDeliveryOrder(\n order: unknown,\n options: { missingStreetNumber: string },\n): NormalizedMarketplaceOrder | null {\n const externalOrderId = firstString(order, [[\"id\"]]);\n const rawItems = pick(order, \"items\");\n const lines = (Array.isArray(rawItems) ? rawItems : [])\n .flatMap(readLines);\n if (!externalOrderId || lines.length === 0) return null;\n return {\n provider: NINETY_NINE_FOOD_PROVIDER,\n externalOrderId,\n externalDisplayId: firstString(order, [[\"displayId\"]]),\n externalMerchantId: firstString(order, [[\"merchant\", \"id\"]]),\n buyer: {\n externalId: firstString(order, [[\"customer\", \"id\"]]),\n name: firstString(order, [[\"customer\", \"name\"]]),\n phone: firstString(order, [[\"customer\", \"phone\", \"number\"]]),\n },\n lines,\n // The line sum is the FALLBACK: the stated total carries the fees and\n // discounts the lines do not, and it is the number on the receipt.\n totalCents:\n firstCents(order, [[\"total\", \"orderAmount\", \"value\"]]) ??\n lines.reduce((sum, line) => sum + line.unitPriceCents * line.quantity, 0),\n commissionCents: null,\n deliveryDueAt: firstDate(order, [\n [\"delivery\", \"estimatedDeliveryDateTime\"],\n [\"takeout\", \"takeoutDateTime\"],\n [\"schedule\", \"scheduledDateTimeEnd\"],\n ]),\n placedAt: firstDate(order, [[\"createdAt\"]]) ?? new Date(),\n orderType: readOrderType(order),\n deliveredBy: readDeliveredBy(order),\n deliveryAddress: readAddress(order, options.missingStreetNumber),\n };\n}\n","import {\n answered,\n outboundResultOf,\n tokenGrantResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type FetchOrderResult,\n type MarketplaceHttpResponse,\n type OutboundOrderRef,\n type OutboundResult,\n} from \"../core/adapter\";\nimport { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryOrder } from \"./normalize\";\n\n/**\n * The 99Food adapter's OUTBOUND half, on Open Delivery v1.7.1: the OAuth\n * grant, the order fetch, confirm and requestCancellation. Paths, verbs,\n * bodies and answers are the spec's; the job that calls these, its retries\n * and what a failure shows are the engine's.\n *\n * The one thing the spec cannot pin is WHERE: Open Delivery standardizes the\n * paths under each Ordering Application's own base URL, and 99Food gives its\n * base URLs to a partner at onboarding. So the base URL per environment is\n * the adapter's REQUIRED config, never a guessed default. Tests never reach\n * 99Food: the HTTP client is the host's port, answered by a fake.\n */\n\n/** Where 99Food serves Open Delivery, per environment (given at partner onboarding). */\nexport type NinetyNineFoodApiBaseUrls = Readonly<Record<\"SANDBOX\" | \"PRODUCTION\", string>>;\n\n/** A token is renewed this long before it expires. */\nconst TOKEN_MARGIN_MS = 60_000;\n/** `expires_in` is optional in the spec's `TokenResponse`; an hour when absent. ESTIMATED. */\nconst DEFAULT_TOKEN_SECONDS = 3600;\n\n/** The base URL with its trailing slashes cut, by a loop: a `/\\/+$/` regex backtracks polynomially on many slashes. */\nexport function baseOf(ctx: AdapterCallContext, bases: NinetyNineFoodApiBaseUrls): string {\n const base = bases[ctx.environment];\n let end = base.length;\n while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;\n return base.slice(0, end);\n}\nexport const tokenKey = (ctx: AdapterCallContext): string =>\n `${NINETY_NINE_FOOD_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** The spec's `TokenResponse` (`access_token`, `token_type`, `expires_in`), read defensively. */\nfunction tokenOf(body: string): { token: string; expiresInSeconds: number } | null {\n try {\n const parsed = JSON.parse(body) as { access_token?: unknown; expires_in?: unknown };\n if (typeof parsed.access_token !== \"string\" || parsed.access_token === \"\") return null;\n const expires =\n typeof parsed.expires_in === \"number\" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;\n return { token: parsed.access_token, expiresInSeconds: expires };\n } catch {\n return null;\n }\n}\n\n/**\n * A bearer token from the per-process cache, or a fresh `client_credentials`\n * grant (`POST /oauth/token`, form-encoded `client_id`, `client_secret`,\n * `grant_type`). Keyed by environment and client id; memory only.\n */\nexport async function bearer(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n): Promise<{ token: string } | Exclude<OutboundResult, { kind: \"accepted\" }>> {\n const cached = ctx.tokens.get(tokenKey(ctx));\n if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };\n const response = await ctx.http({\n method: \"POST\",\n url: `${baseOf(ctx, bases)}/oauth/token`,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n client_id: ctx.credentials.clientId,\n client_secret: ctx.credentials.clientSecret,\n grant_type: \"client_credentials\",\n }).toString(),\n });\n if (response.status < 200 || response.status >= 300) {\n const result = tokenGrantResultOf(response);\n return result.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected token answer\" } : result;\n }\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: \"99Food answered the token grant without a token\" };\n ctx.tokens.set(tokenKey(ctx), { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });\n return { token: token.token };\n}\n\n/** One authenticated call to an order's resource, the raw answer or the result that ends it. */\nasync function callOrder(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n request: { method: \"GET\" | \"POST\"; externalOrderId: string; action: string | null; body?: unknown },\n): Promise<MarketplaceHttpResponse | Exclude<OutboundResult, { kind: \"accepted\" }>> {\n const auth = await bearer(ctx, bases);\n if (!(\"token\" in auth)) return auth;\n const suffix = request.action === null ? \"\" : `/${request.action}`;\n const response = await ctx.http({\n method: request.method,\n url: `${baseOf(ctx, bases)}/v1/orders/${encodeURIComponent(request.externalOrderId)}${suffix}`,\n headers: {\n Authorization: `Bearer ${auth.token}`,\n ...(request.body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),\n });\n // A 401 is a token that went stale under us: forget it, and the retry fetches another.\n if (response.status !== 401) return response;\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"99Food refused the token\" };\n}\n\n/** Whether a 422 answer's `CancellationError.cancellationStatus` says the order is already cancelled. */\nfunction alreadyCancelled(response: MarketplaceHttpResponse): boolean {\n if (response.status !== 422) return false;\n try {\n return (JSON.parse(response.body) as { cancellationStatus?: unknown }).cancellationStatus === \"CANCELLED\";\n } catch {\n return false;\n }\n}\n\n/** {@link answered} for a fetch: a call that never got an answer is a retry. */\nasync function fetched(call: () => Promise<FetchOrderResult>): Promise<FetchOrderResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/** `GET /v1/orders/{orderId}`: the order an event announced, normalized. A 404 is an expired order: refused. */\nexport function openDeliveryFetchOrder(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n order: { externalOrderId: string },\n options: { missingStreetNumber: string },\n): Promise<FetchOrderResult> {\n return fetched(async () => {\n const response = await callOrder(ctx, bases, { method: \"GET\", externalOrderId: order.externalOrderId, action: null });\n if (\"kind\" in response) return response;\n const result = outboundResultOf(response);\n if (result.kind !== \"accepted\") return result;\n let body: unknown;\n try {\n body = JSON.parse(response.body);\n } catch {\n return { kind: \"refused\", status: response.status, message: \"the order is not JSON\" };\n }\n const normalized = normalizeOpenDeliveryOrder(body, options);\n return normalized\n ? { kind: \"order\", order: normalized }\n : { kind: \"refused\", status: response.status, message: \"the order carries no id or no line\" };\n });\n}\n\n/**\n * `POST /v1/orders/{orderId}/confirm` with the spec's `OrderConfirmed`:\n * `orderExternalCode` (the host's own order id) and `createdAt`, plus the\n * `preparationTime` in minutes when the store stated one. The spec describes\n * `createdAt` with the ORDER's creation text (a copy of another schema's), so\n * it is sent as the moment of the confirmation: ESTIMATED.\n *\n * Every 422 is a refusal. It is the spec's generic `UnprocessableEntity`\n * (\"unable to process the contained instructions. (Check if the instruction\n * has not been sent before.)\"), and its body cannot tell a duplicate from a\n * cancelled order. So a retried confirm whose first answer was lost reads\n * \"não confirmou\" with the app link — a false alarm a person dismisses on\n * 99Food — and a confirm 99Food truly refused is never stamped confirmed.\n */\nexport function openDeliveryConfirm(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n): Promise<OutboundResult> {\n return answered(async () => {\n const response = await callOrder(ctx, bases, {\n method: \"POST\",\n externalOrderId: order.externalOrderId,\n action: \"confirm\",\n body: {\n orderExternalCode: order.hostOrderCode,\n createdAt: ctx.now.toISOString(),\n ...(input.preparationMinutes === null ? {} : { preparationTime: input.preparationMinutes }),\n },\n });\n if (\"kind\" in response) return response;\n return outboundResultOf(response);\n });\n}\n\n/**\n * `POST /v1/orders/{orderId}/requestCancellation` with the spec's\n * `RequestCancelled`: `reason` (free text: the store's, else the label),\n * `code` (one of the spec's codes) and `mode` (`MANUAL` or `AUTO`). 202 means\n * taken; the outcome is a later `CANCELLED` or `CANCELLATION_REQUEST_DENIED`\n * event. A 422 whose `cancellationStatus` is `CANCELLED` means the order is\n * cancelled already, which is what the request wanted.\n *\n * `outOfStockItems` is not sent: the spec wants the ITEM ids (uuids) there,\n * and the engine keeps the marketplace's SKUs (`externalCode`), which the SKU\n * map is keyed on. The field is optional.\n */\nexport function openDeliveryRequestCancellation(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n): Promise<OutboundResult> {\n return answered(async () => {\n const response = await callOrder(ctx, bases, {\n method: \"POST\",\n externalOrderId: order.externalOrderId,\n action: \"requestCancellation\",\n body: { reason: input.text === \"\" ? input.reason.label : input.text, code: input.reason.code, mode: input.mode },\n });\n if (\"kind\" in response) return response;\n if (alreadyCancelled(response)) return { kind: \"accepted\" };\n const result = outboundResultOf(response);\n // Open Delivery's 400 is a malformed request (a bad id or body: ours);\n // its 422 is the business answer and stays a refusal.\n return result.kind === \"refused\" && result.status === 400 ? { ...result, own: true } : result;\n });\n}\n","import { answered, outboundResultOf, type OutboundResult } from \"../core/adapter\";\nimport { stableUuid } from \"../core/catalogue-ids\";\nimport type { CatalogueCallContext, CatalogueMenuEntry, CatalogueMenuOptions, PullCatalogue } from \"../core/catalogue-port\";\nimport { baseOf, bearer, tokenKey, type NinetyNineFoodApiBaseUrls } from \"./outbound\";\n\n/**\n * The 99Food adapter's CATALOGUE half, on Open Delivery v1.7.1: PULL (FUT-4768).\n *\n * In Open Delivery the store's software does not write the menu to the\n * marketplace. The SOFTWARE SERVICE (the host) serves `GET /v1/merchant`, a\n * `Merchant` document carrying `menus`, `categories`, `items` and\n * `itemOffers` (the price lives on the offer), and the ORDERING APPLICATION\n * (99Food) pulls it, again when its `TTL` runs out or when told the merchant\n * changed (`POST /v1/merchantUpdate`, sent with an empty body: \"pull\n * everything again\"). Spec: https://abrasel-nacional.github.io/opendelivery/openapi.yaml\n *\n * So the adapter does two things: build the menu part of that document from\n * the items the store switched on (`menuDocument`, pure; the host merges it\n * into the rest of the `Merchant`, which is its own: `basicInfo`, `services`,\n * `lastUpdate`, `TTL`, `status`), and tell 99Food the menu changed\n * (`notifyMenuChanged`).\n *\n * ESTIMATED, to be checked once 99Food grants partner access:\n * - the path: the spec's route table and prose name `POST /merchantUpdate`\n * (`/v1/merchantUpdate`), while its path key is `/v1/menuUpdated`; this\n * sends the prose's;\n * - the `X-App-MerchantId` header on it: the operation lists none, and one\n * client app may serve many merchants, so it is sent to name which;\n * - that 99Food reads the whole `Merchant` on that notification (scenario 1\n * of the operation) rather than needing `entityType`/`updatedObjects`.\n *\n * Every id in the document is a UUID the software generates (the spec's\n * `format: uuid`), derived from the publication's stable reference, so the\n * same product keeps the same ids across pulls.\n */\n\n/** One category per host category name, in first-seen order. */\nfunction categoriesOf(merchantId: string, entries: readonly CatalogueMenuEntry[]) {\n const byName = new Map<string, { id: string; name: string; offers: string[] }>();\n for (const entry of entries) {\n const name = entry.categoryName.trim();\n const category = byName.get(name) ?? { id: stableUuid(`${merchantId}:category:${name}`), name, offers: [] };\n category.offers.push(stableUuid(`${entry.ref}:offer`));\n byName.set(name, category);\n }\n return [...byName.values()];\n}\n\n/** The menu part of Open Delivery's `Merchant`: `menus`, `categories`, `items`, `itemOffers`. */\nexport function openDeliveryMenuDocument(input: {\n externalMerchantId: string;\n entries: readonly CatalogueMenuEntry[];\n options: CatalogueMenuOptions;\n}) {\n const { externalMerchantId: merchantId, entries, options } = input;\n const categories = categoriesOf(merchantId, entries);\n return {\n menus: [\n {\n id: stableUuid(`${merchantId}:menu`),\n name: options.menuName,\n externalCode: \"menu\",\n categoryId: categories.map((category) => category.id),\n },\n ],\n categories: categories.map((category, index) => ({\n id: category.id,\n index,\n name: category.name,\n externalCode: category.name,\n status: \"AVAILABLE\",\n itemOfferId: category.offers,\n })),\n items: entries.map((entry) => ({\n id: stableUuid(`${entry.ref}:item`),\n name: entry.name,\n description: entry.description ?? \"\",\n externalCode: entry.productId,\n status: \"AVAILABLE\",\n unit: \"UN\",\n ...(entry.imageUrl === null ? {} : { image: { URL: entry.imageUrl } }),\n })),\n itemOffers: entries.map((entry, index) => {\n const value = Math.round(entry.priceCents) / 100;\n return {\n id: stableUuid(`${entry.ref}:offer`),\n itemId: stableUuid(`${entry.ref}:item`),\n index,\n status: \"AVAILABLE\",\n price: { value, originalValue: value, currency: options.currency },\n };\n }),\n };\n}\n\n/** `POST /v1/merchantUpdate` with no body: 99Food pulls the whole `Merchant` again. 200 or 204. */\nasync function notify(ctx: CatalogueCallContext, bases: NinetyNineFoodApiBaseUrls): Promise<OutboundResult> {\n const auth = await bearer(ctx, bases);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"POST\",\n url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,\n headers: { Authorization: `Bearer ${auth.token}`, \"X-App-MerchantId\": ctx.externalMerchantId },\n });\n if (response.status !== 401) return outboundResultOf(response);\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"99Food refused the token\" };\n}\n\n/** 99Food's catalogue capability, for the base URLs it was given. */\nexport function openDeliveryCatalogue(bases: NinetyNineFoodApiBaseUrls): PullCatalogue {\n return {\n mode: \"pull\",\n menuDocument: openDeliveryMenuDocument,\n notifyMenuChanged: (ctx) => answered(() => notify(ctx, bases)),\n };\n}\n","import { answered, outboundResultOf, type AdapterCallContext, type OutboundResult } from \"../core/adapter\";\nimport type { MarketplaceAvailability } from \"../core/pause-port\";\nimport { baseOf, bearer, tokenKey, type NinetyNineFoodApiBaseUrls } from \"./outbound\";\n\n/**\n * 99Food's half of the store pause (FUT-4851), on Open Delivery v1.7.1: the\n * software PUSHES the merchant's status to the Ordering Application.\n *\n * `POST /v1/merchantUpdate` (host: the Ordering Application, OAuth2 `od.all`)\n * \"sent with only the `merchantStatus` field ... will force the opening or\n * closing of the merchant within the Ordering Application\"; `merchantStatus`\n * is `AVAILABLE | UNAVAILABLE`, \"only use this type when you must close\n * (disable) the merchant due to an unexpected event and you don't know when\n * the service will be re-established\"; 204 (200 \"for compatibility\"), 400,\n * 401, 403, 404, 503 (openapi.yaml v1.7.1, README \"Pausing a store\").\n *\n * A SWITCH, with no id and no end, so offered only when the host opts in\n * (`pauseByStoreSwitch`; see `../core/pause-port.ts`). ESTIMATED: the path\n * (the spec files this webhook under the key `/v1/menuUpdated` while its own\n * description and route table say `POST /v1/merchantUpdate`; the latter is\n * sent), that 99Food implements it at all, and that the token names the\n * merchant (Open Delivery authenticates per merchant, so the body names none).\n */\n\n/** Set the merchant's status. */\nexport function openDeliverySetMerchantStatus(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n status: \"AVAILABLE\" | \"UNAVAILABLE\",\n): Promise<OutboundResult> {\n return answered(async () => {\n const auth = await bearer(ctx, bases);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"POST\",\n url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,\n headers: { Authorization: `Bearer ${auth.token}`, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ merchantStatus: status }),\n });\n if (response.status !== 401) return outboundResultOf(response);\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"99Food refused the token\" };\n });\n}\n\n/** 99Food's availability capability: Open Delivery's merchant status, a switch. */\nexport function openDeliveryAvailability(bases: NinetyNineFoodApiBaseUrls): MarketplaceAvailability {\n return {\n kind: \"switch\",\n pause: async (ctx, request) => {\n const result = await openDeliverySetMerchantStatus(ctx, bases, \"UNAVAILABLE\");\n return result.kind === \"accepted\" ? { kind: \"paused\", externalId: null, until: request.until } : result;\n },\n resume: (ctx) => openDeliverySetMerchantStatus(ctx, bases, \"AVAILABLE\"),\n };\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport {\n NINETY_NINE_FOOD_REASON_CODES,\n type NinetyNineFoodAdapterCopy,\n type NinetyNineFoodReasonCode,\n} from \"./copy\";\nimport { openDeliveryCatalogue } from \"./catalogue\";\nimport { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryEvent, verifyOpenDeliverySignature } from \"./normalize\";\nimport {\n openDeliveryConfirm,\n openDeliveryFetchOrder,\n openDeliveryRequestCancellation,\n type NinetyNineFoodApiBaseUrls,\n} from \"./outbound\";\nimport { openDeliveryAvailability } from \"./pause\";\n\n/**\n * `@12-apps/marketplace/99food` — 99Food, as one adapter on the engine.\n *\n * 99Food completed Open Delivery (Abrasel) adherence, so this adapter speaks\n * Open Delivery v1.7.1: the signed webhook, `CREATED` → fetch the order,\n * confirm, requestCancellation with the spec's codes. Everything 99Food is\n * under this folder; the engine reaches it only through the\n * {@link MarketplaceAdapter} port, and registering it is the whole cost:\n *\n * ```ts\n * import { createNinetyNineFoodAdapter } from \"@12-apps/marketplace/99food\";\n * import { NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/99food/pt-BR\";\n *\n * createMarketplaceEngine({\n * …ports,\n * adapters: [\n * createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR }),\n * createNinetyNineFoodAdapter({ copy: NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR, apiBaseUrl, portalUrl }),\n * ],\n * });\n * ```\n *\n * Its webhook is the engine's one route, `POST\n * /webhooks/marketplace/:tenantSlug/NINETY_NINE_FOOD`.\n */\n\nexport { NINETY_NINE_FOOD_PROVIDER } from \"./normalize\";\n\n/** How long 99Food may take to answer a cancellation request. ESTIMATED: the spec names no deadline. */\nexport const NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;\n\n/** The one reason that means \"an item is unavailable\". */\nconst ITEM_UNAVAILABLE: NinetyNineFoodReasonCode = \"UNAVAILABLE_ITEM\";\n\nexport interface NinetyNineFoodAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: NinetyNineFoodAdapterCopy;\n /**\n * Where 99Food serves Open Delivery, per environment: the base the spec's\n * paths (`/oauth/token`, `/v1/orders/…`) hang from. Given to a partner at\n * onboarding and not public, so required and defaultless. https only.\n */\n apiBaseUrl: NinetyNineFoodApiBaseUrls;\n /**\n * Where \"open it on 99Food\" goes: the merchant portal. Open Delivery names no\n * per-order deep link, so the link is the portal. Required; https only.\n */\n portalUrl: string;\n /**\n * OPTIONAL, off by default. Offer the store pause (FUT-4851) through Open\n * Delivery's `merchantStatus`, a store-wide switch with no id: a store the\n * owner also closed by hand on 99Food during the kitchen's pause is opened\n * with it. A host turns this on knowing that.\n */\n pauseByStoreSwitch?: boolean;\n}\n\nfunction assertHttps(name: string, url: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`@12-apps/marketplace/99food: ${name} is not a URL.`);\n }\n if (parsed.protocol !== \"https:\") throw new Error(`@12-apps/marketplace/99food: ${name} must be https.`);\n}\n\n/** Build the 99Food adapter. Its reasons are static: a dialog never waits on 99Food. */\nexport function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig): MarketplaceAdapter {\n assertHttps(\"apiBaseUrl.SANDBOX\", config.apiBaseUrl.SANDBOX);\n assertHttps(\"apiBaseUrl.PRODUCTION\", config.apiBaseUrl.PRODUCTION);\n assertHttps(\"portalUrl\", config.portalUrl);\n const bases = { ...config.apiBaseUrl };\n const reasons: readonly CancellationReason[] = NINETY_NINE_FOOD_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === ITEM_UNAVAILABLE,\n // `outOfStockItems` is optional in the spec (see `./outbound.ts`).\n needsItems: false,\n }));\n const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };\n return {\n provider: NINETY_NINE_FOOD_PROVIDER,\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n // The spec lets a merchant request a cancellation before or after the\n // confirm (\"rules may vary depending on the timing\"); the answer says.\n cancelAfterAccept: true,\n // 202, then a CANCELLED or CANCELLATION_REQUEST_DENIED event.\n asyncCancellationOutcome: true,\n perOrderAppLink: false,\n // `OrderConfirmed.preparationTime`, in minutes.\n confirmTakesPreparationTime: true,\n cancellationAnswerWindowMs: NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS,\n },\n normalize: normalizeOpenDeliveryEvent,\n readSignature: (header) => header(\"x-app-signature\"),\n verifySignature: verifyOpenDeliverySignature,\n cancellationReasons: () => reasons,\n // PULL: 99Food reads the menu the host serves (`GET /v1/merchant`) and is told when it changed (FUT-4768).\n catalogue: openDeliveryCatalogue(bases),\n fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx, bases, order, normalizeOptions),\n confirm: (ctx, order, input) => openDeliveryConfirm(ctx, bases, order, input),\n requestCancellation: (ctx, order, input) => openDeliveryRequestCancellation(ctx, bases, order, input),\n appLink: () => config.portalUrl,\n ...(config.pauseByStoreSwitch ? { availability: openDeliveryAvailability(bases) } : {}),\n };\n}\n\nexport {\n NINETY_NINE_FOOD_REASON_CODES,\n type NinetyNineFoodAdapterCopy,\n type NinetyNineFoodReasonCode,\n} from \"./copy\";\nexport { normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, verifyOpenDeliverySignature } from \"./normalize\";\nexport type { NinetyNineFoodApiBaseUrls } from \"./outbound\";\nexport { openDeliveryCatalogue, openDeliveryMenuDocument } from \"./catalogue\";\nexport { openDeliveryAvailability, openDeliverySetMerchantStatus } from \"./pause\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAcO,IAAM,gCAAgC;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACSO,IAAM,4BAA4B;AAGzC,IAAM,UAAU;AAEhB,IAAM,YAAY;AAElB,IAAM,8BAA8B;AAa7B,SAAS,4BACd,SACA,WACA,eACS;AACT,MAAI,CAAC,cAAe,QAAO;AAC3B,SAAO,oBAAoB,SAAS,WAAW,aAAa;AAC9D;AAPgB;AAsBT,SAAS,2BAA2B,SAA0C;AACnF,QAAM,kBAAkB,YAAY,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC;AAC1D,MAAI,CAAC,gBAAiB,QAAO;AAC7B,QAAM,aAAa,YAAY,SAAS,CAAC,CAAC,WAAW,CAAC,CAAC,KAAK,WAAW,YAAY;A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ACT,GAAI,OAAO,qBAAqB,EAAE,cAAc,yBAAyB,KAAK,EAAE,IAAI,CAAC;AAAA,EACvF;AACF;AAxCgB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/99food/copy.ts","../../src/99food/normalize.ts","../../src/99food/outbound.ts","../../src/99food/catalogue.ts","../../src/99food/pause.ts","../../src/99food/index.ts"],"sourcesContent":["import { OPEN_DELIVERY_MERCHANT_REASON_CODES } from \"../open-delivery/reasons\";\n\n/**\n * The words the 99Food adapter needs from its host, and nothing else.\n *\n * Required and defaultless, like every copy port in this repo: the adapter\n * ships no language of its own. Two packs sit beside it (`./pt-BR`,\n * `./en-US`); a host passes one by hand, or its own.\n */\n\n/** The cancellation codes a merchant may send: Open Delivery v1.7.1's (`../open-delivery/reasons.ts`). */\nexport const NINETY_NINE_FOOD_REASON_CODES = OPEN_DELIVERY_MERCHANT_REASON_CODES;\n\nexport type NinetyNineFoodReasonCode = (typeof NINETY_NINE_FOOD_REASON_CODES)[number];\n\nexport interface NinetyNineFoodAdapterCopy {\n /** One label per reason code. Sent as the request's `reason` text when the store wrote none. */\n reasonLabels: Readonly<Record<NinetyNineFoodReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import type { NormalizedEvent, NormalizedMarketplaceOrder } from \"../core/types\";\nimport { normalizeOpenDeliveryEventAs, normalizeOpenDeliveryOrderAs } from \"../open-delivery/normalize\";\n\n/**\n * The 99Food adapter's INBOUND half: Open Delivery v1.7.1's readers\n * (`../open-delivery/normalize.ts`), stamped with 99Food's provider id. 99Food\n * departs from the standard in nothing inbound: the `X-App-Signature` is the\n * standard's lowercase-hex HMAC-SHA256 of the body.\n */\n\n/** The provider id 99Food is registered under. Uppercase: the column's CHECK holds that shape. */\nexport const NINETY_NINE_FOOD_PROVIDER = \"NINETY_NINE_FOOD\";\n\nexport { verifyOpenDeliverySignature } from \"../open-delivery/normalize\";\n\n/** Normalize one webhook `Event` (see `normalizeOpenDeliveryEventAs`). Null only when it names no order. */\nexport function normalizeOpenDeliveryEvent(payload: unknown): NormalizedEvent | null {\n return normalizeOpenDeliveryEventAs(NINETY_NINE_FOOD_PROVIDER, payload);\n}\n\n/** Normalize one `Order` (see `normalizeOpenDeliveryOrderAs`). Null when it carries no id or no line. */\nexport function normalizeOpenDeliveryOrder(\n order: unknown,\n options: { missingStreetNumber: string },\n): NormalizedMarketplaceOrder | null {\n return normalizeOpenDeliveryOrderAs(NINETY_NINE_FOOD_PROVIDER, order, options);\n}\n","import type { OpenDeliveryApiBaseUrls, OpenDeliveryDialect } from \"../open-delivery/client\";\nimport { NINETY_NINE_FOOD_PROVIDER } from \"./normalize\";\n\n/**\n * 99Food's Open Delivery DIALECT: v1.7.1 as the standard writes it. The calls\n * themselves (the grant, the order fetch, confirm, requestCancellation, the\n * status steps) are `../open-delivery/`'s; this file only says where and how\n * 99Food takes them.\n *\n * - Token: `POST /oauth/token`, form-encoded `client_id`, `client_secret`,\n * `grant_type=client_credentials`.\n * - Bodies: plain JSON; no request signature.\n *\n * The one thing the spec cannot pin is WHERE: Open Delivery standardizes the\n * paths under each Ordering Application's own base URL, and 99Food gives its\n * base URLs to a partner at onboarding. So the base URL per environment is\n * the adapter's REQUIRED config, never a guessed default.\n */\n\n/** Where 99Food serves Open Delivery, per environment (given at partner onboarding). */\nexport type NinetyNineFoodApiBaseUrls = OpenDeliveryApiBaseUrls;\n\n/** 99Food's dialect, for the base URLs it was given. */\nexport function ninetyNineFoodDialect(bases: NinetyNineFoodApiBaseUrls): OpenDeliveryDialect {\n return {\n provider: NINETY_NINE_FOOD_PROVIDER,\n name: \"99Food\",\n bases,\n tokenGrant: (ctx) => ({\n contentType: \"application/x-www-form-urlencoded\",\n body: new URLSearchParams({\n client_id: ctx.credentials.clientId,\n client_secret: ctx.credentials.clientSecret,\n grant_type: \"client_credentials\",\n }).toString(),\n }),\n serialize: (body) => JSON.stringify(body),\n };\n}\n","import type { PullCatalogue } from \"../core/catalogue-port\";\nimport { openDeliveryMenuDocument, openDeliveryMerchantUpdate } from \"../open-delivery/merchant\";\nimport { ninetyNineFoodDialect, type NinetyNineFoodApiBaseUrls } from \"./outbound\";\n\n/**\n * The 99Food adapter's CATALOGUE half, on Open Delivery v1.7.1: PULL (FUT-4768).\n *\n * In Open Delivery the store's software does not write the menu to the\n * marketplace. The SOFTWARE SERVICE (the host) serves `GET /v1/merchant`, a\n * `Merchant` document carrying `menus`, `categories`, `items` and\n * `itemOffers`, and the ORDERING APPLICATION (99Food) pulls it, again when its\n * `TTL` runs out or when told the merchant changed (`POST\n * /v1/merchantUpdate`, sent with an empty body: \"pull everything again\").\n * Spec: https://abrasel-nacional.github.io/opendelivery/openapi.yaml\n *\n * So the adapter does two things: build the menu part of that document from\n * the items the store switched on (`menuDocument`, pure, shared:\n * `../open-delivery/merchant.ts`; the host merges it into the rest of the\n * `Merchant`, which is its own: `basicInfo`, `services`, `lastUpdate`, `TTL`,\n * `status`), and tell 99Food the menu changed (`notifyMenuChanged`).\n *\n * ESTIMATED, to be checked once 99Food grants partner access:\n * - the path: the spec's route table and prose name `POST /merchantUpdate`\n * (`/v1/merchantUpdate`), while its path key is `/v1/menuUpdated`; this\n * sends the prose's;\n * - the `X-App-MerchantId` header on it: the operation lists none, and one\n * client app may serve many merchants, so it is sent to name which;\n * - that 99Food reads the whole `Merchant` on that notification (scenario 1\n * of the operation) rather than needing `entityType`/`updatedObjects`.\n */\n\nexport { openDeliveryMenuDocument } from \"../open-delivery/merchant\";\n\n/** 99Food's catalogue capability, for the base URLs it was given. */\nexport function openDeliveryCatalogue(bases: NinetyNineFoodApiBaseUrls): PullCatalogue {\n const dialect = ninetyNineFoodDialect(bases);\n return {\n mode: \"pull\",\n menuDocument: openDeliveryMenuDocument,\n // No body: 99Food pulls the whole `Merchant` again. 200 or 204.\n notifyMenuChanged: (ctx) =>\n openDeliveryMerchantUpdate(ctx, dialect, {\n path: \"/v1/merchantUpdate\",\n headers: { \"X-App-MerchantId\": ctx.externalMerchantId },\n }),\n };\n}\n","import type { AdapterCallContext, OutboundResult } from \"../core/adapter\";\nimport type { MarketplaceAvailability } from \"../core/pause-port\";\nimport { openDeliveryMerchantUpdate, openDeliverySwitchAvailability } from \"../open-delivery/merchant\";\nimport { ninetyNineFoodDialect, type NinetyNineFoodApiBaseUrls } from \"./outbound\";\n\n/**\n * 99Food's half of the store pause (FUT-4851), on Open Delivery v1.7.1: the\n * software PUSHES the merchant's status to the Ordering Application.\n *\n * `POST /v1/merchantUpdate` (host: the Ordering Application, OAuth2 `od.all`)\n * \"sent with only the `merchantStatus` field ... will force the opening or\n * closing of the merchant within the Ordering Application\"; `merchantStatus`\n * is `AVAILABLE | UNAVAILABLE`, \"only use this type when you must close\n * (disable) the merchant due to an unexpected event and you don't know when\n * the service will be re-established\"; 204 (200 \"for compatibility\"), 400,\n * 401, 403, 404, 503 (openapi.yaml v1.7.1, README \"Pausing a store\").\n *\n * A SWITCH, with no id and no end, so offered only when the host opts in\n * (`pauseByStoreSwitch`; see `../core/pause-port.ts`). ESTIMATED: the path\n * (the spec files this webhook under the key `/v1/menuUpdated` while its own\n * description and route table say `POST /v1/merchantUpdate`; the latter is\n * sent), that 99Food implements it at all, and that the token names the\n * merchant (Open Delivery authenticates per merchant, so the body names none).\n */\n\n/** Set the merchant's status. */\nexport function openDeliverySetMerchantStatus(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n status: \"AVAILABLE\" | \"UNAVAILABLE\",\n): Promise<OutboundResult> {\n return openDeliveryMerchantUpdate(ctx, ninetyNineFoodDialect(bases), {\n path: \"/v1/merchantUpdate\",\n body: { merchantStatus: status },\n });\n}\n\n/** 99Food's availability capability: Open Delivery's merchant status, a switch. */\nexport function openDeliveryAvailability(bases: NinetyNineFoodApiBaseUrls): MarketplaceAvailability {\n return openDeliverySwitchAvailability((ctx, _merchantId, status) => openDeliverySetMerchantStatus(ctx, bases, status));\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport {\n openDeliveryConfirm,\n openDeliveryFetchOrder,\n openDeliveryRequestCancellation,\n openDeliveryStatus,\n} from \"../open-delivery/orders\";\nimport { assertHttpsUrl } from \"../open-delivery/client\";\nimport { OPEN_DELIVERY_ITEM_UNAVAILABLE } from \"../open-delivery/reasons\";\nimport { NINETY_NINE_FOOD_REASON_CODES, type NinetyNineFoodAdapterCopy } from \"./copy\";\nimport { openDeliveryCatalogue } from \"./catalogue\";\nimport { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, verifyOpenDeliverySignature } from \"./normalize\";\nimport { ninetyNineFoodDialect, type NinetyNineFoodApiBaseUrls } from \"./outbound\";\nimport { openDeliveryAvailability } from \"./pause\";\n\n/**\n * `@12-apps/marketplace/99food` — 99Food, as one adapter on the engine.\n *\n * 99Food completed Open Delivery (Abrasel) adherence, so this adapter speaks\n * Open Delivery v1.7.1: the signed webhook, `CREATED` → fetch the order,\n * confirm, requestCancellation with the spec's codes. The standard's calls\n * and readers are `../open-delivery/`, shared with Keeta; what is 99Food's\n * (its dialect, its copy, its ESTIMATED choices) is under this folder; the engine reaches it only through the\n * {@link MarketplaceAdapter} port, and registering it is the whole cost:\n *\n * ```ts\n * import { createNinetyNineFoodAdapter } from \"@12-apps/marketplace/99food\";\n * import { NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/99food/pt-BR\";\n *\n * createMarketplaceEngine({\n * …ports,\n * adapters: [\n * createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR }),\n * createNinetyNineFoodAdapter({ copy: NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR, apiBaseUrl, portalUrl }),\n * ],\n * });\n * ```\n *\n * Its webhook is the engine's one route, `POST\n * /webhooks/marketplace/:tenantSlug/NINETY_NINE_FOOD`.\n */\n\nexport { NINETY_NINE_FOOD_PROVIDER } from \"./normalize\";\n\n/** How long 99Food may take to answer a cancellation request. ESTIMATED: the spec names no deadline. */\nexport const NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;\n\n/** 99Food serves `pickedUp` for a take-out (v1.7.1). */\nconst STATUS = openDeliveryStatus({ takeoutPickedUp: true });\n\nexport interface NinetyNineFoodAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: NinetyNineFoodAdapterCopy;\n /**\n * Where 99Food serves Open Delivery, per environment: the base the spec's\n * paths (`/oauth/token`, `/v1/orders/…`) hang from. Given to a partner at\n * onboarding and not public, so required and defaultless. https only.\n */\n apiBaseUrl: NinetyNineFoodApiBaseUrls;\n /**\n * Where \"open it on 99Food\" goes: the merchant portal. Open Delivery names no\n * per-order deep link, so the link is the portal. Required; https only.\n */\n portalUrl: string;\n /**\n * OPTIONAL, off by default. Offer the store pause (FUT-4851) through Open\n * Delivery's `merchantStatus`, a store-wide switch with no id: a store the\n * owner also closed by hand on 99Food during the kitchen's pause is opened\n * with it. A host turns this on knowing that.\n */\n pauseByStoreSwitch?: boolean;\n}\n\nconst assertHttps = (name: string, url: string): void => assertHttpsUrl(\"@12-apps/marketplace/99food\", name, url);\n\n/** Build the 99Food adapter. Its reasons are static: a dialog never waits on 99Food. */\nexport function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig): MarketplaceAdapter {\n assertHttps(\"apiBaseUrl.SANDBOX\", config.apiBaseUrl.SANDBOX);\n assertHttps(\"apiBaseUrl.PRODUCTION\", config.apiBaseUrl.PRODUCTION);\n assertHttps(\"portalUrl\", config.portalUrl);\n const dialect = ninetyNineFoodDialect({ ...config.apiBaseUrl });\n const bases = dialect.bases;\n const reasons: readonly CancellationReason[] = NINETY_NINE_FOOD_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === OPEN_DELIVERY_ITEM_UNAVAILABLE,\n // `outOfStockItems` is optional in the spec, and not sent (see `cancellation` below).\n needsItems: false,\n }));\n const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };\n const fetchOptions = { normalize: (order: unknown) => normalizeOpenDeliveryOrder(order, normalizeOptions) };\n // `outOfStockItems` wants 99Food's item uuids; the engine keeps SKUs (`externalCode`). Not sent.\n const cancellation = { outOfStockAsSkus: false };\n return {\n provider: NINETY_NINE_FOOD_PROVIDER,\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n // The spec lets a merchant request a cancellation before or after the\n // confirm (\"rules may vary depending on the timing\"); the answer says.\n cancelAfterAccept: true,\n // 202, then a CANCELLED or CANCELLATION_REQUEST_DENIED event.\n asyncCancellationOutcome: true,\n perOrderAppLink: false,\n // `OrderConfirmed.preparationTime`, in minutes.\n confirmTakesPreparationTime: true,\n cancellationAnswerWindowMs: NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS,\n // Open Delivery's readyForPickup, dispatch and delivered / pickedUp (`../open-delivery/orders.ts`).\n statusSteps: [\"READY\", \"DISPATCHED\", \"HANDED_OVER\"],\n },\n normalize: normalizeOpenDeliveryEvent,\n readSignature: (header) => header(\"x-app-signature\"),\n verifySignature: verifyOpenDeliverySignature,\n cancellationReasons: () => reasons,\n // PULL: 99Food reads the menu the host serves (`GET /v1/merchant`) and is told when it changed (FUT-4768).\n catalogue: openDeliveryCatalogue(bases),\n fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx, dialect, order, fetchOptions),\n confirm: (ctx, order, input) => openDeliveryConfirm(ctx, dialect, order, input),\n requestCancellation: (ctx, order, input) =>\n openDeliveryRequestCancellation(ctx, dialect, order, input, cancellation),\n statusSupported: STATUS.supported,\n informStatus: (ctx, order, facts) => STATUS.inform(ctx, dialect, order, facts),\n appLink: () => config.portalUrl,\n ...(config.pauseByStoreSwitch ? { availability: openDeliveryAvailability(bases) } : {}),\n };\n}\n\nexport {\n NINETY_NINE_FOOD_REASON_CODES,\n type NinetyNineFoodAdapterCopy,\n type NinetyNineFoodReasonCode,\n} from \"./copy\";\nexport { normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, verifyOpenDeliverySignature } from \"./normalize\";\nexport type { NinetyNineFoodApiBaseUrls } from \"./outbound\";\nexport { openDeliveryCatalogue, openDeliveryMenuDocument } from \"./catalogue\";\nexport { openDeliveryAvailability, openDeliverySetMerchantStatus } from \"./pause\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAWO,IAAM,gCAAgC;;;ACAtC,IAAM,4BAA4B;AAKlC,SAAS,2BAA2B,SAA0C;AACnF,SAAO,6BAA6B,2BAA2B,OAAO;AACxE;AAFgB;AAKT,SAAS,2BACd,OACA,SACmC;AACnC,SAAO,6BAA6B,2BAA2B,OAAO,OAAO;AAC/E;AALgB;;;ACET,SAAS,sBAAsB,OAAuD;AAC3F,SAAO;AAAA,IACL,UAAU;AAAA,IACV,MAAM;AAAA,IACN;AAAA,IACA,YAAY,wBAAC,SAAS;AAAA,MACpB,aAAa;AAAA,MACb,MAAM,IAAI,gBAAgB;AAAA,QACxB,WAAW,IAAI,YAAY;AAAA,QAC3B,eAAe,IAAI,YAAY;AAAA,QAC/B,YAAY;AAAA,MACd,CAAC,EAAE,SAAS;AAAA,IACd,IAPY;AAAA,IAQZ,WAAW,wBAAC,SAAS,KAAK,UAAU,IAAI,GAA7B;AAAA,EACb;AACF;AAfgB;;;ACWT,SAAS,sBAAsB,OAAiD;AACrF,QAAM,UAAU,sBAAsB,KAAK;AAC3C,SAAO;AAAA,IACL,MAAM;AAAA,IACN,cAAc;AAAA;AAAA,IAEd,mBAAmB,wBAAC,QAClB,2BAA2B,KAAK,SAAS;AAAA,MACvC,MAAM;AAAA,MACN,SAAS,EAAE,oBAAoB,IAAI,mBAAmB;AAAA,IACxD,CAAC,GAJgB;AAAA,EAKrB;AACF;AAZgB;;;ACRT,SAAS,8BACd,KACA,OACA,QACyB;AACzB,SAAO,2BAA2B,KAAK,sBAAsB,KAAK,GAAG;AAAA,IACnE,MAAM;AAAA,IACN,MAAM,EAAE,gBAAgB,OAAO;AAAA,EACjC,CAAC;AACH;AATgB;AAY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AAAA;AAAA,IAErB,WAAW,sBAAsB,KAAK;AAAA,IACtC,YAAY,wBAAC,KAAK,UAAU,uBAAuB,KAAK,SAAS,OAAO,YAAY,GAAxE;AAAA,IACZ,SAAS,wBAAC,KAAK,OAAO,UAAU,oBAAoB,KAAK,SAAS,OAAO,KAAK,GAArE;AAAA,IACT,qBAAqB,wBAAC,KAAK,OAAO,UAChC,gCAAgC,KAAK,SAAS,OAAO,OAAO,YAAY,GADrD;AAAA,IAErB,iBAAiB,OAAO;AAAA,IACxB,cAAc,wBAAC,KAAK,OAAO,UAAU,OAAO,OAAO,KAAK,SAAS,OAAO,KAAK,GAA/D;AAAA,IACd,SAAS,6BAAM,OAAO,WAAb;AAAA,IACT,GAAI,OAAO,qBAAqB,EAAE,cAAc,yBAAyB,KAAK,EAAE,IAAI,CAAC;AAAA,EACvF;AACF;AAjDgB;","names":[]}
|
|
@@ -543,6 +543,13 @@ interface NormalizedMarketplaceOrder {
|
|
|
543
543
|
* `FAILED` when it refused the request.
|
|
544
544
|
*/
|
|
545
545
|
type CancellationOutcome = "CONFIRMED" | "FAILED";
|
|
546
|
+
/**
|
|
547
|
+
* A step of the order's life a marketplace announces about an order it
|
|
548
|
+
* already has (FUT-4653): the courier left (`DISPATCHED`) or the order is
|
|
549
|
+
* finished (`CONCLUDED`). An event that names one moves nothing by itself; the
|
|
550
|
+
* engine asks the host to move the order forward (`onLifecycle`).
|
|
551
|
+
*/
|
|
552
|
+
type MarketplaceLifecycle = "DISPATCHED" | "CONCLUDED";
|
|
546
553
|
/** What an adapter makes of one inbound delivery. */
|
|
547
554
|
interface NormalizedEvent {
|
|
548
555
|
provider: MarketplaceProvider;
|
|
@@ -574,6 +581,12 @@ interface NormalizedEvent {
|
|
|
574
581
|
* the event. Ignored when `order` is present.
|
|
575
582
|
*/
|
|
576
583
|
orderToFetch?: boolean;
|
|
584
|
+
/**
|
|
585
|
+
* OPTIONAL. The lifecycle step this event announces about an order the
|
|
586
|
+
* engine already has. Absent or null: the event names none. An event that
|
|
587
|
+
* names one carries no order body.
|
|
588
|
+
*/
|
|
589
|
+
lifecycle?: MarketplaceLifecycle | null;
|
|
577
590
|
}
|
|
578
591
|
|
|
579
592
|
/**
|
|
@@ -651,6 +664,21 @@ interface MarketplaceCapabilities {
|
|
|
651
664
|
* the request as TIMEOUT. Absent: only the 24-hour give-up applies.
|
|
652
665
|
*/
|
|
653
666
|
cancellationAnswerWindowMs?: number;
|
|
667
|
+
/**
|
|
668
|
+
* OPTIONAL. The steps this marketplace can be told about (`informStatus`).
|
|
669
|
+
* Absent or empty: the engine tells it nothing.
|
|
670
|
+
*/
|
|
671
|
+
statusSteps?: readonly StatusStep[];
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* A step of the order the store tells the marketplace about (FUT-4653): the
|
|
675
|
+
* order is ready for pickup, the courier left, the order was handed over.
|
|
676
|
+
*/
|
|
677
|
+
type StatusStep = "READY" | "DISPATCHED" | "HANDED_OVER";
|
|
678
|
+
/** What a status call is told about the order: who carries it (null: a take-out, or unstated). */
|
|
679
|
+
interface StatusFacts {
|
|
680
|
+
step: StatusStep;
|
|
681
|
+
deliveredBy: MarketplaceDeliveredBy | null;
|
|
654
682
|
}
|
|
655
683
|
/** One reason a store may give for refusing or cancelling an order. */
|
|
656
684
|
interface CancellationReason {
|
|
@@ -746,6 +774,22 @@ interface MarketplaceAdapter {
|
|
|
746
774
|
}): Promise<OutboundResult>;
|
|
747
775
|
/** Ask the marketplace to cancel the order, with one of its own reasons. */
|
|
748
776
|
requestCancellation(ctx: AdapterCallContext, order: OutboundOrderRef, input: CancellationRequestInput): Promise<OutboundResult>;
|
|
777
|
+
/**
|
|
778
|
+
* OPTIONAL. Whether this marketplace takes this step for this kind of order,
|
|
779
|
+
* answered offline, with no call: the job asks it BEFORE it claims anything
|
|
780
|
+
* (an unsupported step leaves no row). Absent: every step in
|
|
781
|
+
* `capabilities.statusSteps` is taken for every order.
|
|
782
|
+
*/
|
|
783
|
+
statusSupported?(facts: StatusFacts): boolean;
|
|
784
|
+
/**
|
|
785
|
+
* OPTIONAL. Tell the marketplace the order reached a step (FUT-4653). Called
|
|
786
|
+
* only from the `marketplace.outbound` job, action `status`. `unsupported`
|
|
787
|
+
* (no endpoint for this step and this kind of order) ends the job with no
|
|
788
|
+
* row. Absent: the marketplace is told nothing.
|
|
789
|
+
*/
|
|
790
|
+
informStatus?(ctx: AdapterCallContext, order: OutboundOrderRef, facts: StatusFacts): Promise<OutboundResult | {
|
|
791
|
+
kind: "unsupported";
|
|
792
|
+
}>;
|
|
749
793
|
/**
|
|
750
794
|
* OPTIONAL. Fetch the order an event announced with `orderToFetch` (a
|
|
751
795
|
* marketplace whose events carry no order body). Called only from the
|
|
@@ -793,4 +837,4 @@ declare function tokenGrantResultOf(response: MarketplaceHttpResponse): Outbound
|
|
|
793
837
|
/** A call that never got an answer is a retry, with the reason a log can read. */
|
|
794
838
|
declare function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult>;
|
|
795
839
|
|
|
796
|
-
export { type
|
|
840
|
+
export { type NormalizedOrderLine as $, type AdapterCallContext as A, type CatalogueSnapshotCategory as B, type CatalogueMenuEntry as C, type CatalogueSnapshotItem as D, type CatalogueSnapshotOption as E, type CatalogueSnapshotOptionGroup as F, type CatalogueStoredImage as G, type CatalogueWarningCode as H, type FetchOrderResult as I, type MarketplaceCapabilities as J, type MarketplaceCatalogue as K, type MarketplaceCredentials as L, type MarketplaceAvailability as M, type NormalizedEvent as N, type OutboundResult as O, type PullCatalogue as P, type MarketplaceDeliveredBy as Q, type MarketplaceDiscountSponsor as R, type StorePauseRequest as S, type MarketplaceHttp as T, type MarketplaceHttpRequest as U, type MarketplaceHttpResponse as V, type MarketplaceLifecycle as W, type MarketplaceOrderType as X, type NormalizedAddress as Y, type NormalizedBuyer as Z, type NormalizedOrderDiscount as _, type NormalizedMarketplaceOrder as a, type OutboundOrderRef as a0, PROVIDER_ID_PATTERN as a1, type StatusFacts as a2, type StatusStep as a3, answered as a4, centsFromMajor as a5, outboundResultOf as a6, tokenGrantResultOf as a7, type CatalogueMenuOptions as b, type MarketplaceAdapter as c, type PushCatalogue as d, type CatalogueItemOut as e, type CatalogueReader as f, type StorePauseResult as g, type StorePauseRef as h, type MarketplaceProvider as i, type CancellationReason as j, type AdapterTokenCache as k, type CancellationOutcome as l, type CancellationRequestInput as m, type CatalogueCallContext as n, type CatalogueFailure as o, type CatalogueImage as p, type CatalogueItem as q, type CatalogueItemRef as r, type CataloguePublishResult as s, type CatalogueReadContext as t, type CatalogueReadNotice as u, type CatalogueReadRefusalCode as v, type CatalogueReadResult as w, type CatalogueReadWarning as x, type CatalogueReadWarningCode as y, type CatalogueSnapshot as z };
|
|
@@ -7,13 +7,13 @@ import {
|
|
|
7
7
|
listMarketplaceMenuLinksQuery,
|
|
8
8
|
upsertMarketplaceIntegrationsBody,
|
|
9
9
|
upsertMarketplaceMenuLinksBody
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-NP4EYKPO.js";
|
|
11
11
|
import {
|
|
12
12
|
AvailabilityRetryError,
|
|
13
13
|
CatalogueRetryError,
|
|
14
14
|
FetchOrderRetryError,
|
|
15
15
|
OutboundRetryError
|
|
16
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-BMCERPQX.js";
|
|
17
17
|
import {
|
|
18
18
|
__name
|
|
19
19
|
} from "./chunk-7QVYU63E.js";
|
|
@@ -99,7 +99,7 @@ async function handleWebhook(config, request) {
|
|
|
99
99
|
payload,
|
|
100
100
|
// A DISABLED connection still stores its deliveries and ingests nothing;
|
|
101
101
|
// the retry sweep ingests them if the store turns it back on.
|
|
102
|
-
settings: target.enabled ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds } : null
|
|
102
|
+
settings: target.enabled ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds, followStatus: target.followStatus } : null
|
|
103
103
|
});
|
|
104
104
|
if (outcome.kind === "failed") {
|
|
105
105
|
return { status: 500, body: { received: true, error: outcome.reason } };
|
|
@@ -473,4 +473,4 @@ export {
|
|
|
473
473
|
MARKETPLACE_JOBS,
|
|
474
474
|
createApiMarketplace
|
|
475
475
|
};
|
|
476
|
-
//# sourceMappingURL=chunk-
|
|
476
|
+
//# sourceMappingURL=chunk-6N2HEV3U.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/http.ts","../src/server/webhook.ts","../src/server/routes.ts","../src/server/jobs.ts","../src/server/index.ts"],"sourcesContent":["import type { z } from \"zod\";\n\nimport type { WireResponse } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceLogger } from \"../core/ports\";\nimport type { MarketplaceServerCopy } from \"./copy\";\n\n/**\n * What the route descriptors share: the config, the actor, and the two answer\n * shapes every handler uses.\n */\n\n/** Whoever the host resolved: the tenant this request may act inside. */\nexport interface MarketplaceActor {\n /** The tenant's id — every engine call is scoped to it. */\n clientId: string;\n /** The person, for the audit line an archive writes. Null for a system caller. */\n userId?: string | null;\n}\n\nexport interface MarketplaceApiConfig {\n /** The mounted engine (`createMarketplaceEngine`). */\n engine: MarketplaceEngine;\n /** Every sentence the routes answer a person with. Required, no defaults. */\n copy: MarketplaceServerCopy;\n /**\n * Which tenant a webhook's URL slug names, or null for none. The webhook is\n * unauthenticated by design (a marketplace cannot sign in), so the tenant\n * comes from the URL and is then proved by that tenant's signature secret.\n */\n tenantBySlug: (slug: string) => Promise<string | null>;\n /** Where the routes say what they refused. The manifest's `marketplace` namespace. */\n logger: MarketplaceLogger;\n}\n\n/** A 200 in the `{ data }` envelope. */\nexport function ok(data: unknown): WireResponse {\n return { status: 200, body: { data } };\n}\n\n/** A refusal in the `{ error }` envelope, with any extra fields beside it. */\nexport function refuse(status: number, error: string, extra: Record<string, unknown> = {}): WireResponse {\n return { status, body: { error, ...extra } };\n}\n\n/** The parsed value, or the 422 that names every problem and its path. */\nexport function parse<T>(\n schema: z.ZodType<T>,\n value: unknown,\n copy: MarketplaceServerCopy,\n): { ok: true; value: T } | { ok: false; response: WireResponse } {\n const parsed = schema.safeParse(value ?? {});\n if (parsed.success) return { ok: true, value: parsed.data };\n const problems = parsed.error.issues.map((issue) => ({\n path: issue.path.map((segment) => (typeof segment === \"number\" ? segment : String(segment))),\n code: \"INVALID_INPUT\",\n message: issue.message,\n }));\n return { ok: false, response: refuse(422, copy.invalidInput, { problems }) };\n}\n\n/** An ISO string, or null. */\nexport function iso(value: Date | null | undefined): string | null {\n return value ? value.toISOString() : null;\n}\n","import type { WireRequest, WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { IngestionTarget } from \"../core/integration\";\nimport type { MarketplaceApiConfig } from \"./http\";\n\n/**\n * `POST /webhooks/marketplace/:tenantSlug/:provider` — inbound deliveries for\n * ONE store, from any registered marketplace.\n *\n * PUBLIC by design (`kind: \"webhook\"`): a marketplace cannot authenticate as a\n * user. The store is attributed from the URL slug, then the delivery is\n * verified against THAT store's secret, through the provider's own adapter\n * (which header carries the signature, and how it is computed) — the route\n * itself knows no marketplace.\n *\n * It answers 2xx for almost everything, deliberately. A marketplace\n * redelivers on any non-2xx, so the only failures worth signalling are the\n * ones a redelivery could fix: a genuine processing failure answers 500, and\n * the inbox row it left is retried by the sweep regardless. Refusals (unknown\n * slug, no connection, bad signature) answer 401, indistinguishably, so a\n * prober cannot learn which stores exist. The bodies are machine codes: the\n * reader is a server, not a person.\n */\n\nconst UNAUTHORIZED: WireResponse = { status: 401, body: { error: \"unauthorized\" } };\n\n/**\n * The tenant the slug names and its connection to this marketplace, or the\n * 401 that ends the request. A blob that will not open is a 401 too, logged:\n * a key problem must never read as \"no secret configured\".\n */\nasync function connectionOf(\n config: MarketplaceApiConfig,\n tenantSlug: string,\n provider: string,\n): Promise<{ clientId: string; target: IngestionTarget } | WireResponse> {\n const clientId = await config.tenantBySlug(tenantSlug);\n if (!clientId) {\n config.logger.warn(`marketplace.webhook: unknown tenant slug \"${tenantSlug}\" (${provider})`);\n return UNAUTHORIZED;\n }\n try {\n const target = await config.engine.target(clientId, provider);\n // No connection at all: refused rather than stored — without one there is\n // no secret to verify against.\n return target ? { clientId, target } : UNAUTHORIZED;\n } catch (error) {\n config.logger.error(\n `marketplace.webhook: ${tenantSlug} ${provider} credentials do not open: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n return UNAUTHORIZED;\n }\n}\n\n/** The verified, parsed delivery, or the answer that ends the request. */\nasync function admit(\n config: MarketplaceApiConfig,\n request: WireRequest<unknown>,\n): Promise<{ clientId: string; provider: string; payload: unknown; target: IngestionTarget } | WireResponse> {\n const { tenantSlug = \"\", provider = \"\" } = request.params;\n const { engine } = config;\n if (!engine.knows(provider)) return { status: 404, body: { error: \"unknown_provider\" } };\n const raw = request.request;\n if (!raw) return { status: 400, body: { error: \"raw_request_required\" } };\n\n const connection = await connectionOf(config, tenantSlug, provider);\n if (\"status\" in connection) return connection;\n const rawBody = await raw.text();\n const signature = engine.readSignature(provider, (name) => raw.headers.get(name));\n if (!engine.verifySignature(provider, rawBody, signature, connection.target.webhookSecret)) {\n config.logger.warn(`marketplace.webhook: ${tenantSlug} ${provider} signature rejected`);\n return UNAUTHORIZED;\n }\n try {\n return { ...connection, provider, payload: JSON.parse(rawBody) as unknown };\n } catch {\n return { status: 400, body: { error: \"invalid_json\" } };\n }\n}\n\n/** Record and act on one verified delivery. */\nasync function handleWebhook(config: MarketplaceApiConfig, request: WireRequest<unknown>): Promise<WireResponse> {\n const admitted = await admit(config, request);\n if (\"status\" in admitted) return admitted;\n const { clientId, provider, payload, target } = admitted;\n const { engine } = config;\n\n const event = engine.normalize(provider, payload);\n if (!event) {\n // Nothing the adapter can key on. 200: redelivering an unreadable payload\n // produces an identical unreadable payload.\n config.logger.warn(`marketplace.webhook: ${provider} payload did not normalize`);\n return { status: 200, body: { received: true, ignored: \"unrecognized_payload\" } };\n }\n const outcome = await engine.deliver({\n clientId,\n event,\n payload,\n // A DISABLED connection still stores its deliveries and ingests nothing;\n // the retry sweep ingests them if the store turns it back on.\n settings: target.enabled\n ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds, followStatus: target.followStatus }\n : null,\n });\n if (outcome.kind === \"failed\") {\n return { status: 500, body: { received: true, error: outcome.reason } };\n }\n return { status: 200, body: { received: true, outcome: outcome.kind } };\n}\n\n/** The webhook descriptor. Raw body required: signatures are computed over bytes. */\nexport function webhookRoute(config: MarketplaceApiConfig): WireRoute<unknown> {\n return {\n method: \"POST\",\n path: \"/webhooks/marketplace/:tenantSlug/:provider\",\n kind: \"webhook\",\n handle: (request) => handleWebhook(config, request),\n };\n}\n","import type { WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { BulkProblem } from \"../core/bulk\";\nimport type { DecisionProblem } from \"../core/cancellation\";\nimport type { MarketplaceIntegrationView } from \"../core/integration\";\nimport type { MarketplaceMenuLinkView } from \"../core/menu-links\";\nimport { MARKETPLACE_DECIDE, MARKETPLACE_MANAGE } from \"./contribution\";\nimport type { MarketplaceServerCopy } from \"./copy\";\nimport { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from \"./http\";\nimport {\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nimport { webhookRoute } from \"./webhook\";\n\n/**\n * The marketplace HTTP surface as framework-neutral wiring descriptors: the\n * webhook every marketplace posts to, and, per entity, one read and one bulk\n * write — connections, SKU links, decisions — for a store's staff and its MCP\n * tools alike.\n *\n * There is no authentication, tenant resolution or RBAC in here: each\n * descriptor DECLARES the permission it needs and the host's guard answers it;\n * the actor arrives already resolved. Paths are relative to the host's mount.\n */\n\nexport type MarketplaceRoute = WireRoute<MarketplaceActor> | WireRoute<unknown>;\n\nconst BASE = \"/admin/:tenantSlug/marketplace\";\n\n/** The 409 code of a decision on an order that is no longer on the clock. */\nexport const ORDER_NOT_PENDING_CODE = \"MARKETPLACE_ORDER_NOT_PENDING\";\n\nconst NOT_PENDING = new Set([\"NOT_FOUND\", \"ALREADY_DECIDED\", \"EXPIRED\", \"CONFLICT\"]);\n\n/** A connection as the read returns it: dates as ISO, the adapter's half beside it. */\nfunction integrationOut(config: MarketplaceApiConfig, row: MarketplaceIntegrationView) {\n const adapter = config.engine.adapter(row.provider);\n return {\n ...row,\n lastEventAt: iso(row.lastEventAt),\n lastVerifiedAt: iso(row.lastVerifiedAt),\n archivedAt: iso(row.archivedAt),\n capabilities: adapter ? adapter.capabilities : null,\n reasons: adapter ? [...adapter.cancellationReasons()] : [],\n };\n}\n\nfunction linkOut(link: MarketplaceMenuLinkView) {\n return { ...link, lastSeenAt: link.lastSeenAt.toISOString() };\n}\n\n/** Each problem with its sentence; a host refusal keeps the host's own words. */\nfunction problemsOut(copy: MarketplaceServerCopy, problems: readonly (BulkProblem | DecisionProblem)[]) {\n return problems.map((problem) => {\n const host = \"host\" in problem ? problem.host : undefined;\n return {\n ...problem,\n message: host?.message ?? copy.problems[problem.code],\n ...(host ? { hostCode: host.code, details: host.details } : {}),\n };\n });\n}\n\n/** A refused bulk write: 422, nothing saved, every problem with its path. */\nfunction refusedBulk(copy: MarketplaceServerCopy, problems: readonly BulkProblem[]): WireResponse {\n return refuse(422, copy.nothingSaved, { problems: problemsOut(copy, problems) });\n}\n\n/**\n * A refused decision call. The host's own refusal is a 409 carrying ITS code\n * (`MARKETPLACE_STOCK_ASK` and the short lines in `details`); an order no\n * longer on the clock a 409; anything else (a reason, an item) a 422.\n */\nfunction refusedDecisions(copy: MarketplaceServerCopy, problems: readonly DecisionProblem[]): WireResponse {\n const out = problemsOut(copy, problems);\n const host = problems.find((problem) => problem.code === \"HOST_REFUSED\")?.host;\n if (host) return refuse(409, host.message, { code: host.code, details: host.details, problems: out });\n if (problems.some((problem) => NOT_PENDING.has(problem.code))) {\n return refuse(409, copy.orderNoLongerPending, { code: ORDER_NOT_PENDING_CODE, problems: out });\n }\n return refuse(422, copy.nothingSaved, { problems: out });\n}\n\nfunction integrationRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceIntegrationsQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const rows = await engine.integrations(actor.clientId, {\n providers: parsed.value.ids,\n includeArchived: parsed.value.includeArchived === \"true\",\n });\n return ok(rows.map((row) => integrationOut(config, row)));\n },\n },\n {\n method: \"PUT\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceIntegrationsBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertIntegrations({\n clientId: actor.clientId,\n actorId: actor.userId ?? null,\n validateOnly: parsed.value.validateOnly,\n rows: parsed.value.integrations.map((row) =>\n \"credentials\" in row && row.credentials\n ? { ...row, credentials: { ...row.credentials, webhookSecret: row.credentials.webhookSecret ?? null } }\n : row,\n ) as Parameters<typeof engine.upsertIntegrations>[0][\"rows\"],\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, integrations: result.rows.map((row) => integrationOut(config, row)) });\n },\n },\n ];\n}\n\nfunction menuLinkRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceMenuLinksQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const links = await engine.menuLinks({\n clientId: actor.clientId,\n provider: parsed.value.provider,\n unmappedOnly: parsed.value.unmapped === \"true\",\n ids: parsed.value.ids,\n });\n return ok(links.map(linkOut));\n },\n },\n {\n method: \"PUT\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceMenuLinksBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertMenuLinks({\n clientId: actor.clientId,\n rows: parsed.value.links,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, links: result.rows.map(linkOut) });\n },\n },\n ];\n}\n\nfunction acceptanceRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceAcceptancesQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const pending = await engine.pending(actor.clientId, parsed.value.ids);\n return ok(\n pending.map((order) => ({\n ...order,\n acknowledgeBy: iso(order.acknowledgeBy),\n externalDueAt: iso(order.externalDueAt),\n })),\n );\n },\n },\n {\n method: \"POST\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, body }) => {\n const parsed = parse(decideMarketplaceOrdersBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.decideMany({\n clientId: actor.clientId,\n decisions: parsed.value.decisions,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedDecisions(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, decisions: result.rows });\n },\n },\n ];\n}\n\n/** The whole surface, in mount order. */\nexport function marketplaceRoutes(config: MarketplaceApiConfig): MarketplaceRoute[] {\n return [\n webhookRoute(config),\n ...integrationRoutes(config),\n ...menuLinkRoutes(config),\n ...acceptanceRoutes(config),\n ];\n}\n","import type { JobsContribution, WireJobBlueprint } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport { CatalogueRetryError, type CatalogueJobPayload } from \"../core/catalogue-job\";\nimport { FetchOrderRetryError, type FetchOrderJobPayload } from \"../core/fetch-order\";\nimport { OutboundRetryError } from \"../core/outbound\";\nimport type { OutboundJobPayload } from \"../core/outbound-queue\";\nimport { AvailabilityRetryError } from \"../core/pause-job\";\nimport type { AvailabilityJobPayload } from \"../core/pause-store\";\n\n/**\n * The engine's eight jobs, declared here because every number in them is the\n * engine's knowledge, not a host's:\n *\n * - `expire-acceptances`, every minute: the unit being measured is minutes (a\n * default window is five), so a coarser tick would make \"expired\" mean\n * anywhere from five to twenty.\n * - `reconcile-inbox`, every five minutes: nothing races a deadline here, and\n * each pass re-runs real ingestion work; the engine's attempt bound retires\n * a payload that will never succeed.\n * - `outbound`, on demand: one call to a marketplace, three attempts with\n * backoff. Its idempotency is the ROW's (the engine re-reads it), never the\n * queue's dedupe alone.\n * - `fetch-order`, on demand: one GET of an order a marketplace's event only\n * announced (`orderToFetch`), then the one ingest path. Three attempts with\n * backoff; the reconciliation sweep re-queues a row still owed.\n * - `catalogue`, on demand: one publish or withdraw of one product on one\n * marketplace's catalogue (FUT-4768). Three attempts with backoff; the\n * last one stamps FAILED with a failure code.\n * - `outbound-sweep`, every five minutes: re-queues every call a row still\n * owes (a PENDING request, an accept with no confirm stamp, a catalogue\n * publish or withdraw on its way) once it is older than the job's own retry\n * span, so a refused enqueue or a dead process loses nothing.\n * - `availability`, on demand: brings one marketplace in line with the host's\n * last pause or resume ask for one store (FUT-4851). Three attempts with\n * backoff; the last one stamps FAILED with a failure code.\n * - `availability-sweep`, every five minutes: resumes a pause past its\n * `until` (the host stopped renewing it), re-queues an ask still owed, and\n * gives up on one older than a day.\n *\n * What stays the host's: whether to run them at all, on which runtime, and the\n * lease implementation. A host with no worker declines `jobs` in writing.\n *\n * Bound with `{ engine }`, these arrive at a runner as\n * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,\n * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.catalogue`,\n * `marketplace.outbound-sweep`, `marketplace.availability` and\n * `marketplace.availability-sweep`.\n */\n\n/** What the host closes over at bind time: the mounted engine. */\nexport interface MarketplaceJobDeps {\n engine: Pick<\n MarketplaceEngine,\n | \"expireLapsed\"\n | \"retryable\"\n | \"reprocess\"\n | \"runOutbound\"\n | \"runFetchOrder\"\n | \"runCatalogue\"\n | \"sweepOutbound\"\n | \"runAvailability\"\n | \"sweepAvailability\"\n >;\n}\n\n/** The single-flight queue name (`@12-apps/jobs`' `SWEEP_QUEUE`), as a literal. */\nexport const MARKETPLACE_SWEEP_QUEUE = \"sweeps\";\n\n/** How long one sweep pass may hold its name. */\nconst SWEEP_LEASE_MS = 5 * 60_000;\n\n/** The outbound job's attempts: the last one stamps the failure. */\nexport const MARKETPLACE_OUTBOUND_ATTEMPTS = 3;\n\nconst expireAcceptances: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"expire-acceptances\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"* * * * *\", timezone: \"UTC\" },\n // Never retried by the queue: the next tick re-finds everything from the rows.\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.expireLapsed();\n if (result.expired === 0) return;\n context.logger.info(\n `marketplace.expire-acceptances: expired ${result.expired} order(s) across ${result.tenants} tenant(s).`,\n );\n },\n};\n\nconst reconcileInbox: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"reconcile-inbox\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const pending = await deps.engine.retryable();\n let ingested = 0;\n // One event's failure never wedges the batch: `reprocess` never throws.\n for (const event of pending) {\n const outcome = await deps.engine.reprocess(event);\n if (outcome.kind === \"ingested\") ingested += 1;\n }\n if (pending.length === 0) return;\n context.logger.info(\n `marketplace.reconcile-inbox: re-ran ${pending.length} stored delivery(ies), ${ingested} became order(s).`,\n );\n },\n};\n\nconst outbound: WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps> = {\n name: \"outbound\",\n attempts: MARKETPLACE_OUTBOUND_ATTEMPTS,\n backoff: { type: \"exponential\", delayMs: 30_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runOutbound(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.outbound: ${payload.action} ${payload.orderId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof OutboundRetryError) context.logger.warn(`marketplace.outbound: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The fetch job's attempts: the last one settles the inbox row FAILED. */\nexport const MARKETPLACE_FETCH_ORDER_ATTEMPTS = 3;\n\nconst fetchOrder: WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps> = {\n name: \"fetch-order\",\n attempts: MARKETPLACE_FETCH_ORDER_ATTEMPTS,\n // Short: an order waiting for its body is on the store's acceptance clock.\n backoff: { type: \"exponential\", delayMs: 5_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runFetchOrder(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.fetch-order: inbox ${payload.inboxId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof FetchOrderRetryError) context.logger.warn(`marketplace.fetch-order: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The catalogue job's attempts: the last one stamps FAILED. */\nconst MARKETPLACE_CATALOGUE_ATTEMPTS = 3;\n\nconst catalogue: WireJobBlueprint<CatalogueJobPayload, MarketplaceJobDeps> = {\n name: \"catalogue\",\n attempts: MARKETPLACE_CATALOGUE_ATTEMPTS,\n // Short: a person is watching the switch say \"sending\".\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runCatalogue(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.catalogue: ${payload.action} ${payload.publicationId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof CatalogueRetryError) context.logger.warn(`marketplace.catalogue: ${error.message}`);\n throw error;\n }\n },\n};\n\nconst outboundSweep: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"outbound-sweep\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.sweepOutbound();\n const idle = result.requeued + result.givenUp + result.timedOut + result.catalogueRequeued === 0;\n if (idle) return;\n context.logger.info(\n `marketplace.outbound-sweep: re-queued ${result.requeued} call(s) and ${result.catalogueRequeued} catalogue ` +\n `call(s), timed out ${result.timedOut} cancellation request(s), gave up on ${result.givenUp}.`,\n );\n },\n};\n\n/** The availability job's attempts: the last one stamps FAILED. */\nexport const MARKETPLACE_AVAILABILITY_ATTEMPTS = 3;\n\nconst availability: WireJobBlueprint<AvailabilityJobPayload, MarketplaceJobDeps> = {\n name: \"availability\",\n attempts: MARKETPLACE_AVAILABILITY_ATTEMPTS,\n // Short: a store is open on the marketplace while the kitchen is paused.\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runAvailability(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.availability: ${payload.provider} ${payload.clientId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof AvailabilityRetryError) context.logger.warn(`marketplace.availability: ${error.message}`);\n throw error;\n }\n },\n};\n\nconst availabilitySweep: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"availability-sweep\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.sweepAvailability();\n if (result.expired + result.requeued + result.givenUp === 0) return;\n context.logger.info(\n `marketplace.availability-sweep: resumed ${result.expired} expired pause(s), re-queued ${result.requeued}, ` +\n `gave up on ${result.givenUp}.`,\n );\n },\n};\n\n/** The jobs contribution. */\nexport const MARKETPLACE_JOBS = {\n namespace: \"marketplace\",\n blueprints: {\n \"expire-acceptances\": expireAcceptances,\n \"reconcile-inbox\": reconcileInbox,\n outbound,\n \"fetch-order\": fetchOrder,\n catalogue,\n \"outbound-sweep\": outboundSweep,\n availability,\n \"availability-sweep\": availabilitySweep,\n },\n} as const satisfies JobsContribution<MarketplaceJobDeps>;\n","import type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceApiConfig } from \"./http\";\nimport { marketplaceRoutes, type MarketplaceRoute } from \"./routes\";\n\n/**\n * `@12-apps/marketplace/server` — the engine's HTTP surface, jobs, MCP tools\n * and permissions, as wiring-contract values.\n *\n * ```ts\n * const engine = createMarketplaceEngine({ …ports, adapters });\n * const api = createApiMarketplace({ engine, copy, tenantBySlug, logger });\n * // api.routes: mount under `/api` (the hono adapter does it in one line)\n * ```\n */\n\n/** What `createApiMarketplace` hands back: the routes, and the engine they serve. */\nexport interface ApiMarketplace {\n routes: MarketplaceRoute[];\n engine: MarketplaceEngine;\n}\n\n/** Build the route table over a mounted engine. */\nexport function createApiMarketplace(config: MarketplaceApiConfig): ApiMarketplace {\n if (!config.logger) {\n throw new Error(\"@12-apps/marketplace: the observability namespace needs a logger; pass `logger`.\");\n }\n return { routes: marketplaceRoutes(config), engine: config.engine };\n}\n\nexport type { MarketplaceActor, MarketplaceApiConfig } from \"./http\";\nexport type { MarketplaceRoute } from \"./routes\";\nexport type { MarketplaceServerCopy } from \"./copy\";\nexport {\n MARKETPLACE_DECIDE,\n MARKETPLACE_MANAGE,\n MARKETPLACE_PERMISSIONS,\n} from \"./contribution\";\nexport {\n MARKETPLACE_AVAILABILITY_ATTEMPTS,\n MARKETPLACE_FETCH_ORDER_ATTEMPTS,\n MARKETPLACE_JOBS,\n MARKETPLACE_OUTBOUND_ATTEMPTS,\n MARKETPLACE_SWEEP_QUEUE,\n type MarketplaceJobDeps,\n} from \"./jobs\";\nexport {\n MARKETPLACE_MCP_TOOLS,\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n marketplaceParams,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nexport { ORDER_NOT_PENDING_CODE } from \"./routes\";\nexport type { MarketplaceProblemCode } from \"./copy\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqCO,SAAS,GAAG,MAA6B;AAC9C,SAAO,EAAE,QAAQ,KAAK,MAAM,EAAE,KAAK,EAAE;AACvC;AAFgB;AAKT,SAAS,OAAO,QAAgB,OAAe,QAAiC,CAAC,GAAiB;AACvG,SAAO,EAAE,QAAQ,MAAM,EAAE,OAAO,GAAG,MAAM,EAAE;AAC7C;AAFgB;AAKT,SAAS,MACd,QACA,OACA,MACgE;AAChE,QAAM,SAAS,OAAO,UAAU,SAAS,CAAC,CAAC;AAC3C,MAAI,OAAO,QAAS,QAAO,EAAE,IAAI,MAAM,OAAO,OAAO,KAAK;AAC1D,QAAM,WAAW,OAAO,MAAM,OAAO,IAAI,CAAC,WAAW;AAAA,IACnD,MAAM,MAAM,KAAK,IAAI,CAAC,YAAa,OAAO,YAAY,WAAW,UAAU,OAAO,OAAO,CAAE;AAAA,IAC3F,MAAM;AAAA,IACN,SAAS,MAAM;AAAA,EACjB,EAAE;AACF,SAAO,EAAE,IAAI,OAAO,UAAU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