@12-apps/marketplace 1.8.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/README.md +102 -8
- package/dist/99food/index.d.ts +30 -54
- package/dist/99food/index.js +60 -418
- package/dist/99food/index.js.map +1 -1
- 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/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/package.json +14 -2
- package/src/99food/catalogue.ts +19 -89
- package/src/99food/copy.ts +4 -19
- package/src/99food/index.ts +28 -33
- package/src/99food/normalize.ts +11 -253
- package/src/99food/outbound.ts +29 -270
- package/src/99food/pause.ts +7 -22
- package/src/index.ts +2 -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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/open-delivery/client.ts","../src/open-delivery/orders.ts","../src/open-delivery/reasons.ts","../src/open-delivery/merchant.ts","../src/open-delivery/normalize.ts"],"sourcesContent":["import {\n tokenGrantResultOf,\n type AdapterCallContext,\n type MarketplaceHttpRequest,\n type MarketplaceHttpResponse,\n type OutboundResult,\n} from \"../core/adapter\";\n\n/**\n * The HTTP half every Open Delivery adapter shares: the token grant and its\n * cache, and one authenticated call. Not a subpath: an adapter folder\n * (`../99food`, `../keeta`) builds a {@link OpenDeliveryDialect} and hands it\n * to these functions, so the standard is written once and each marketplace's\n * departures from it are data in its own folder.\n *\n * Open Delivery standardizes the PATHS under each Ordering Application's own\n * base URL, so the base URL per environment is part of the dialect.\n */\n\n/** Where an Ordering Application serves Open Delivery, per environment. */\nexport type OpenDeliveryApiBaseUrls = Readonly<Record<\"SANDBOX\" | \"PRODUCTION\", string>>;\n\n/** One marketplace's way of speaking Open Delivery: what differs from the standard, as data. */\nexport interface OpenDeliveryDialect {\n /** The provider id the adapter is registered under; it keys the token cache. */\n readonly provider: string;\n /** The marketplace's name, in the reasons a log reads (\"99Food refused the token\"). */\n readonly name: string;\n readonly bases: OpenDeliveryApiBaseUrls;\n /** The token grant's `Content-Type` and body: the standard's form-encoded `client_credentials`, or the marketplace's own. */\n tokenGrant(ctx: AdapterCallContext): { contentType: string; body: string };\n /** A JSON body exactly as it is sent (and, where a signature covers it, signed). */\n serialize(body: unknown): string;\n /** OPTIONAL. Headers derived from the final URL and body, added to EVERY call, the token grant included (a signature). */\n sign?(ctx: AdapterCallContext, url: string, body: string | undefined): Record<string, string>;\n}\n\n/** Refuse, at construction, a configured URL that is not https: credentials travel on it. */\nexport function assertHttpsUrl(packagePath: string, name: string, url: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`${packagePath}: ${name} is not a URL.`);\n }\n if (parsed.protocol !== \"https:\") throw new Error(`${packagePath}: ${name} must be https.`);\n}\n\n/** A token is renewed this long before it expires. */\nconst TOKEN_MARGIN_MS = 60_000;\n/** `expires_in` is optional in the standard's `TokenResponse`; an hour when absent. ESTIMATED. */\nconst DEFAULT_TOKEN_SECONDS = 3600;\n\n/** The result that ends a call before it was answered usefully. */\nexport type OpenDeliveryStop = Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** The base URL with its trailing slashes cut, by a loop: a `/\\/+$/` regex backtracks polynomially on many slashes. */\nfunction baseOf(ctx: AdapterCallContext, bases: OpenDeliveryApiBaseUrls): 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}\n\nconst tokenKey = (ctx: AdapterCallContext, dialect: OpenDeliveryDialect): string =>\n `${dialect.provider}:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** The standard'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/** The dialect's signature headers for one request, or none. */\nfunction signed(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n request: MarketplaceHttpRequest,\n): MarketplaceHttpRequest {\n if (!dialect.sign) return request;\n return { ...request, headers: { ...request.headers, ...dialect.sign(ctx, request.url, request.body) } };\n}\n\n/**\n * A bearer token from the per-process cache, or a fresh grant at `POST\n * /oauth/token`. Keyed by provider, environment and client id; memory only.\n */\nasync function bearer(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n): Promise<{ token: string } | OpenDeliveryStop> {\n const cached = ctx.tokens.get(tokenKey(ctx, dialect));\n if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };\n const grant = dialect.tokenGrant(ctx);\n const response = await ctx.http(\n signed(ctx, dialect, {\n method: \"POST\",\n url: `${baseOf(ctx, dialect.bases)}/oauth/token`,\n headers: { \"Content-Type\": grant.contentType },\n body: grant.body,\n }),\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: `${dialect.name} answered the token grant without a token` };\n ctx.tokens.set(tokenKey(ctx, dialect), {\n token: token.token,\n expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000,\n });\n return { token: token.token };\n}\n\n/** One call, as an Open Delivery adapter states it. */\ninterface OpenDeliveryCall {\n method: MarketplaceHttpRequest[\"method\"];\n /** From the base: `/v1/orders/…`. Path segments are the caller's to encode. */\n path: string;\n /** Sent as the query string. */\n query?: Readonly<Record<string, string>>;\n /** A JSON body, serialized by the dialect. Absent: no body and no `Content-Type`. */\n body?: unknown;\n /** Extra headers (`X-App-MerchantId`). */\n headers?: Readonly<Record<string, string>>;\n /** Whether the call carries the bearer token. Default true; the standard's few open calls say false. */\n authenticated?: boolean;\n}\n\n/** The URL a call goes to: base, path, and the query string when there is one. */\nfunction urlOf(ctx: AdapterCallContext, dialect: OpenDeliveryDialect, call: OpenDeliveryCall): string {\n const query = call.query && Object.keys(call.query).length > 0 ? `?${new URLSearchParams(call.query).toString()}` : \"\";\n return `${baseOf(ctx, dialect.bases)}${call.path}${query}`;\n}\n\n/** The request a call makes, before its signature. */\nfunction requestOf(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n call: OpenDeliveryCall,\n token: string | null,\n): MarketplaceHttpRequest {\n const body = call.body === undefined ? undefined : dialect.serialize(call.body);\n return {\n method: call.method,\n url: urlOf(ctx, dialect, call),\n headers: {\n ...(token === null ? {} : { Authorization: `Bearer ${token}` }),\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n ...call.headers,\n },\n ...(body === undefined ? {} : { body }),\n };\n}\n\n/**\n * One call, authenticated unless it says otherwise: the raw answer, or the\n * result that ends it. A 401 is a token that went stale under us: it is\n * forgotten, and the retry fetches another.\n */\nexport async function openDeliveryCall(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n call: OpenDeliveryCall,\n): Promise<MarketplaceHttpResponse | OpenDeliveryStop> {\n const authenticated = call.authenticated ?? true;\n const auth = authenticated ? await bearer(ctx, dialect) : null;\n if (auth && !(\"token\" in auth)) return auth;\n const response = await ctx.http(signed(ctx, dialect, requestOf(ctx, dialect, call, auth?.token ?? null)));\n if (!authenticated || response.status !== 401) return response;\n ctx.tokens.delete(tokenKey(ctx, dialect));\n return { kind: \"retry\", reason: `${dialect.name} refused the token` };\n}\n\n/** Whether a call ended before an answer worth reading. */\nexport const isStop = (value: MarketplaceHttpResponse | OpenDeliveryStop): value is OpenDeliveryStop =>\n \"kind\" in value;\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type FetchOrderResult,\n type MarketplaceHttpResponse,\n type OutboundOrderRef,\n type OutboundResult,\n type StatusFacts,\n} from \"../core/adapter\";\nimport type { NormalizedMarketplaceOrder } from \"../core/types\";\nimport { isStop, openDeliveryCall, type OpenDeliveryDialect, type OpenDeliveryStop } from \"./client\";\n\n/**\n * The ORDER calls every Open Delivery adapter shares: the order fetch,\n * confirm, requestCancellation and the status steps. Paths, verbs, bodies and\n * answers are the standard's (v1.7.1 and v1.5.0 agree on all of them); the\n * job that calls these, its retries and what a failure shows are the\n * engine's. What a marketplace does differently is an option here, set by its\n * adapter folder. Tests never reach a marketplace: the HTTP client is the\n * host's port, answered by a fake.\n */\n\n/** One authenticated call to an order's resource. */\nfunction callOrder(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n request: { method: \"GET\" | \"POST\"; externalOrderId: string; action: string | null; body?: unknown },\n): Promise<MarketplaceHttpResponse | OpenDeliveryStop> {\n const suffix = request.action === null ? \"\" : `/${request.action}`;\n return openDeliveryCall(ctx, dialect, {\n method: request.method,\n path: `/v1/orders/${encodeURIComponent(request.externalOrderId)}${suffix}`,\n ...(request.body === undefined ? {} : { body: request.body }),\n });\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/** How a fetched `Order` becomes the engine's order. */\ninterface OpenDeliveryFetchOptions {\n normalize(order: unknown): NormalizedMarketplaceOrder | null;\n /**\n * OPTIONAL. What the adapter does to the parsed `Order` before it is\n * normalized (Keeta's encrypted fields). Never fails the fetch.\n */\n prepare?(ctx: AdapterCallContext, order: unknown): Promise<unknown>;\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 dialect: OpenDeliveryDialect,\n order: { externalOrderId: string },\n options: OpenDeliveryFetchOptions,\n): Promise<FetchOrderResult> {\n return fetched(async () => {\n const response = await callOrder(ctx, dialect, { method: \"GET\", externalOrderId: order.externalOrderId, action: null });\n if (isStop(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 prepared = options.prepare ? await options.prepare(ctx, body) : body;\n const normalized = options.normalize(prepared);\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 standard's `OrderConfirmed`:\n * `orderExternalCode` (the host's own order id) and `createdAt`, plus the\n * `preparationTime` in minutes when the store stated one. `createdAt` is sent\n * as the moment of the confirmation: ESTIMATED (the standard describes it\n * with the ORDER's creation text, a copy of another schema's).\n *\n * Every 422 is a refusal. It is the standard's generic `UnprocessableEntity`\n * (\"check if the instruction has not been sent before\"), and its body cannot\n * tell a duplicate from a cancelled order. So a retried confirm whose first\n * answer was lost reads \"not confirmed\" with the app link (a false alarm a\n * person dismisses on the marketplace), and a confirm the marketplace truly\n * refused is never stamped confirmed.\n */\nexport function openDeliveryConfirm(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n): Promise<OutboundResult> {\n return answered(async () => {\n const response = await callOrder(ctx, dialect, {\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 return isStop(response) ? response : outboundResultOf(response);\n });\n}\n\n/** The standard's limit on `outOfStockItems`. */\nconst MAX_OUT_OF_STOCK_ITEMS = 100;\n\n/** How a marketplace reads `RequestCancelled.outOfStockItems`. */\ninterface OpenDeliveryCancellationOptions {\n /**\n * The offending SKUs (`externalCode`) are sent as `outOfStockItems` with an\n * item-unavailable reason. False where the marketplace wants its own item\n * uuids there, which the engine does not keep (99Food, v1.7.1).\n */\n outOfStockAsSkus: boolean;\n}\n\n/**\n * `POST /v1/orders/{orderId}/requestCancellation` with the standard's\n * `RequestCancelled`: `reason` (free text: the store's, else the label),\n * `code` (one of the standard's codes) and `mode` (`MANUAL` or `AUTO`). 202\n * means taken; the outcome is a later event. A 422 whose `cancellationStatus`\n * is `CANCELLED` means the order is cancelled already, which is what the\n * request wanted. A 400 is a malformed request (a bad id or body: ours); a\n * 422 is the business answer and stays a refusal.\n */\nexport function openDeliveryRequestCancellation(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n options: OpenDeliveryCancellationOptions,\n): Promise<OutboundResult> {\n const skus =\n options.outOfStockAsSkus && input.reason.itemUnavailable && input.offendingSkus.length > 0\n ? { outOfStockItems: input.offendingSkus.slice(0, MAX_OUT_OF_STOCK_ITEMS) }\n : {};\n return answered(async () => {\n const response = await callOrder(ctx, dialect, {\n method: \"POST\",\n externalOrderId: order.externalOrderId,\n action: \"requestCancellation\",\n body: {\n reason: input.text === \"\" ? input.reason.label : input.text,\n code: input.reason.code,\n mode: input.mode,\n ...skus,\n },\n });\n if (isStop(response)) return response;\n if (alreadyCancelled(response)) return { kind: \"accepted\" };\n const result = outboundResultOf(response);\n return result.kind === \"refused\" && result.status === 400 ? { ...result, own: true } : result;\n });\n}\n\n/** Which standard status call a step takes, for which kind of order. */\ntype StatusPath = (facts: StatusFacts) => { action: string; body?: unknown } | null;\n\n/** The status calls a marketplace serves. */\ninterface OpenDeliveryStatusOptions {\n /** A take-out's HANDED_OVER is `POST /v1/orders/{id}/pickedUp`. False where the marketplace has no take-out. */\n takeoutPickedUp: boolean;\n}\n\n/**\n * The standard's status calls (FUT-4653):\n *\n * - READY: `POST /v1/orders/{id}/readyForPickup`, no body; 202. Every kind of order.\n * - DISPATCHED: `POST /v1/orders/{id}/dispatch`, body `OrderDispatched`\n * (`deliveryTrackingInfo` optional, sent empty). Only where the logistics\n * is the merchant's.\n * - HANDED_OVER: the merchant's bag `POST /v1/orders/{id}/delivered`; a\n * take-out `POST /v1/orders/{id}/pickedUp` where the marketplace serves it.\n * The marketplace's own fleet: none.\n *\n * The kind of order is `deliveredBy` (null: a take-out; ESTIMATED: an order\n * that merely omits it reads as a take-out here).\n */\nfunction statusPaths(options: OpenDeliveryStatusOptions): Readonly<Record<string, StatusPath>> {\n return {\n READY: () => ({ action: \"readyForPickup\" }),\n DISPATCHED: (facts) => (facts.deliveredBy === \"MERCHANT\" ? { action: \"dispatch\", body: {} } : null),\n HANDED_OVER: (facts) =>\n facts.deliveredBy === \"MERCHANT\"\n ? { action: \"delivered\", body: {} }\n : facts.deliveredBy === null && options.takeoutPickedUp\n ? { action: \"pickedUp\", body: {} }\n : null,\n };\n}\n\n/** A marketplace's status half: whether a step is taken (offline), and the call that tells it. */\nexport function openDeliveryStatus(options: OpenDeliveryStatusOptions) {\n const paths = statusPaths(options);\n return {\n supported: (facts: StatusFacts): boolean => paths[facts.step]?.(facts) != null,\n inform(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n order: OutboundOrderRef,\n facts: StatusFacts,\n ): Promise<OutboundResult | { kind: \"unsupported\" }> {\n const path = paths[facts.step]?.(facts) ?? null;\n if (path === null) return Promise.resolve({ kind: \"unsupported\" });\n return answered(async () => {\n const response = await callOrder(ctx, dialect, {\n method: \"POST\",\n externalOrderId: order.externalOrderId,\n action: path.action,\n ...(path.body === undefined ? {} : { body: path.body }),\n });\n return isStop(response) ? response : outboundResultOf(response);\n });\n },\n };\n}\n","/**\n * The cancellation codes a merchant may send, verbatim from Open Delivery's\n * `RequestCancelled.code`: the same eleven in v1.7.1 and in Keeta's v1.5.0\n * (its \"códigos de cancelamento (v1.0.7+)\"). Pinned by the standard, not\n * estimated. The two codes only the marketplace sends\n * (`CONSUMER_CANCELLATION_REQUESTED`, `OTHER_CANCELLATION_REASON`) are not a\n * store's to choose and are left out.\n */\nexport const OPEN_DELIVERY_MERCHANT_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\ntype OpenDeliveryMerchantReasonCode = (typeof OPEN_DELIVERY_MERCHANT_REASON_CODES)[number];\n\n/** The one reason that means \"an item is unavailable\". */\nexport const OPEN_DELIVERY_ITEM_UNAVAILABLE: OpenDeliveryMerchantReasonCode = \"UNAVAILABLE_ITEM\";\n","import { answered, outboundResultOf, type AdapterCallContext, type OutboundResult } from \"../core/adapter\";\nimport { stableUuid } from \"../core/catalogue-ids\";\nimport type { CatalogueMenuEntry, CatalogueMenuOptions } from \"../core/catalogue-port\";\nimport type { MarketplaceAvailability } from \"../core/pause-port\";\nimport { isStop, openDeliveryCall, type OpenDeliveryDialect } from \"./client\";\n\n/**\n * The MERCHANT half every Open Delivery adapter shares: the menu part of the\n * `Merchant` document the host serves (`GET /v1/merchant`, PULL: FUT-4768),\n * the `merchantUpdate` notification, and the store pause built on it\n * (FUT-4851). Where a marketplace puts `merchantUpdate` and what it sends\n * with it is its adapter folder's.\n *\n * Every id in the document is a UUID the software generates (the standard'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/**\n * The menu part of Open Delivery's `Merchant`: `menus`, `categories`,\n * `items`, `itemOffers` (the price lives on the offer). Every item is a unit\n * (`UN`) with a status, and every offer states `originalValue`: what both\n * v1.7.1 and Keeta's v1.5.0 require.\n */\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/** One `merchantUpdate` call, where and with what the marketplace takes it. */\ninterface OpenDeliveryMerchantUpdate {\n /** From the base: `/v1/merchantUpdate`, or a marketplace's own (Keeta's names the merchant). */\n path: string;\n /** Absent: the empty body that means \"pull the whole merchant again\". */\n body?: unknown;\n headers?: Readonly<Record<string, string>>;\n}\n\n/** `POST {merchantUpdate}`: 2xx accepted (the standard answers 204, 200 \"for compatibility\"). */\nexport function openDeliveryMerchantUpdate(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n update: OpenDeliveryMerchantUpdate,\n): Promise<OutboundResult> {\n return answered(async () => {\n const response = await openDeliveryCall(ctx, dialect, {\n method: \"POST\",\n path: update.path,\n ...(update.body === undefined ? {} : { body: update.body }),\n ...(update.headers === undefined ? {} : { headers: update.headers }),\n });\n return isStop(response) ? response : outboundResultOf(response);\n });\n}\n\n/**\n * The store pause on `merchantUpdate`'s `merchantStatus` (`AVAILABLE` /\n * `UNAVAILABLE`): a SWITCH, with no id and no end (\"you don't know when the\n * service will be re-established\"), so an adapter offers it only when its\n * host opts in (see `../core/pause-port.ts`).\n */\nexport function openDeliverySwitchAvailability(\n setStatus: (ctx: AdapterCallContext, merchantId: string, status: \"AVAILABLE\" | \"UNAVAILABLE\") => Promise<OutboundResult>,\n): MarketplaceAvailability {\n return {\n kind: \"switch\",\n pause: async (ctx, request) => {\n const result = await setStatus(ctx, request.merchantId, \"UNAVAILABLE\");\n return result.kind === \"accepted\" ? { kind: \"paused\", externalId: null, until: request.until } : result;\n },\n resume: (ctx, ref) => setStatus(ctx, ref.merchantId, \"AVAILABLE\"),\n };\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 MarketplaceLifecycle,\n MarketplaceDeliveredBy,\n MarketplaceOrderType,\n NormalizedAddress,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n NormalizedOrderLine,\n} from \"../core/types\";\n\n/**\n * The INBOUND half every Open Delivery adapter shares (Abrasel's standard;\n * 99Food speaks v1.7.1, Keeta v1.5.0 with its own changes). Each reader takes\n * the provider id the result is stamped with.\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 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 order left (DISPATCHED) and the order is finished (CONCLUDED): the lifecycle events (FUT-4653). */\nconst LIFECYCLE_OF: Readonly<Record<string, MarketplaceLifecycle>> = { DISPATCHED: \"DISPATCHED\", CONCLUDED: \"CONCLUDED\" };\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 * - `DISPATCHED` and `CONCLUDED` are lifecycle events (FUT-4653): the engine\n * asks the host to move the order forward, when the store follows them.\n * - Everything else (`CONFIRMED`, `CANCELLATION_REQUESTED`, 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 normalizeOpenDeliveryEventAs(provider: string, 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,\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 ...(LIFECYCLE_OF[eventType] ? { lifecycle: LIFECYCLE_OF[eventType] } : {}),\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 normalizeOpenDeliveryOrderAs(\n provider: string,\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,\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAsCO,SAAS,eAAe,aAAqB,MAAc,KAAmB;AACnF,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,GAAG;AAAA,EACtB,QAAQ;AACN,UAAM,IAAI,MAAM,GAAG,WAAW,KAAK,IAAI,gBAAgB;AAAA,EACzD;AACA,MAAI,OAAO,aAAa,SAAU,OAAM,IAAI,MAAM,GAAG,WAAW,KAAK,IAAI,iBAAiB;AAC5F;AARgB;AAWhB,IAAM,kBAAkB;AAExB,IAAM,wBAAwB;AAM9B,SAAS,OAAO,KAAyB,OAAwC;AAC/E,QAAM,OAAO,MAAM,IAAI,WAAW;AAClC,MAAI,MAAM,KAAK;AACf,SAAO,MAAM,KAAK,KAAK,WAAW,MAAM,CAAC,MAAM,GAAI,QAAO;AAC1D,SAAO,KAAK,MAAM,GAAG,GAAG;AAC1B;AALS;AAOT,IAAM,WAAW,wBAAC,KAAyB,YACzC,GAAG,QAAQ,QAAQ,IAAI,IAAI,WA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A,IACA;AAAA;AAAA;AAAA,IAGA,YACE,WAAW,OAAO,CAAC,CAAC,SAAS,eAAe,OAAO,CAAC,CAAC,KACrD,MAAM,OAAO,CAAC,KAAK,SAAS,MAAM,KAAK,iBAAiB,KAAK,UAAU,CAAC;AAAA,IAC1E,iBAAiB;AAAA,IACjB,eAAe,UAAU,OAAO;AAAA,MAC9B,CAAC,YAAY,2BAA2B;AAAA,MACxC,CAAC,WAAW,iBAAiB;AAAA,MAC7B,CAAC,YAAY,sBAAsB;AAAA,IACrC,CAAC;AAAA,IACD,UAAU,UAAU,OAAO,CAAC,CAAC,WAAW,CAAC,CAAC,KAAK,oBAAI,KAAK;AAAA,IACxD,WAAW,cAAc,KAAK;AAAA,IAC9B,aAAa,gBAAgB,KAAK;AAAA,IAClC,iBAAiB,YAAY,OAAO,QAAQ,mBAAmB;AAAA,EACjE;AACF;AArCgB;","names":[]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { O as OutboundResult } from './adapter-CYJzu1c9.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The HTTP half every Open Delivery adapter shares: the token grant and its
|
|
5
|
+
* cache, and one authenticated call. Not a subpath: an adapter folder
|
|
6
|
+
* (`../99food`, `../keeta`) builds a {@link OpenDeliveryDialect} and hands it
|
|
7
|
+
* to these functions, so the standard is written once and each marketplace's
|
|
8
|
+
* departures from it are data in its own folder.
|
|
9
|
+
*
|
|
10
|
+
* Open Delivery standardizes the PATHS under each Ordering Application's own
|
|
11
|
+
* base URL, so the base URL per environment is part of the dialect.
|
|
12
|
+
*/
|
|
13
|
+
/** Where an Ordering Application serves Open Delivery, per environment. */
|
|
14
|
+
type OpenDeliveryApiBaseUrls = Readonly<Record<"SANDBOX" | "PRODUCTION", string>>;
|
|
15
|
+
/** The result that ends a call before it was answered usefully. */
|
|
16
|
+
type OpenDeliveryStop = Exclude<OutboundResult, {
|
|
17
|
+
kind: "accepted";
|
|
18
|
+
}>;
|
|
19
|
+
|
|
20
|
+
export type { OpenDeliveryApiBaseUrls as O, OpenDeliveryStop as a };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** The Keeta adapter's en-US pack: the same reasons, in English. */
|
|
2
|
+
declare const KEETA_ADAPTER_COPY_EN_US: {
|
|
3
|
+
readonly reasonLabels: {
|
|
4
|
+
readonly SYSTEMIC_ISSUES: "System problems";
|
|
5
|
+
readonly DUPLICATE_APPLICATION: "Duplicate order";
|
|
6
|
+
readonly UNAVAILABLE_ITEM: "Item unavailable";
|
|
7
|
+
readonly RESTAURANT_WITHOUT_DELIVERY_PERSON: "No courier available";
|
|
8
|
+
readonly OUTDATED_MENU: "Menu out of date";
|
|
9
|
+
readonly ORDER_OUTSIDE_THE_DELIVERY_AREA: "Outside the delivery area";
|
|
10
|
+
readonly BLOCKED_CUSTOMER: "Blocked customer";
|
|
11
|
+
readonly OUTSIDE_DELIVERY_HOURS: "Outside delivery hours";
|
|
12
|
+
readonly INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT: "Internal difficulties";
|
|
13
|
+
readonly RISK_AREA: "Risk area";
|
|
14
|
+
readonly DELIVERY_PROBLEM: "Delivery problem";
|
|
15
|
+
};
|
|
16
|
+
readonly missingStreetNumber: "no number";
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export { KEETA_ADAPTER_COPY_EN_US };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import "../chunk-7QVYU63E.js";
|
|
2
|
+
|
|
3
|
+
// src/keeta/en-US.ts
|
|
4
|
+
var KEETA_ADAPTER_COPY_EN_US = {
|
|
5
|
+
reasonLabels: {
|
|
6
|
+
SYSTEMIC_ISSUES: "System problems",
|
|
7
|
+
DUPLICATE_APPLICATION: "Duplicate order",
|
|
8
|
+
UNAVAILABLE_ITEM: "Item unavailable",
|
|
9
|
+
RESTAURANT_WITHOUT_DELIVERY_PERSON: "No courier available",
|
|
10
|
+
OUTDATED_MENU: "Menu out of date",
|
|
11
|
+
ORDER_OUTSIDE_THE_DELIVERY_AREA: "Outside the delivery area",
|
|
12
|
+
BLOCKED_CUSTOMER: "Blocked customer",
|
|
13
|
+
OUTSIDE_DELIVERY_HOURS: "Outside delivery hours",
|
|
14
|
+
INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT: "Internal difficulties",
|
|
15
|
+
RISK_AREA: "Risk area",
|
|
16
|
+
DELIVERY_PROBLEM: "Delivery problem"
|
|
17
|
+
},
|
|
18
|
+
missingStreetNumber: "no number"
|
|
19
|
+
};
|
|
20
|
+
export {
|
|
21
|
+
KEETA_ADAPTER_COPY_EN_US
|
|
22
|
+
};
|
|
23
|
+
//# sourceMappingURL=en-US.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/keeta/en-US.ts"],"sourcesContent":["import type { KeetaAdapterCopy } from \"./copy\";\n\n/** The Keeta adapter's en-US pack: the same reasons, in English. */\nexport const KEETA_ADAPTER_COPY_EN_US = {\n reasonLabels: {\n SYSTEMIC_ISSUES: \"System problems\",\n DUPLICATE_APPLICATION: \"Duplicate order\",\n UNAVAILABLE_ITEM: \"Item unavailable\",\n RESTAURANT_WITHOUT_DELIVERY_PERSON: \"No courier available\",\n OUTDATED_MENU: \"Menu out of date\",\n ORDER_OUTSIDE_THE_DELIVERY_AREA: \"Outside the delivery area\",\n BLOCKED_CUSTOMER: \"Blocked customer\",\n OUTSIDE_DELIVERY_HOURS: \"Outside delivery hours\",\n INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT: \"Internal difficulties\",\n RISK_AREA: \"Risk area\",\n DELIVERY_PROBLEM: \"Delivery problem\",\n },\n missingStreetNumber: \"no number\",\n} as const satisfies KeetaAdapterCopy;\n"],"mappings":";;;AAGO,IAAM,2BAA2B;AAAA,EACtC,cAAc;AAAA,IACZ,iBAAiB;AAAA,IACjB,uBAAuB;AAAA,IACvB,kBAAkB;AAAA,IAClB,oCAAoC;AAAA,IACpC,eAAe;AAAA,IACf,iCAAiC;AAAA,IACjC,kBAAkB;AAAA,IAClB,wBAAwB;AAAA,IACxB,yCAAyC;AAAA,IACzC,WAAW;AAAA,IACX,kBAAkB;AAAA,EACpB;AAAA,EACA,qBAAqB;AACvB;","names":[]}
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { A as AdapterCallContext, N as NormalizedEvent, a as NormalizedMarketplaceOrder, c as MarketplaceAdapter } from '../adapter-CYJzu1c9.js';
|
|
2
|
+
import { a as OpenDeliveryStop, O as OpenDeliveryApiBaseUrls } from '../client-B4EQCRD_.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Keeta's MERCHANT AUTHORIZATION, automated from the software (Keeta's
|
|
6
|
+
* "Autorização Self-serve do Merchant", read 2026-11-26 at
|
|
7
|
+
* https://api-docs.mykeeta.com/apis/opendelivery/merchant-self-serve-authorization).
|
|
8
|
+
* Not on the adapter port: connecting a store is the host's flow, and these
|
|
9
|
+
* are the calls it is built from.
|
|
10
|
+
*
|
|
11
|
+
* 1. {@link KeetaAuthorization.authorizationUrl}: `GET
|
|
12
|
+
* /oauth/authorization/url?clientId=&redirectUri=` (no token: a token
|
|
13
|
+
* needs at least one authorized store), the link the merchant opens.
|
|
14
|
+
* 2. The merchant authorizes; Keeta redirects to `redirectUri` with `authId`
|
|
15
|
+
* (and `state`, `appId`, `timestamp`), and POSTs the authorization webhook
|
|
16
|
+
* ({@link normalizeKeetaAuthorizationEvent}: `opType` 1 added, 2 revoked).
|
|
17
|
+
* 3. {@link KeetaAuthorization.authorizedShops}: `GET
|
|
18
|
+
* /oauth/authorized/{authId}/merchantInfo?pageNum=&pageSize=` lists the
|
|
19
|
+
* stores of that authorization (Keeta's ids, names, addresses, time zones).
|
|
20
|
+
* 4. The host maps a Keeta store to its own, then
|
|
21
|
+
* {@link KeetaAuthorization.onboard}: `PUT /v1/merchantOnboarding?merchantId=`
|
|
22
|
+
* binds the SOFTWARE's merchant id (the connection's `externalMerchantId`)
|
|
23
|
+
* to `keetaMerchantId` and registers the `GET /v1/merchant` URL and the
|
|
24
|
+
* orders webhook. "Without onboarding there are no order events"; sending
|
|
25
|
+
* it again for the same id REPLACES the mapping. Answer 201.
|
|
26
|
+
*
|
|
27
|
+
* ESTIMATED: the JSON answer the authorization webhook wants ("200 within
|
|
28
|
+
* ~5 s, with JSON containing `code` and `message`": the values are not
|
|
29
|
+
* given, {@link KEETA_AUTHORIZATION_WEBHOOK_ANSWER} sends 0 and "success").
|
|
30
|
+
*/
|
|
31
|
+
/** What the authorization webhook is answered with, 200, within ~5 s. ESTIMATED values. */
|
|
32
|
+
declare const KEETA_AUTHORIZATION_WEBHOOK_ANSWER: {
|
|
33
|
+
readonly code: 0;
|
|
34
|
+
readonly message: "success";
|
|
35
|
+
};
|
|
36
|
+
/** One authorization change Keeta reported (event 1301 added, 1302 revoked). */
|
|
37
|
+
interface KeetaAuthorizationEvent {
|
|
38
|
+
authId: string;
|
|
39
|
+
change: "AUTHORIZED" | "REVOKED";
|
|
40
|
+
/** Keeta's store id (an integer on the wire, text here). */
|
|
41
|
+
shopId: string;
|
|
42
|
+
shopName: string | null;
|
|
43
|
+
/** The application's id. */
|
|
44
|
+
clientId: string | null;
|
|
45
|
+
at: Date | null;
|
|
46
|
+
}
|
|
47
|
+
/** Read the authorization webhook's body (`WebhookNotification`). Null when it names no authorization or store. */
|
|
48
|
+
declare function normalizeKeetaAuthorizationEvent(payload: unknown): KeetaAuthorizationEvent | null;
|
|
49
|
+
/** One store of an authorization, as `merchantInfo` lists it. */
|
|
50
|
+
interface KeetaAuthorizedShop {
|
|
51
|
+
/** Keeta's store id: the `keetaMerchantId` the onboarding takes. */
|
|
52
|
+
id: string;
|
|
53
|
+
name: string | null;
|
|
54
|
+
address: string | null;
|
|
55
|
+
latitude: number | null;
|
|
56
|
+
longitude: number | null;
|
|
57
|
+
timeZone: string | null;
|
|
58
|
+
}
|
|
59
|
+
/** One page of an authorization's stores. */
|
|
60
|
+
interface KeetaAuthorizedShops {
|
|
61
|
+
brandId: string | null;
|
|
62
|
+
brandName: string | null;
|
|
63
|
+
shops: KeetaAuthorizedShop[];
|
|
64
|
+
page: {
|
|
65
|
+
pageNum: number;
|
|
66
|
+
totalPage: number;
|
|
67
|
+
totalCount: number;
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/** What the host registers for one store at onboarding. */
|
|
71
|
+
interface KeetaOnboarding {
|
|
72
|
+
/** The SOFTWARE's merchant id: the connection's `externalMerchantId`, the `Merchant.id` the host serves. */
|
|
73
|
+
merchantId: string;
|
|
74
|
+
/** Keeta's store id, from `authorizedShops` or Keeta's portal. */
|
|
75
|
+
keetaMerchantId: number;
|
|
76
|
+
/** Where Keeta reads this store's `GET /v1/merchant` (one URL per store), and its key if it wants one. */
|
|
77
|
+
merchantDocument?: {
|
|
78
|
+
url: string;
|
|
79
|
+
apiKey?: string;
|
|
80
|
+
};
|
|
81
|
+
/** The engine's webhook for this store: `…/webhooks/marketplace/:tenantSlug/KEETA`. */
|
|
82
|
+
ordersWebhookUrl?: string;
|
|
83
|
+
}
|
|
84
|
+
type KeetaAuthorizationResult<T> = {
|
|
85
|
+
kind: "ok";
|
|
86
|
+
value: T;
|
|
87
|
+
} | OpenDeliveryStop;
|
|
88
|
+
/** The self-serve authorization calls, bound to Keeta's dialect. */
|
|
89
|
+
interface KeetaAuthorization {
|
|
90
|
+
authorizationUrl(ctx: AdapterCallContext, input: {
|
|
91
|
+
redirectUri?: string;
|
|
92
|
+
}): Promise<KeetaAuthorizationResult<string>>;
|
|
93
|
+
authorizedShops(ctx: AdapterCallContext, input: {
|
|
94
|
+
authId: string;
|
|
95
|
+
pageNum?: number;
|
|
96
|
+
pageSize?: number;
|
|
97
|
+
}): Promise<KeetaAuthorizationResult<KeetaAuthorizedShops>>;
|
|
98
|
+
onboard(ctx: AdapterCallContext, input: KeetaOnboarding): Promise<KeetaAuthorizationResult<true>>;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The words the Keeta adapter needs from its host, and nothing else.
|
|
103
|
+
*
|
|
104
|
+
* Required and defaultless, like every copy port in this repo: the adapter
|
|
105
|
+
* ships no language of its own. Two packs sit beside it (`./pt-BR`,
|
|
106
|
+
* `./en-US`); a host passes one by hand, or its own.
|
|
107
|
+
*/
|
|
108
|
+
/**
|
|
109
|
+
* The cancellation codes a merchant may send: Keeta's "códigos de
|
|
110
|
+
* cancelamento (v1.0.7+)", the same eleven as Open Delivery's
|
|
111
|
+
* (`../open-delivery/reasons.ts`). Keeta still accepts its legacy codes
|
|
112
|
+
* (`INSUFFICIENT_DISHES`, `SUSPENSION_OF_BUSINESS`, `INSUFFICIENT_MANPOWER`,
|
|
113
|
+
* `OTHERS`) and recommends the new ones, so only the new ones are offered.
|
|
114
|
+
*/
|
|
115
|
+
declare const KEETA_REASON_CODES: readonly ["SYSTEMIC_ISSUES", "DUPLICATE_APPLICATION", "UNAVAILABLE_ITEM", "RESTAURANT_WITHOUT_DELIVERY_PERSON", "OUTDATED_MENU", "ORDER_OUTSIDE_THE_DELIVERY_AREA", "BLOCKED_CUSTOMER", "OUTSIDE_DELIVERY_HOURS", "INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT", "RISK_AREA", "DELIVERY_PROBLEM"];
|
|
116
|
+
type KeetaReasonCode = (typeof KEETA_REASON_CODES)[number];
|
|
117
|
+
interface KeetaAdapterCopy {
|
|
118
|
+
/** One label per reason code. Sent as the request's `reason` text when the store wrote none. */
|
|
119
|
+
reasonLabels: Readonly<Record<KeetaReasonCode, string>>;
|
|
120
|
+
/** What an address with no street number (or an encrypted one Keeta would not reveal) says instead. */
|
|
121
|
+
missingStreetNumber: string;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Keeta's Open Delivery DIALECT. Keeta follows Open Delivery v1.5.0 with
|
|
126
|
+
* changes of its own, and "the definitions of this document prevail"
|
|
127
|
+
* (https://api-docs.mykeeta.com/apis/opendelivery/general-info, read
|
|
128
|
+
* 2026-11-26). The calls are `../open-delivery/`'s; this file says how Keeta
|
|
129
|
+
* takes them:
|
|
130
|
+
*
|
|
131
|
+
* - Token: `POST /oauth/token` with a JSON body `{ client_id, client_secret,
|
|
132
|
+
* grant_type: "app_level_token" }` (v1.0.9's name for the standard's
|
|
133
|
+
* `client_credentials`, which stays accepted for integrations already
|
|
134
|
+
* certified). The token is the APPLICATION's: one for every store that
|
|
135
|
+
* authorized it, so the cache key (provider, environment, client id) is
|
|
136
|
+
* right as it is. Answer `{ access_token, token_type, expires_in }`; no
|
|
137
|
+
* refresh token in this mode.
|
|
138
|
+
* - Every request, the grant included, carries `X-App-Signature`
|
|
139
|
+
* (`./signature.ts`), and every JSON body is RFC 8785 canonical.
|
|
140
|
+
*/
|
|
141
|
+
/** Where Keeta serves Open Delivery, per environment. */
|
|
142
|
+
type KeetaApiBaseUrls = OpenDeliveryApiBaseUrls;
|
|
143
|
+
/**
|
|
144
|
+
* The documented server (`servers[0]` of Keeta's `openapi.json`). ESTIMATED
|
|
145
|
+
* for SANDBOX: Keeta documents one host, and a test application (its own
|
|
146
|
+
* client id and secret, its test stores) is what makes a session a test one.
|
|
147
|
+
*/
|
|
148
|
+
declare const KEETA_API_BASE_URL = "https://open.mykeeta.com/api/open/opendelivery";
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The Keeta adapter's INBOUND half: Open Delivery's readers
|
|
152
|
+
* (`../open-delivery/normalize.ts`) stamped with Keeta's provider id, plus
|
|
153
|
+
* the one thing Keeta's `Order` does that the standard's does not: personal
|
|
154
|
+
* data arrives ENCRYPTED.
|
|
155
|
+
*
|
|
156
|
+
* Events (Keeta's order guide, read 2026-11-26): `CREATED` → fetch;
|
|
157
|
+
* `CANCELLED` (with a JSON-string `metadata` carrying `reason` and `code`) →
|
|
158
|
+
* cancelled; `DISPATCHED`, `CONCLUDED` → lifecycle. Keeta has NO
|
|
159
|
+
* `CANCELLATION_REQUEST_DENIED`: a store's request that Keeta does not grant
|
|
160
|
+
* produces no event, so it ends TIMEOUT at the adapter's answer window. The
|
|
161
|
+
* rest (`CONFIRMED`, `READY_FOR_PICKUP`, `PICKUP_ONGOING`,
|
|
162
|
+
* `RIDER_ARRIVED_AT_STORE`, `ORDER_COLLECTED`, `DELIVERED`,
|
|
163
|
+
* `CANCELLATION_REQUESTED`, `USER_REFUND_REQUEST`, `REFUNDED`,
|
|
164
|
+
* `REFUND_FAILED`, `RECOMMENDED_PREPARATION_START`) are recorded and IGNORED.
|
|
165
|
+
*/
|
|
166
|
+
/** The provider id Keeta is registered under. Uppercase: the column's CHECK holds that shape. */
|
|
167
|
+
declare const KEETA_PROVIDER = "KEETA";
|
|
168
|
+
/** Normalize one webhook `Event`. Null only when it names no order. */
|
|
169
|
+
declare function normalizeKeetaEvent(payload: unknown): NormalizedEvent | null;
|
|
170
|
+
/** Normalize one `Order`, after {@link revealKeetaOrder}. Null when it carries no id or no line. */
|
|
171
|
+
declare function normalizeKeetaOrder(order: unknown, options: {
|
|
172
|
+
missingStreetNumber: string;
|
|
173
|
+
}): NormalizedMarketplaceOrder | null;
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Keeta's `X-App-Signature`, both directions (read 2026-11-26 at
|
|
177
|
+
* https://api-docs.mykeeta.com/apis/opendelivery/signature-calculation and its
|
|
178
|
+
* three sub-pages, and the `newEvent` and webhook guide pages).
|
|
179
|
+
*
|
|
180
|
+
* OUTBOUND — every request the software sends Keeta, the token grant
|
|
181
|
+
* included, carries it (Keeta's change to Open Delivery: a token alone is not
|
|
182
|
+
* enough, so an intercepted token cannot be replayed):
|
|
183
|
+
*
|
|
184
|
+
* - the string is the URL without its query, then `&key=value` for each
|
|
185
|
+
* query parameter sorted by key (a null value is `key=`), then `&` and the
|
|
186
|
+
* body when there is one: an empty body, a blank one or `{}` is left out,
|
|
187
|
+
* and so is its `&`;
|
|
188
|
+
* - the body is compact JSON canonicalized by RFC 8785 (JCS), and the SAME
|
|
189
|
+
* string is sent;
|
|
190
|
+
* - HMAC-SHA256 of the string (UTF-8), keyed by the application's
|
|
191
|
+
* `client_secret`, encoded Base64.
|
|
192
|
+
*
|
|
193
|
+
* INBOUND — a webhook Keeta sends (`POST /v1/newEvent`, and the
|
|
194
|
+
* authorization webhook) is signed "HMAC-SHA256 of the body, with the
|
|
195
|
+
* client_secret as key, in Base64".
|
|
196
|
+
*
|
|
197
|
+
* ESTIMATED:
|
|
198
|
+
* - query values are signed DECODED (the reference implementations take them
|
|
199
|
+
* from a map, before any URL encoding); only the self-serve authorization
|
|
200
|
+
* calls send a query, and only `redirectUri` can hold a character encoding
|
|
201
|
+
* changes;
|
|
202
|
+
* - the inbound signature covers the raw body bytes as received, with no URL
|
|
203
|
+
* prefix (the pages say "the body");
|
|
204
|
+
* - the authorization webhook's header uses the same Base64 HMAC (its schema
|
|
205
|
+
* says only "SHA256 hash of the request body, using the client secret as the
|
|
206
|
+
* key").
|
|
207
|
+
*/
|
|
208
|
+
/**
|
|
209
|
+
* RFC 8785 (JCS) for the JSON this adapter sends: object keys sorted by
|
|
210
|
+
* UTF-16 code units, no whitespace, strings and numbers as ECMAScript's
|
|
211
|
+
* `JSON.stringify` writes them (which is what JCS specifies). `undefined`
|
|
212
|
+
* members are dropped, as `JSON.stringify` drops them.
|
|
213
|
+
*/
|
|
214
|
+
declare function canonicalJson(value: unknown): string;
|
|
215
|
+
/** The `X-App-Signature` of one outbound request. */
|
|
216
|
+
declare function keetaRequestSignature(url: string, body: string | undefined, clientSecret: string): string;
|
|
217
|
+
/**
|
|
218
|
+
* Verify a webhook Keeta sent: Base64 HMAC-SHA256 of the raw body, keyed by
|
|
219
|
+
* the application's client secret, which a connection stores as its webhook
|
|
220
|
+
* secret. The key exists from the moment the store connects, so an unset
|
|
221
|
+
* secret REFUSES: an unsigned CANCELLED for a known order id would otherwise
|
|
222
|
+
* cancel it. Compared in constant time.
|
|
223
|
+
*/
|
|
224
|
+
declare function verifyKeetaSignature(rawBody: string, signature: string | null, webhookSecret: string | null): boolean;
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* How long Keeta may take to answer a cancellation request. ESTIMATED: Keeta
|
|
228
|
+
* names none, and sends no event for a refusal, so past this the request is
|
|
229
|
+
* failed as TIMEOUT. Keeta's own clock is 5 minutes for the acceptance.
|
|
230
|
+
*/
|
|
231
|
+
declare const KEETA_CANCELLATION_ANSWER_WINDOW_MS: number;
|
|
232
|
+
/** Where "open it on Keeta" goes by default: the Merchant Portal (Keeta names no per-order link). */
|
|
233
|
+
declare const KEETA_PORTAL_URL = "https://merchant.mykeeta.com/";
|
|
234
|
+
interface KeetaAdapterConfig {
|
|
235
|
+
/** The words the adapter needs: reason labels and the missing-number text. Required. */
|
|
236
|
+
copy: KeetaAdapterCopy;
|
|
237
|
+
/** OPTIONAL. Where Keeta serves Open Delivery, per environment. Default: the documented server for both. https only. */
|
|
238
|
+
apiBaseUrl?: KeetaApiBaseUrls;
|
|
239
|
+
/** OPTIONAL. Where "open it on Keeta" goes. Default: the Merchant Portal. https only. */
|
|
240
|
+
portalUrl?: string;
|
|
241
|
+
/**
|
|
242
|
+
* OPTIONAL, off by default. Offer the store pause (FUT-4851) through
|
|
243
|
+
* `merchantStatus`, a store-wide switch with no id: a store the owner also
|
|
244
|
+
* closed by hand on Keeta during the kitchen's pause is opened with it.
|
|
245
|
+
*/
|
|
246
|
+
pauseByStoreSwitch?: boolean;
|
|
247
|
+
}
|
|
248
|
+
/** Build the Keeta adapter. Its reasons are static: a dialog never waits on Keeta. */
|
|
249
|
+
declare function createKeetaAdapter(config: KeetaAdapterConfig): MarketplaceAdapter;
|
|
250
|
+
/** The self-serve merchant authorization calls (`./authorization.ts`), for the same base URLs as the adapter. */
|
|
251
|
+
declare function createKeetaAuthorization(config?: Pick<KeetaAdapterConfig, "apiBaseUrl">): KeetaAuthorization;
|
|
252
|
+
|
|
253
|
+
export { KEETA_API_BASE_URL, KEETA_AUTHORIZATION_WEBHOOK_ANSWER, KEETA_CANCELLATION_ANSWER_WINDOW_MS, KEETA_PORTAL_URL, KEETA_PROVIDER, KEETA_REASON_CODES, type KeetaAdapterConfig, type KeetaAdapterCopy, type KeetaApiBaseUrls, type KeetaAuthorization, type KeetaAuthorizationEvent, type KeetaAuthorizationResult, type KeetaAuthorizedShop, type KeetaAuthorizedShops, type KeetaOnboarding, type KeetaReasonCode, canonicalJson, createKeetaAdapter, createKeetaAuthorization, keetaRequestSignature, normalizeKeetaAuthorizationEvent, normalizeKeetaEvent, normalizeKeetaOrder, verifyKeetaSignature };
|