@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.
Files changed (96) hide show
  1. package/ADOPTING.md +17 -0
  2. package/README.md +153 -3
  3. package/dist/99food/index.d.ts +30 -52
  4. package/dist/99food/index.js +62 -391
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-DOjTak1H.d.ts → adapter-CYJzu1c9.d.ts} +45 -1
  7. package/dist/{chunk-YVUZHXUF.js → chunk-6N2HEV3U.js} +4 -4
  8. package/dist/chunk-6N2HEV3U.js.map +1 -0
  9. package/dist/{chunk-SJUKBCVO.js → chunk-BMCERPQX.js} +198 -12
  10. package/dist/chunk-BMCERPQX.js.map +1 -0
  11. package/dist/{chunk-L3DCOZUU.js → chunk-HEXLCTOG.js} +1 -1
  12. package/dist/chunk-HEXLCTOG.js.map +1 -0
  13. package/dist/{chunk-UYFYGGCS.js → chunk-NP4EYKPO.js} +3 -1
  14. package/dist/chunk-NP4EYKPO.js.map +1 -0
  15. package/dist/chunk-PYHNM47K.js +478 -0
  16. package/dist/chunk-PYHNM47K.js.map +1 -0
  17. package/dist/client-B4EQCRD_.d.ts +20 -0
  18. package/dist/{engine-DG1fg43Y.d.ts → engine-wmW-VuBL.d.ts} +107 -4
  19. package/dist/hono/index.d.ts +2 -2
  20. package/dist/hono/index.js +3 -3
  21. package/dist/ifood/index.d.ts +1 -1
  22. package/dist/ifood/index.js +29 -3
  23. package/dist/ifood/index.js.map +1 -1
  24. package/dist/index.d.ts +3 -3
  25. package/dist/index.js +104 -7
  26. package/dist/index.js.map +1 -1
  27. package/dist/keeta/en-US.d.ts +19 -0
  28. package/dist/keeta/en-US.js +23 -0
  29. package/dist/keeta/en-US.js.map +1 -0
  30. package/dist/keeta/index.d.ts +253 -0
  31. package/dist/keeta/index.js +388 -0
  32. package/dist/keeta/index.js.map +1 -0
  33. package/dist/keeta/pt-BR.d.ts +23 -0
  34. package/dist/keeta/pt-BR.js +23 -0
  35. package/dist/keeta/pt-BR.js.map +1 -0
  36. package/dist/manifest/index.d.ts +3 -0
  37. package/dist/manifest/index.js +1 -1
  38. package/dist/manifest/server.d.ts +2 -2
  39. package/dist/manifest/server.js +3 -3
  40. package/dist/rappi/index.d.ts +7 -1
  41. package/dist/rappi/index.js +20 -3
  42. package/dist/rappi/index.js.map +1 -1
  43. package/dist/server/index.d.ts +6 -2
  44. package/dist/server/index.js +3 -3
  45. package/package.json +14 -2
  46. package/prisma/marketplace.prisma +45 -1
  47. package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
  48. package/src/99food/catalogue.ts +19 -89
  49. package/src/99food/copy.ts +4 -19
  50. package/src/99food/index.ts +29 -28
  51. package/src/99food/normalize.ts +11 -247
  52. package/src/99food/outbound.ts +29 -215
  53. package/src/99food/pause.ts +7 -22
  54. package/src/core/adapter.ts +41 -1
  55. package/src/core/bulk.ts +1 -1
  56. package/src/core/engine.ts +9 -0
  57. package/src/core/ingest.ts +6 -0
  58. package/src/core/integration.ts +17 -0
  59. package/src/core/lifecycle-port.ts +16 -0
  60. package/src/core/lifecycle.ts +133 -0
  61. package/src/core/outbound-queue.ts +24 -4
  62. package/src/core/outbound-sweep.ts +49 -5
  63. package/src/core/outbound.ts +11 -0
  64. package/src/core/pipeline.ts +22 -2
  65. package/src/core/ports.ts +39 -3
  66. package/src/core/status-inform.ts +51 -0
  67. package/src/core/status-job.ts +207 -0
  68. package/src/core/status-store.ts +85 -0
  69. package/src/core/types.ts +14 -0
  70. package/src/ifood/index.ts +7 -1
  71. package/src/ifood/normalize.ts +17 -0
  72. package/src/ifood/outbound.ts +35 -0
  73. package/src/index.ts +8 -1
  74. package/src/keeta/authorization.ts +226 -0
  75. package/src/keeta/copy.ts +27 -0
  76. package/src/keeta/en-US.ts +19 -0
  77. package/src/keeta/index.ts +162 -0
  78. package/src/keeta/merchant.ts +70 -0
  79. package/src/keeta/normalize.ts +131 -0
  80. package/src/keeta/outbound.ts +55 -0
  81. package/src/keeta/pt-BR.ts +23 -0
  82. package/src/keeta/signature.ts +85 -0
  83. package/src/open-delivery/client.ts +185 -0
  84. package/src/open-delivery/merchant.ts +126 -0
  85. package/src/open-delivery/normalize.ts +269 -0
  86. package/src/open-delivery/orders.ts +241 -0
  87. package/src/open-delivery/reasons.ts +26 -0
  88. package/src/rappi/index.ts +6 -1
  89. package/src/rappi/normalize.ts +6 -0
  90. package/src/rappi/outbound.ts +31 -2
  91. package/src/server/mcp.ts +2 -0
  92. package/src/server/webhook.ts +3 -1
  93. package/dist/chunk-L3DCOZUU.js.map +0 -1
  94. package/dist/chunk-SJUKBCVO.js.map +0 -1
  95. package/dist/chunk-UYFYGGCS.js.map +0 -1
  96. package/dist/chunk-YVUZHXUF.js.map +0 -1
@@ -31,4 +31,4 @@ export {
31
31
  tokenGrantResultOf,
32
32
  answered
33
33
  };
34
- //# sourceMappingURL=chunk-L3DCOZUU.js.map
34
+ //# sourceMappingURL=chunk-HEXLCTOG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { MarketplaceCatalogue } from \"./catalogue-port\";\nimport type { CatalogueReader } from \"./catalogue-read-port\";\nimport type { MarketplaceAvailability } from \"./pause-port\";\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceProvider,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n} from \"./types\";\n\n/**\n * The adapter port: everything one marketplace is, behind one shape.\n *\n * The owner's rule, which this file exists to make true: \"the integration\n * engine must be the same for all integrations: iFood, Rappi, 99. Only an\n * adapter is made for each one, to connect to the base engine.\"\n *\n * A marketplace differs from the next in five ways that matter to a store:\n * how its deliveries look and are signed (`normalize`, `readSignature`,\n * `verifySignature`), what it lets a store answer through its API (`confirm`,\n * `requestCancellation`), which reasons a refusal may carry\n * (`cancellationReasons`), and where a person goes when the API cannot do it\n * (`appLink`). Everything else — the inbox, the clock, the SKU map, the\n * outbound bookkeeping and its retries — is the engine's and does not change\n * with the marketplace.\n *\n * What a marketplace CAN do is stated by its adapter as\n * {@link MarketplaceCapabilities} and read by the engine and the host. It is\n * never inferred from the provider's id: a branch on the id outside an adapter\n * would make the next marketplace a code change instead of an adapter.\n *\n * The HTTP client is a host port ({@link MarketplaceHttp}), handed to every\n * outbound call. An adapter never reaches the network on its own, so tests\n * answer the seam and nothing else, and the host owns the timeout, the proxy\n * and the CA.\n */\n\n/** A marketplace's credentials, as the merchant supplies them. Sealed at rest. */\nexport interface MarketplaceCredentials {\n clientId: string;\n clientSecret: string;\n /**\n * The shared secret a delivery's signature is verified against. Separate\n * from the OAuth pair: a merchant rotating their webhook secret has not\n * re-onboarded.\n */\n webhookSecret: string | null;\n}\n\n/** What the host's HTTP client takes. */\nexport interface MarketplaceHttpRequest {\n /**\n * `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it.\n * `DELETE` since FUT-4851: iFood removes an interruption with it.\n */\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: string;\n}\n\n/** What the host's HTTP client answers: any status, never a throw for a 4xx or 5xx. */\nexport interface MarketplaceHttpResponse {\n status: number;\n body: string;\n}\n\n/** The host's HTTP client. It throws only when no answer arrived (a timeout, a network error). */\nexport type MarketplaceHttp = (request: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>;\n\n/** What a marketplace can do, stated by its adapter. */\nexport interface MarketplaceCapabilities {\n /** Accepting is answered through the API. */\n apiConfirm: boolean;\n /** A cancellation can be requested through the API at all. */\n apiCancel: boolean;\n /** …and still once the order was accepted. */\n cancelAfterAccept: boolean;\n /** The cancellation's outcome arrives later as an event rather than in the answer. */\n asyncCancellationOutcome: boolean;\n /** `appLink` names this order, rather than only the marketplace's portal. */\n perOrderAppLink: boolean;\n /** Confirming states a preparation time. */\n confirmTakesPreparationTime: boolean;\n /**\n * OPTIONAL. How long the marketplace takes, at most, to answer a store's\n * cancellation request, in milliseconds: past it the outbound sweep fails\n * the request as TIMEOUT. Absent: only the 24-hour give-up applies.\n */\n cancellationAnswerWindowMs?: number;\n /**\n * OPTIONAL. The steps this marketplace can be told about (`informStatus`).\n * Absent or empty: the engine tells it nothing.\n */\n statusSteps?: readonly StatusStep[];\n}\n\n/**\n * A step of the order the store tells the marketplace about (FUT-4653): the\n * order is ready for pickup, the courier left, the order was handed over.\n */\nexport type StatusStep = \"READY\" | \"DISPATCHED\" | \"HANDED_OVER\";\n\n/** What a status call is told about the order: who carries it (null: a take-out, or unstated). */\nexport interface StatusFacts {\n step: StatusStep;\n deliveredBy: MarketplaceDeliveredBy | null;\n}\n\n/** One reason a store may give for refusing or cancelling an order. */\nexport interface CancellationReason {\n /** The marketplace's own code, sent verbatim. */\n code: string;\n /** The label the host was configured with for this code (a named pack). */\n label: string;\n /** This reason means \"an item is unavailable\": the host preselects it when stock is short. */\n itemUnavailable: boolean;\n /** The marketplace requires the offending SKUs with this reason. */\n needsItems: boolean;\n}\n\n/** The order an outbound call is about, as the engine knows it. */\nexport interface OutboundOrderRef {\n externalOrderId: string;\n externalDisplayId: string | null;\n /** The host's own id for the order. */\n hostOrderCode: string;\n /** When the engine recorded the order. */\n placedAt: Date;\n}\n\n/** A per-engine token cache an adapter reads and fills. Never persisted. */\nexport type AdapterTokenCache = Map<string, { token: string; expiresAt: number }>;\n\n/** What one outbound call is handed. */\nexport interface AdapterCallContext {\n http: MarketplaceHttp;\n credentials: MarketplaceCredentials;\n environment: \"SANDBOX\" | \"PRODUCTION\";\n /** Written to no row, log or audit entry: memory only, per process. */\n tokens: AdapterTokenCache;\n now: Date;\n}\n\n/** One outbound call's answer, in the three shapes the engine acts on. */\nexport type OutboundResult =\n /** 2xx. For a marketplace whose outcome is asynchronous, \"the request was taken\". */\n | { kind: \"accepted\" }\n /**\n * A final 4xx (not 408/425/429): never retried. `own` marks a refusal that\n * is not the marketplace's judgement of the order: our credentials were not\n * accepted, or our request was malformed. A cancellation request that ends\n * so fails as UNREACHABLE, not REFUSED.\n */\n | { kind: \"refused\"; status: number; message: string; own?: true }\n /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */\n | { kind: \"retry\"; reason: string };\n\n/**\n * One order-body fetch's answer: the order, normalized, or the same refusal and\n * retry shapes an outbound call answers with (a 404 for an expired order is a\n * refusal; a 5xx, a timeout or a 429 is a retry).\n */\nexport type FetchOrderResult =\n | { kind: \"order\"; order: NormalizedMarketplaceOrder }\n | Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** What a cancellation request carries. */\nexport interface CancellationRequestInput {\n reason: CancellationReason;\n /** Free text from the store; empty means \"the reason's own label\". */\n text: string;\n mode: \"MANUAL\" | \"AUTO\";\n offendingSkus: readonly string[];\n}\n\n/** One marketplace, in and out. */\nexport interface MarketplaceAdapter {\n readonly provider: MarketplaceProvider;\n readonly capabilities: MarketplaceCapabilities;\n /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */\n normalize(payload: unknown): NormalizedEvent | null;\n /** Which header carries this marketplace's signature, read off the request. */\n readSignature(header: (name: string) => string | null): string | null;\n /** Is this delivery's signature the one this store's secret would produce? */\n verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;\n /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */\n cancellationReasons(): readonly CancellationReason[];\n /** Tell the marketplace the store accepted the order. */\n confirm(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n ): Promise<OutboundResult>;\n /** Ask the marketplace to cancel the order, with one of its own reasons. */\n requestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n ): Promise<OutboundResult>;\n /**\n * OPTIONAL. Whether this marketplace takes this step for this kind of order,\n * answered offline, with no call: the job asks it BEFORE it claims anything\n * (an unsupported step leaves no row). Absent: every step in\n * `capabilities.statusSteps` is taken for every order.\n */\n statusSupported?(facts: StatusFacts): boolean;\n /**\n * OPTIONAL. Tell the marketplace the order reached a step (FUT-4653). Called\n * only from the `marketplace.outbound` job, action `status`. `unsupported`\n * (no endpoint for this step and this kind of order) ends the job with no\n * row. Absent: the marketplace is told nothing.\n */\n informStatus?(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n facts: StatusFacts,\n ): Promise<OutboundResult | { kind: \"unsupported\" }>;\n /**\n * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a\n * marketplace whose events carry no order body). Called only from the\n * `marketplace.fetch-order` job. An adapter whose events always carry the\n * order (iFood) leaves it out.\n */\n fetchOrder?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<FetchOrderResult>;\n /**\n * OPTIONAL. Publishing the store's products to this marketplace's catalogue\n * (FUT-4768): `push` (the adapter writes each item) or `pull` (the\n * marketplace reads a menu document the host serves). Absent: the\n * marketplace cannot be published to, and the host says so.\n */\n readonly catalogue?: MarketplaceCatalogue;\n /**\n * OPTIONAL. Reading the menu the store already keeps on this marketplace,\n * through its own connection, for the host to import (FUT-951). Absent: the\n * menu cannot be read through an API, and the host says so.\n */\n readonly catalogueReader?: CatalogueReader;\n /**\n * OPTIONAL. Closing the store on this marketplace for a while, and opening\n * it again (FUT-4851). Absent: the marketplace cannot be paused through an\n * API, and the host says so.\n */\n readonly availability?: MarketplaceAvailability;\n /** Where \"open it on the marketplace\" goes: the order when `perOrderAppLink`, else the portal. Always https. */\n appLink(order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string;\n}\n\n/**\n * The 4xx statuses that are NOT a refusal: a request timeout (408), \"too\n * early\" (425) and a rate limit (429) say \"ask again later\" by HTTP's own\n * semantics, and a marketplace rate-limits its merchant API.\n */\nconst TRANSIENT_CLIENT_STATUSES = new Set([408, 425, 429]);\n\n/**\n * Read one HTTP answer the way the engine acts on it. Shared by every adapter\n * whose API speaks plain status codes, so the rule is one rule rather than one\n * per marketplace: 2xx accepted; a 4xx other than 408/425/429 refused and\n * final; everything else (408, 425, 429, 5xx, anything unexpected) retried.\n */\nexport function outboundResultOf(response: MarketplaceHttpResponse): OutboundResult {\n if (response.status >= 200 && response.status < 300) return { kind: \"accepted\" };\n const message = response.body.slice(0, 300);\n const refusal = response.status >= 400 && response.status < 500 && !TRANSIENT_CLIENT_STATUSES.has(response.status);\n if (refusal) return { kind: \"refused\", status: response.status, message };\n return { kind: \"retry\", reason: `status ${response.status}: ${message}` };\n}\n\n/**\n * {@link outboundResultOf} for a token grant: a final 4xx there says our\n * credentials were not accepted, never a judgement of any order, so it is an\n * `own` refusal.\n */\nexport function tokenGrantResultOf(response: MarketplaceHttpResponse): OutboundResult {\n const result = outboundResultOf(response);\n return result.kind === \"refused\" ? { ...result, own: true } : result;\n}\n\n/** A call that never got an answer is a retry, with the reason a log can read. */\nexport async function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n"],"mappings":";;;;;AA6PA,IAAM,4BAA4B,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAQlD,SAAS,iBAAiB,UAAmD;AAClF,MAAI,SAAS,UAAU,OAAO,SAAS,SAAS,IAAK,QAAO,EAAE,MAAM,WAAW;AAC/E,QAAM,UAAU,SAAS,KAAK,MAAM,GAAG,GAAG;AAC1C,QAAM,UAAU,SAAS,UAAU,OAAO,SAAS,SAAS,OAAO,CAAC,0BAA0B,IAAI,SAAS,MAAM;AACjH,MAAI,QAAS,QAAO,EAAE,MAAM,WAAW,QAAQ,SAAS,QAAQ,QAAQ;AACxE,SAAO,EAAE,MAAM,SAAS,QAAQ,UAAU,SAAS,MAAM,KAAK,OAAO,GAAG;AAC1E;AANgB;AAaT,SAAS,mBAAmB,UAAmD;AACpF,QAAM,SAAS,iBAAiB,QAAQ;AACxC,SAAO,OAAO,SAAS,YAAY,EAAE,GAAG,QAAQ,KAAK,KAAK,IAAI;AAChE;AAHgB;AAMhB,eAAsB,SAAS,MAA8D;AAC3F,MAAI;AACF,WAAO,MAAM,KAAK;AAAA,EACpB,SAAS,OAAO;AACd,WAAO,EAAE,MAAM,SAAS,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE;AAAA,EACzF;AACF;AANsB;","names":[]}
@@ -52,6 +52,7 @@ var integrationUpsertInput = z.strictObject({
52
52
  environment: environmentSchema.optional(),
53
53
  externalMerchantId: z.string().trim().min(1).nullable().optional(),
54
54
  autoAccept: z.boolean().optional(),
55
+ followStatus: z.boolean().optional(),
55
56
  // Below a minute nothing human can answer in time; above an hour the
56
57
  // deadline has stopped describing anything a marketplace would wait for.
57
58
  ackSlaSeconds: z.number().int().min(60).max(3600).optional(),
@@ -127,6 +128,7 @@ var integrationSchema = z.object({
127
128
  status: z.enum(["UNVERIFIED", "VERIFIED", "FAILED"]),
128
129
  externalMerchantId: z.string().nullable(),
129
130
  autoAccept: z.boolean(),
131
+ followStatus: z.boolean(),
130
132
  ackSlaSeconds: z.number().int(),
131
133
  connected: z.boolean(),
132
134
  lastEventAt: z.string().nullable(),
@@ -247,4 +249,4 @@ export {
247
249
  decideMarketplaceOrdersBody,
248
250
  MARKETPLACE_MCP_TOOLS
249
251
  };
250
- //# sourceMappingURL=chunk-UYFYGGCS.js.map
252
+ //# sourceMappingURL=chunk-NP4EYKPO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server/contribution.ts","../src/server/mcp.ts"],"sourcesContent":["import type { WirePermissionsContribution } from \"@12-apps/wiring\";\n\n/**\n * THIS PACKAGE'S OWN PERMISSION CONTRIBUTION.\n *\n * Two privileges, kept apart on purpose (the ADR-0117 pattern of naming the\n * act, not the role):\n *\n * - `marketplace:manage` — CONNECT a marketplace (store its credentials, turn\n * it on, set auto-accept and the acceptance window) and MAP its SKUs to the\n * catalog. Committing the store to a commercial relationship and teaching\n * the engine what a SKU means are the same person's job.\n * - `marketplace:decide` — read the acceptance queue and answer it: accept or\n * refuse an order with a reason. That is whoever is on the floor when the\n * clock runs, and a queue only an owner could answer would lapse.\n *\n * Which roles hold either is the HOST's decision; the package only names\n * them. The shape is `@12-apps/rbac`'s `PermissionContribution`, taken from\n * the wiring contract's type-only twin. No labels: a label is a word in a\n * language, and the vocabulary a picker renders is the host's.\n */\nexport const MARKETPLACE_PERMISSIONS = {\n source: \"@12-apps/marketplace\",\n ids: [\"marketplace:manage\", \"marketplace:decide\"],\n permissions: {\n \"marketplace:manage\": { kind: \"class\" },\n \"marketplace:decide\": { kind: \"class\" },\n },\n} as const satisfies WirePermissionsContribution;\n\n/** Connect a marketplace and map its SKUs. */\nexport const MARKETPLACE_MANAGE = \"marketplace:manage\";\n/** Read and answer the acceptance queue. */\nexport const MARKETPLACE_DECIDE = \"marketplace:decide\";\n","import { z } from \"zod\";\n\nimport type { WireMcpTool } from \"@12-apps/wiring\";\n\n/**\n * The marketplace tool surface — authored ONCE, beside the route descriptors\n * it proxies to, and reused as the runtime validators. The advertised schema\n * and what a handler accepts are the same objects, so they cannot drift.\n *\n * The shape is the bulk-upsert protocol: ONE bulk write per entity\n * (connections, SKU links, decisions), each taking a list, all-or-nothing,\n * `validateOnly` supported, idempotent on the natural key, every refusal\n * returned with its path; a connection is ARCHIVED, never deleted. A read is\n * the entity's `list*` tool, taking `ids`.\n *\n * Every input is STRICT (an unknown key is refused, never stripped), and the\n * cross-row checks (a key twice in one call) are part of the schema. The\n * provider is checked for SHAPE here and for EXISTENCE at runtime, because\n * the set of marketplaces is the set of adapters a host registered.\n *\n * Paths are RELATIVE to the http capability's mount (`/api` in the origin\n * host). The webhook is not a tool: a marketplace's server-to-server callback\n * is not a capability anybody invokes.\n */\n\nconst providerSchema = z.string().regex(/^[A-Z][A-Z0-9_]*$/u);\nconst environmentSchema = z.enum([\"SANDBOX\", \"PRODUCTION\"]);\nconst booleanText = z.enum([\"true\", \"false\"]);\n/** A comma-separated id list in a query string: `ids=a,b`. */\nconst idsText = z\n .string()\n .transform((text) => text.split(\",\").map((id) => id.trim()).filter((id) => id !== \"\"))\n .pipe(z.array(z.string().min(1)).min(1).max(100));\n\n/** Flag every row whose key repeats an earlier one, at that row's path. */\nfunction noDuplicates<T>(list: string, field: string, keyOf: (row: T) => string) {\n return (rows: readonly T[], ctx: z.RefinementCtx): void => {\n const seen = new Set<string>();\n rows.forEach((row, index) => {\n const key = keyOf(row);\n if (seen.has(key)) {\n ctx.addIssue({ code: \"custom\", path: [index, field], message: `${field} repeats an earlier row of ${list}` });\n }\n seen.add(key);\n });\n };\n}\n\n/** Path params for the tenant-scoped marketplace resource. */\nexport const marketplaceParams = z.strictObject({\n tenantSlug: z.string().min(1),\n});\n\n/** Which connections to read. */\nexport const listMarketplaceIntegrationsQuery = z.strictObject({\n ids: idsText.optional(),\n includeArchived: booleanText.optional(),\n});\n\n/** The credential half of a save. Absent leaves the stored secrets alone. */\nconst credentialsInput = z.strictObject({\n clientId: z.string().trim().min(1),\n clientSecret: z.string().trim().min(1),\n webhookSecret: z.string().trim().min(1).nullable().optional(),\n});\n\n/** Create or patch one connection; any subset of its settings. */\nconst integrationUpsertInput = z.strictObject({\n operation: z.literal(\"upsert\").optional(),\n provider: providerSchema,\n enabled: z.boolean().optional(),\n environment: environmentSchema.optional(),\n externalMerchantId: z.string().trim().min(1).nullable().optional(),\n autoAccept: z.boolean().optional(),\n followStatus: z.boolean().optional(),\n // Below a minute nothing human can answer in time; above an hour the\n // deadline has stopped describing anything a marketplace would wait for.\n ackSlaSeconds: z.number().int().min(60).max(3600).optional(),\n credentials: credentialsInput.optional(),\n});\n\n/** Archive (reversible) or unarchive one connection, with an optional reason. */\nconst integrationArchiveInput = z.strictObject({\n operation: z.enum([\"archive\", \"unarchive\"]),\n provider: providerSchema,\n reason: z.string().trim().min(1).max(500).nullable().optional(),\n});\n\n/** Many connection changes, all-or-nothing. */\nexport const upsertMarketplaceIntegrationsBody = z.strictObject({\n validateOnly: z.boolean().optional(),\n integrations: z\n .array(z.union([integrationArchiveInput, integrationUpsertInput]))\n .min(1)\n .max(20)\n .superRefine(noDuplicates(\"integrations\", \"provider\", (row) => row.provider)),\n});\n\n/** Filters for the SKU map. `unmapped=true` IS the attention list. */\nexport const listMarketplaceMenuLinksQuery = z.strictObject({\n provider: providerSchema.optional(),\n // A query string is text: \"false\" must mean false.\n unmapped: booleanText.optional(),\n ids: idsText.optional(),\n});\n\n/** Map one external SKU to a catalog id, or unmap it with `menuItemId: null`. */\nconst menuLinkInput = z.strictObject({\n provider: providerSchema,\n externalSku: z.string().trim().min(1),\n externalName: z.string().trim().min(1).optional(),\n menuItemId: z.string().min(1).nullable(),\n});\n\n/** Many SKU links, all-or-nothing; idempotent on (provider, externalSku). */\nexport const upsertMarketplaceMenuLinksBody = z.strictObject({\n validateOnly: z.boolean().optional(),\n links: z\n .array(menuLinkInput)\n .min(1)\n .max(200)\n .superRefine(noDuplicates(\"links\", \"externalSku\", (row) => `${row.provider}\\u0000${row.externalSku}`)),\n});\n\n/** Which queued orders to read. */\nexport const listMarketplaceAcceptancesQuery = z.strictObject({\n ids: idsText.optional(),\n});\n\n/** What the person confirmed beside an accept, for the host's admission. */\nconst admissionInput = z.strictObject({\n admitStockPastZero: z.boolean().optional(),\n});\n\n/**\n * One decision. An accept may carry the admission and a preparation time; a\n * refusal one of the marketplace's reason codes (its first when omitted) and,\n * for a reason that needs them, the order's offending SKUs. A field of the\n * other kind is refused, not ignored.\n */\nconst decisionInput = z.discriminatedUnion(\"decision\", [\n z.strictObject({\n orderId: z.string().min(1),\n decision: z.literal(\"ACCEPT\"),\n admission: admissionInput.optional(),\n preparationMinutes: z.number().int().min(1).max(240).optional(),\n }),\n z.strictObject({\n orderId: z.string().min(1),\n decision: z.literal(\"REJECT\"),\n reasonCode: z.string().trim().min(1).optional(),\n offendingSkus: z.array(z.string().trim().min(1)).min(1).max(50).optional(),\n }),\n]);\n\n/** Many decisions, all-or-nothing, the host admitting each inside one transaction. */\nexport const decideMarketplaceOrdersBody = z.strictObject({\n validateOnly: z.boolean().optional(),\n decisions: z\n .array(decisionInput)\n .min(1)\n .max(50)\n .superRefine(noDuplicates(\"decisions\", \"orderId\", (row) => row.orderId)),\n});\n\nconst reasonSchema = z.object({\n code: z.string(),\n label: z.string(),\n itemUnavailable: z.boolean(),\n needsItems: z.boolean(),\n});\n\nconst capabilitiesSchema = z.object({\n apiConfirm: z.boolean(),\n apiCancel: z.boolean(),\n cancelAfterAccept: z.boolean(),\n asyncCancellationOutcome: z.boolean(),\n perOrderAppLink: z.boolean(),\n confirmTakesPreparationTime: z.boolean(),\n});\n\n/** A connection as every read returns it: `connected` stands in for the secrets. */\nconst integrationSchema = z.object({\n provider: z.string(),\n enabled: z.boolean(),\n environment: environmentSchema,\n status: z.enum([\"UNVERIFIED\", \"VERIFIED\", \"FAILED\"]),\n externalMerchantId: z.string().nullable(),\n autoAccept: z.boolean(),\n followStatus: z.boolean(),\n ackSlaSeconds: z.number().int(),\n connected: z.boolean(),\n lastEventAt: z.string().nullable(),\n lastVerifiedAt: z.string().nullable(),\n archivedAt: z.string().nullable(),\n capabilities: capabilitiesSchema.nullable(),\n reasons: z.array(reasonSchema),\n});\n\nconst menuLinkSchema = z.object({\n id: z.string(),\n provider: z.string(),\n externalSku: z.string(),\n externalName: z.string(),\n menuItemId: z.string().nullable(),\n lastSeenAt: z.string(),\n});\n\nconst pendingAcceptanceSchema = z.object({\n id: z.string(),\n orderId: z.string(),\n provider: z.string(),\n externalOrderId: z.string(),\n externalDisplayId: z.string().nullable(),\n totalCents: z.number().int(),\n buyerName: z.string().nullable(),\n acknowledgeBy: z.string().nullable(),\n externalDueAt: z.string().nullable(),\n commissionCents: z.number().int().nullable(),\n unmappedLines: z.number().int(),\n createdAt: z.string().nullable(),\n});\n\nconst decidedSchema = z.object({\n orderId: z.string(),\n status: z.enum([\"ACCEPTED\", \"REJECTED\"]),\n cancellation: z.enum([\"PENDING\", \"REQUESTED\", \"CONFIRMED\", \"FAILED\"]).nullable(),\n reasonCode: z.string().nullable(),\n offendingSkus: z.array(z.string()),\n});\n\nconst BASE = \"/admin/{tenantSlug}/marketplace\";\n\n/** The six marketplace tools: a read and a bulk write per entity. */\nexport const MARKETPLACE_MCP_TOOLS = [\n {\n operationId: \"listMarketplaceIntegrations\",\n method: \"GET\",\n path: BASE,\n summary:\n \"List one or many of a store's marketplace connections (pass `ids` as provider ids, e.g. `ids=IFOOD`): whether each is enabled, its environment, auto-accept, the acknowledgement window, and each marketplace's capabilities and refusal reasons. Archived connections only with `includeArchived=true`. Never returns the stored credentials: `connected` says only whether a set is on file.\",\n tags: [\"marketplace\"],\n params: marketplaceParams,\n query: listMarketplaceIntegrationsQuery,\n response: z.object({ data: z.array(integrationSchema) }),\n annotations: { readOnly: true },\n },\n {\n operationId: \"upsertMarketplaceIntegrations\",\n method: \"PUT\",\n path: BASE,\n summary:\n \"Create, update, archive or unarchive one or many marketplace connections in one all-or-nothing call. A row is keyed by `provider`; `operation` is `upsert` (default: any subset of the settings; omitting `credentials` keeps the stored secrets, sending them resets the status to UNVERIFIED), `archive` or `unarchive` (reversible, audited, with an optional `reason`). Any problem writes nothing and every problem comes back with its path. `validateOnly: true` checks without writing.\",\n tags: [\"marketplace\"],\n params: marketplaceParams,\n body: upsertMarketplaceIntegrationsBody,\n response: z.object({ data: z.object({ validateOnly: z.boolean(), integrations: z.array(integrationSchema) }) }),\n annotations: { readOnly: false, destructive: false },\n },\n {\n operationId: \"listMarketplaceMenuLinks\",\n method: \"GET\",\n path: `${BASE}/menu-links`,\n summary:\n \"List a store's marketplace SKU map, or the links named by `ids`: every external SKU an incoming order has carried, and the catalog id it resolves to. `unmapped=true` is the attention list: the SKUs that arrived with nothing behind them, newest-seen first. An unmapped SKU never rejects an order.\",\n tags: [\"marketplace\"],\n params: marketplaceParams,\n query: listMarketplaceMenuLinksQuery,\n response: z.object({ data: z.array(menuLinkSchema) }),\n annotations: { readOnly: true },\n },\n {\n operationId: \"upsertMarketplaceMenuLinks\",\n method: \"PUT\",\n path: `${BASE}/menu-links`,\n summary:\n \"Map one or many external marketplace SKUs to the store's catalog ids, or unmap them with `menuItemId: null`, in one all-or-nothing call keyed by (`provider`, `externalSku`). A SKU never seen is created, so a store can map ahead of the first order. Applies to orders ingested from now on. Any problem (a catalog id that is not the store's, a repeated SKU) writes nothing; `validateOnly: true` checks without writing.\",\n tags: [\"marketplace\"],\n params: marketplaceParams,\n body: upsertMarketplaceMenuLinksBody,\n response: z.object({ data: z.object({ validateOnly: z.boolean(), links: z.array(menuLinkSchema) }) }),\n annotations: { readOnly: false, destructive: false },\n },\n {\n operationId: \"listMarketplaceAcceptances\",\n method: \"GET\",\n path: `${BASE}/acceptances`,\n summary:\n \"List the marketplace orders waiting on the store's acceptance, soonest deadline first, or those named by `ids` (order ids). `acknowledgeBy` is the instant the marketplace cancels an unacknowledged order; `unmappedLines` counts the lines that arrived with nothing behind them.\",\n tags: [\"marketplace\"],\n params: marketplaceParams,\n query: listMarketplaceAcceptancesQuery,\n response: z.object({ data: z.array(pendingAcceptanceSchema) }),\n annotations: { readOnly: true },\n },\n {\n operationId: \"decideMarketplaceOrders\",\n method: \"POST\",\n path: `${BASE}/acceptances`,\n summary:\n \"Accept or refuse one or many marketplace orders on the acceptance clock, all-or-nothing. ACCEPT may carry `admission` (`admitStockPastZero: true` after the store was told an item is short) and `preparationMinutes`. REJECT cancels the order here and asks the marketplace to cancel it, with `reasonCode` from the marketplace's own list (see `listMarketplaceIntegrations`; its first reason when omitted) and, for a reason that needs them, `offendingSkus` from the order. Any problem writes nothing: an unknown code or item is a 422, an order no longer awaiting a decision a 409, and the store's own refusal a 409 with its code (e.g. `MARKETPLACE_STOCK_ASK` with the short items). `validateOnly: true` checks everything without writing.\",\n tags: [\"marketplace\"],\n params: marketplaceParams,\n body: decideMarketplaceOrdersBody,\n response: z.object({ data: z.object({ validateOnly: z.boolean(), decisions: z.array(decidedSchema) }) }),\n annotations: { readOnly: false, destructive: true, openWorld: true },\n },\n] as const satisfies readonly WireMcpTool<z.ZodType>[];\n"],"mappings":";;;;;AAqBO,IAAM,0BAA0B;AAAA,EAC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AE,CAAC;AAAA,IACpG,aAAa,EAAE,UAAU,OAAO,aAAa,MAAM;AAAA,EACrD;AAAA,EACA;AAAA,IACE,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,MAAM,GAAG,IAAI;AAAA,IACb,SACE;AAAA,IACF,MAAM,CAAC,aAAa;AAAA,IACpB,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,UAAU,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,EAAE,CAAC;AAAA,IAC7D,aAAa,EAAE,UAAU,KAAK;AAAA,EAChC;AAAA,EACA;AAAA,IACE,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,MAAM,GAAG,IAAI;AAAA,IACb,SACE;AAAA,IACF,MAAM,CAAC,aAAa;AAAA,IACpB,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,UAAU,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,QAAQ,GAAG,WAAW,EAAE,MAAM,aAAa,EAAE,CAAC,EAAE,CAAC;AAAA,IACvG,aAAa,EAAE,UAAU,OAAO,aAAa,MAAM,WAAW,KAAK;AAAA,EACrE;AACF;","names":[]}
@@ -0,0 +1,478 @@
1
+ import {
2
+ stableUuid
3
+ } from "./chunk-M2V4RFMA.js";
4
+ import {
5
+ asString,
6
+ firstCents,
7
+ firstDate,
8
+ firstString,
9
+ pick,
10
+ toCents,
11
+ verifyHmacSha256Hex
12
+ } from "./chunk-BD7DS3XM.js";
13
+ import {
14
+ answered,
15
+ outboundResultOf,
16
+ tokenGrantResultOf
17
+ } from "./chunk-HEXLCTOG.js";
18
+ import {
19
+ __name
20
+ } from "./chunk-7QVYU63E.js";
21
+
22
+ // src/open-delivery/client.ts
23
+ function assertHttpsUrl(packagePath, name, url) {
24
+ let parsed;
25
+ try {
26
+ parsed = new URL(url);
27
+ } catch {
28
+ throw new Error(`${packagePath}: ${name} is not a URL.`);
29
+ }
30
+ if (parsed.protocol !== "https:") throw new Error(`${packagePath}: ${name} must be https.`);
31
+ }
32
+ __name(assertHttpsUrl, "assertHttpsUrl");
33
+ var TOKEN_MARGIN_MS = 6e4;
34
+ var DEFAULT_TOKEN_SECONDS = 3600;
35
+ function baseOf(ctx, bases) {
36
+ const base = bases[ctx.environment];
37
+ let end = base.length;
38
+ while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;
39
+ return base.slice(0, end);
40
+ }
41
+ __name(baseOf, "baseOf");
42
+ var tokenKey = /* @__PURE__ */ __name((ctx, dialect) => `${dialect.provider}:${ctx.environment}:${ctx.credentials.clientId}`, "tokenKey");
43
+ function tokenOf(body) {
44
+ try {
45
+ const parsed = JSON.parse(body);
46
+ if (typeof parsed.access_token !== "string" || parsed.access_token === "") return null;
47
+ const expires = typeof parsed.expires_in === "number" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;
48
+ return { token: parsed.access_token, expiresInSeconds: expires };
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+ __name(tokenOf, "tokenOf");
54
+ function signed(ctx, dialect, request) {
55
+ if (!dialect.sign) return request;
56
+ return { ...request, headers: { ...request.headers, ...dialect.sign(ctx, request.url, request.body) } };
57
+ }
58
+ __name(signed, "signed");
59
+ async function bearer(ctx, dialect) {
60
+ const cached = ctx.tokens.get(tokenKey(ctx, dialect));
61
+ if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
62
+ const grant = dialect.tokenGrant(ctx);
63
+ const response = await ctx.http(
64
+ signed(ctx, dialect, {
65
+ method: "POST",
66
+ url: `${baseOf(ctx, dialect.bases)}/oauth/token`,
67
+ headers: { "Content-Type": grant.contentType },
68
+ body: grant.body
69
+ })
70
+ );
71
+ if (response.status < 200 || response.status >= 300) {
72
+ const result = tokenGrantResultOf(response);
73
+ return result.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : result;
74
+ }
75
+ const token = tokenOf(response.body);
76
+ if (!token) return { kind: "retry", reason: `${dialect.name} answered the token grant without a token` };
77
+ ctx.tokens.set(tokenKey(ctx, dialect), {
78
+ token: token.token,
79
+ expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1e3
80
+ });
81
+ return { token: token.token };
82
+ }
83
+ __name(bearer, "bearer");
84
+ function urlOf(ctx, dialect, call) {
85
+ const query = call.query && Object.keys(call.query).length > 0 ? `?${new URLSearchParams(call.query).toString()}` : "";
86
+ return `${baseOf(ctx, dialect.bases)}${call.path}${query}`;
87
+ }
88
+ __name(urlOf, "urlOf");
89
+ function requestOf(ctx, dialect, call, token) {
90
+ const body = call.body === void 0 ? void 0 : dialect.serialize(call.body);
91
+ return {
92
+ method: call.method,
93
+ url: urlOf(ctx, dialect, call),
94
+ headers: {
95
+ ...token === null ? {} : { Authorization: `Bearer ${token}` },
96
+ ...body === void 0 ? {} : { "Content-Type": "application/json" },
97
+ ...call.headers
98
+ },
99
+ ...body === void 0 ? {} : { body }
100
+ };
101
+ }
102
+ __name(requestOf, "requestOf");
103
+ async function openDeliveryCall(ctx, dialect, call) {
104
+ const authenticated = call.authenticated ?? true;
105
+ const auth = authenticated ? await bearer(ctx, dialect) : null;
106
+ if (auth && !("token" in auth)) return auth;
107
+ const response = await ctx.http(signed(ctx, dialect, requestOf(ctx, dialect, call, auth?.token ?? null)));
108
+ if (!authenticated || response.status !== 401) return response;
109
+ ctx.tokens.delete(tokenKey(ctx, dialect));
110
+ return { kind: "retry", reason: `${dialect.name} refused the token` };
111
+ }
112
+ __name(openDeliveryCall, "openDeliveryCall");
113
+ var isStop = /* @__PURE__ */ __name((value) => "kind" in value, "isStop");
114
+
115
+ // src/open-delivery/orders.ts
116
+ function callOrder(ctx, dialect, request) {
117
+ const suffix = request.action === null ? "" : `/${request.action}`;
118
+ return openDeliveryCall(ctx, dialect, {
119
+ method: request.method,
120
+ path: `/v1/orders/${encodeURIComponent(request.externalOrderId)}${suffix}`,
121
+ ...request.body === void 0 ? {} : { body: request.body }
122
+ });
123
+ }
124
+ __name(callOrder, "callOrder");
125
+ function alreadyCancelled(response) {
126
+ if (response.status !== 422) return false;
127
+ try {
128
+ return JSON.parse(response.body).cancellationStatus === "CANCELLED";
129
+ } catch {
130
+ return false;
131
+ }
132
+ }
133
+ __name(alreadyCancelled, "alreadyCancelled");
134
+ async function fetched(call) {
135
+ try {
136
+ return await call();
137
+ } catch (error) {
138
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
139
+ }
140
+ }
141
+ __name(fetched, "fetched");
142
+ function openDeliveryFetchOrder(ctx, dialect, order, options) {
143
+ return fetched(async () => {
144
+ const response = await callOrder(ctx, dialect, { method: "GET", externalOrderId: order.externalOrderId, action: null });
145
+ if (isStop(response)) return response;
146
+ const result = outboundResultOf(response);
147
+ if (result.kind !== "accepted") return result;
148
+ let body;
149
+ try {
150
+ body = JSON.parse(response.body);
151
+ } catch {
152
+ return { kind: "refused", status: response.status, message: "the order is not JSON" };
153
+ }
154
+ const prepared = options.prepare ? await options.prepare(ctx, body) : body;
155
+ const normalized = options.normalize(prepared);
156
+ return normalized ? { kind: "order", order: normalized } : { kind: "refused", status: response.status, message: "the order carries no id or no line" };
157
+ });
158
+ }
159
+ __name(openDeliveryFetchOrder, "openDeliveryFetchOrder");
160
+ function openDeliveryConfirm(ctx, dialect, order, input) {
161
+ return answered(async () => {
162
+ const response = await callOrder(ctx, dialect, {
163
+ method: "POST",
164
+ externalOrderId: order.externalOrderId,
165
+ action: "confirm",
166
+ body: {
167
+ orderExternalCode: order.hostOrderCode,
168
+ createdAt: ctx.now.toISOString(),
169
+ ...input.preparationMinutes === null ? {} : { preparationTime: input.preparationMinutes }
170
+ }
171
+ });
172
+ return isStop(response) ? response : outboundResultOf(response);
173
+ });
174
+ }
175
+ __name(openDeliveryConfirm, "openDeliveryConfirm");
176
+ var MAX_OUT_OF_STOCK_ITEMS = 100;
177
+ function openDeliveryRequestCancellation(ctx, dialect, order, input, options) {
178
+ const skus = options.outOfStockAsSkus && input.reason.itemUnavailable && input.offendingSkus.length > 0 ? { outOfStockItems: input.offendingSkus.slice(0, MAX_OUT_OF_STOCK_ITEMS) } : {};
179
+ return answered(async () => {
180
+ const response = await callOrder(ctx, dialect, {
181
+ method: "POST",
182
+ externalOrderId: order.externalOrderId,
183
+ action: "requestCancellation",
184
+ body: {
185
+ reason: input.text === "" ? input.reason.label : input.text,
186
+ code: input.reason.code,
187
+ mode: input.mode,
188
+ ...skus
189
+ }
190
+ });
191
+ if (isStop(response)) return response;
192
+ if (alreadyCancelled(response)) return { kind: "accepted" };
193
+ const result = outboundResultOf(response);
194
+ return result.kind === "refused" && result.status === 400 ? { ...result, own: true } : result;
195
+ });
196
+ }
197
+ __name(openDeliveryRequestCancellation, "openDeliveryRequestCancellation");
198
+ function statusPaths(options) {
199
+ return {
200
+ READY: /* @__PURE__ */ __name(() => ({ action: "readyForPickup" }), "READY"),
201
+ DISPATCHED: /* @__PURE__ */ __name((facts) => facts.deliveredBy === "MERCHANT" ? { action: "dispatch", body: {} } : null, "DISPATCHED"),
202
+ HANDED_OVER: /* @__PURE__ */ __name((facts) => facts.deliveredBy === "MERCHANT" ? { action: "delivered", body: {} } : facts.deliveredBy === null && options.takeoutPickedUp ? { action: "pickedUp", body: {} } : null, "HANDED_OVER")
203
+ };
204
+ }
205
+ __name(statusPaths, "statusPaths");
206
+ function openDeliveryStatus(options) {
207
+ const paths = statusPaths(options);
208
+ return {
209
+ supported: /* @__PURE__ */ __name((facts) => paths[facts.step]?.(facts) != null, "supported"),
210
+ inform(ctx, dialect, order, facts) {
211
+ const path = paths[facts.step]?.(facts) ?? null;
212
+ if (path === null) return Promise.resolve({ kind: "unsupported" });
213
+ return answered(async () => {
214
+ const response = await callOrder(ctx, dialect, {
215
+ method: "POST",
216
+ externalOrderId: order.externalOrderId,
217
+ action: path.action,
218
+ ...path.body === void 0 ? {} : { body: path.body }
219
+ });
220
+ return isStop(response) ? response : outboundResultOf(response);
221
+ });
222
+ }
223
+ };
224
+ }
225
+ __name(openDeliveryStatus, "openDeliveryStatus");
226
+
227
+ // src/open-delivery/reasons.ts
228
+ var OPEN_DELIVERY_MERCHANT_REASON_CODES = [
229
+ "SYSTEMIC_ISSUES",
230
+ "DUPLICATE_APPLICATION",
231
+ "UNAVAILABLE_ITEM",
232
+ "RESTAURANT_WITHOUT_DELIVERY_PERSON",
233
+ "OUTDATED_MENU",
234
+ "ORDER_OUTSIDE_THE_DELIVERY_AREA",
235
+ "BLOCKED_CUSTOMER",
236
+ "OUTSIDE_DELIVERY_HOURS",
237
+ "INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT",
238
+ "RISK_AREA",
239
+ "DELIVERY_PROBLEM"
240
+ ];
241
+ var OPEN_DELIVERY_ITEM_UNAVAILABLE = "UNAVAILABLE_ITEM";
242
+
243
+ // src/open-delivery/merchant.ts
244
+ function categoriesOf(merchantId, entries) {
245
+ const byName = /* @__PURE__ */ new Map();
246
+ for (const entry of entries) {
247
+ const name = entry.categoryName.trim();
248
+ const category = byName.get(name) ?? { id: stableUuid(`${merchantId}:category:${name}`), name, offers: [] };
249
+ category.offers.push(stableUuid(`${entry.ref}:offer`));
250
+ byName.set(name, category);
251
+ }
252
+ return [...byName.values()];
253
+ }
254
+ __name(categoriesOf, "categoriesOf");
255
+ function openDeliveryMenuDocument(input) {
256
+ const { externalMerchantId: merchantId, entries, options } = input;
257
+ const categories = categoriesOf(merchantId, entries);
258
+ return {
259
+ menus: [
260
+ {
261
+ id: stableUuid(`${merchantId}:menu`),
262
+ name: options.menuName,
263
+ externalCode: "menu",
264
+ categoryId: categories.map((category) => category.id)
265
+ }
266
+ ],
267
+ categories: categories.map((category, index) => ({
268
+ id: category.id,
269
+ index,
270
+ name: category.name,
271
+ externalCode: category.name,
272
+ status: "AVAILABLE",
273
+ itemOfferId: category.offers
274
+ })),
275
+ items: entries.map((entry) => ({
276
+ id: stableUuid(`${entry.ref}:item`),
277
+ name: entry.name,
278
+ description: entry.description ?? "",
279
+ externalCode: entry.productId,
280
+ status: "AVAILABLE",
281
+ unit: "UN",
282
+ ...entry.imageUrl === null ? {} : { image: { URL: entry.imageUrl } }
283
+ })),
284
+ itemOffers: entries.map((entry, index) => {
285
+ const value = Math.round(entry.priceCents) / 100;
286
+ return {
287
+ id: stableUuid(`${entry.ref}:offer`),
288
+ itemId: stableUuid(`${entry.ref}:item`),
289
+ index,
290
+ status: "AVAILABLE",
291
+ price: { value, originalValue: value, currency: options.currency }
292
+ };
293
+ })
294
+ };
295
+ }
296
+ __name(openDeliveryMenuDocument, "openDeliveryMenuDocument");
297
+ function openDeliveryMerchantUpdate(ctx, dialect, update) {
298
+ return answered(async () => {
299
+ const response = await openDeliveryCall(ctx, dialect, {
300
+ method: "POST",
301
+ path: update.path,
302
+ ...update.body === void 0 ? {} : { body: update.body },
303
+ ...update.headers === void 0 ? {} : { headers: update.headers }
304
+ });
305
+ return isStop(response) ? response : outboundResultOf(response);
306
+ });
307
+ }
308
+ __name(openDeliveryMerchantUpdate, "openDeliveryMerchantUpdate");
309
+ function openDeliverySwitchAvailability(setStatus) {
310
+ return {
311
+ kind: "switch",
312
+ pause: /* @__PURE__ */ __name(async (ctx, request) => {
313
+ const result = await setStatus(ctx, request.merchantId, "UNAVAILABLE");
314
+ return result.kind === "accepted" ? { kind: "paused", externalId: null, until: request.until } : result;
315
+ }, "pause"),
316
+ resume: /* @__PURE__ */ __name((ctx, ref) => setStatus(ctx, ref.merchantId, "AVAILABLE"), "resume")
317
+ };
318
+ }
319
+ __name(openDeliverySwitchAvailability, "openDeliverySwitchAvailability");
320
+
321
+ // src/open-delivery/normalize.ts
322
+ var CREATED = "CREATED";
323
+ var CANCELLED = "CANCELLED";
324
+ var LIFECYCLE_OF = { DISPATCHED: "DISPATCHED", CONCLUDED: "CONCLUDED" };
325
+ var CANCELLATION_REQUEST_DENIED = "CANCELLATION_REQUEST_DENIED";
326
+ function verifyOpenDeliverySignature(rawBody, signature, webhookSecret) {
327
+ if (!webhookSecret) return false;
328
+ return verifyHmacSha256Hex(rawBody, signature, webhookSecret);
329
+ }
330
+ __name(verifyOpenDeliverySignature, "verifyOpenDeliverySignature");
331
+ function normalizeOpenDeliveryEventAs(provider, payload) {
332
+ const externalOrderId = firstString(payload, [["orderId"]]);
333
+ if (!externalOrderId) return null;
334
+ const eventType = (firstString(payload, [["eventType"]]) ?? "UNKNOWN").toUpperCase();
335
+ const cancelled = eventType === CANCELLED;
336
+ const denied = eventType === CANCELLATION_REQUEST_DENIED;
337
+ return {
338
+ provider,
339
+ // The spec's own event id. The fallback is deterministic so a redelivery
340
+ // still collides on the inbox's unique index.
341
+ eventId: firstString(payload, [["eventId"]]) ?? `${externalOrderId}:${eventType}`,
342
+ eventType,
343
+ externalMerchantId: null,
344
+ externalOrderId,
345
+ order: null,
346
+ orderToFetch: eventType === CREATED,
347
+ cancelled,
348
+ cancellationOutcome: cancelled ? "CONFIRMED" : denied ? "FAILED" : null,
349
+ ...LIFECYCLE_OF[eventType] ? { lifecycle: LIFECYCLE_OF[eventType] } : {}
350
+ };
351
+ }
352
+ __name(normalizeOpenDeliveryEventAs, "normalizeOpenDeliveryEventAs");
353
+ function priceCents(source, ...path) {
354
+ return toCents(pick(source, ...path, "value"));
355
+ }
356
+ __name(priceCents, "priceCents");
357
+ function lineNote(item, fraction) {
358
+ const rawOptions = pick(item, "options");
359
+ const options = (Array.isArray(rawOptions) ? rawOptions : []).map((option) => {
360
+ const name = asString(pick(option, "name"));
361
+ const quantity = Number(pick(option, "quantity") ?? 1);
362
+ return name && quantity > 1 ? `${quantity}x ${name}` : name;
363
+ }).filter((name) => name !== null);
364
+ const parts = [fraction, options.join(", ") || null, firstString(item, [["specialInstructions"]])];
365
+ const note = parts.filter((part) => part !== null).join(" \xB7 ");
366
+ return note === "" ? null : note;
367
+ }
368
+ __name(lineNote, "lineNote");
369
+ function lineTotalCents(item, quantity) {
370
+ const total = priceCents(item, "totalPrice");
371
+ if (total !== null) return total;
372
+ const unit = priceCents(item, "unitPrice") ?? 0;
373
+ return Math.round(unit * quantity) + (priceCents(item, "optionsPrice") ?? 0);
374
+ }
375
+ __name(lineTotalCents, "lineTotalCents");
376
+ function quantityOf(item) {
377
+ const stated = Number(pick(item, "quantity") ?? 1);
378
+ return Number.isFinite(stated) && stated > 0 ? stated : 1;
379
+ }
380
+ __name(quantityOf, "quantityOf");
381
+ function splitWhole(total, quantity) {
382
+ const floor = Math.floor(total / quantity);
383
+ const remainder = total - floor * quantity;
384
+ if (remainder === 0) return [{ quantity, unitPriceCents: floor }];
385
+ const rest = quantity === 1 ? [] : [{ quantity: quantity - 1, unitPriceCents: floor }];
386
+ return [...rest, { quantity: 1, unitPriceCents: floor + remainder }];
387
+ }
388
+ __name(splitWhole, "splitWhole");
389
+ function readLines(item) {
390
+ const name = firstString(item, [["name"]]);
391
+ const sku = firstString(item, [["externalCode"], ["id"]]) ?? name;
392
+ if (!sku) return [];
393
+ const quantity = quantityOf(item);
394
+ const whole = Number.isInteger(quantity);
395
+ const fraction = whole ? null : `${quantity} ${firstString(item, [["unit"]]) ?? ""}`.trim();
396
+ const total = lineTotalCents(item, quantity);
397
+ const parts = whole ? splitWhole(total, quantity) : [{ quantity: 1, unitPriceCents: total }];
398
+ const note = lineNote(item, fraction);
399
+ return parts.map((part) => ({ externalSku: sku, name: name ?? sku, ...part, note }));
400
+ }
401
+ __name(readLines, "readLines");
402
+ function readOrderType(order) {
403
+ const stated = firstString(order, [["type"]])?.toUpperCase();
404
+ return stated === "DELIVERY" || stated === "TAKEOUT" ? stated : null;
405
+ }
406
+ __name(readOrderType, "readOrderType");
407
+ function readDeliveredBy(order) {
408
+ const stated = firstString(order, [["delivery", "deliveredBy"]])?.toUpperCase();
409
+ return stated === "MERCHANT" || stated === "MARKETPLACE" ? stated : null;
410
+ }
411
+ __name(readDeliveredBy, "readDeliveredBy");
412
+ function readAddress(order, missingStreetNumber) {
413
+ const raw = pick(order, "delivery", "deliveryAddress");
414
+ const street = firstString(raw, [["street"], ["streetName"]]);
415
+ if (street === null) return null;
416
+ return {
417
+ street,
418
+ number: firstString(raw, [["number"], ["streetNumber"]]) ?? missingStreetNumber,
419
+ neighborhood: firstString(raw, [["district"], ["neighborhood"]]) ?? "",
420
+ complement: firstString(raw, [["complement"]]),
421
+ reference: firstString(raw, [["reference"]]),
422
+ postalCode: firstString(raw, [["postalCode"]])?.replace(/\D/g, "") || null,
423
+ city: firstString(raw, [["city"]]),
424
+ state: firstString(raw, [["state"]])?.replace(/^[A-Z]{2}-/u, "") ?? null
425
+ };
426
+ }
427
+ __name(readAddress, "readAddress");
428
+ function normalizeOpenDeliveryOrderAs(provider, order, options) {
429
+ const externalOrderId = firstString(order, [["id"]]);
430
+ const rawItems = pick(order, "items");
431
+ const lines = (Array.isArray(rawItems) ? rawItems : []).flatMap(readLines);
432
+ if (!externalOrderId || lines.length === 0) return null;
433
+ return {
434
+ provider,
435
+ externalOrderId,
436
+ externalDisplayId: firstString(order, [["displayId"]]),
437
+ externalMerchantId: firstString(order, [["merchant", "id"]]),
438
+ buyer: {
439
+ externalId: firstString(order, [["customer", "id"]]),
440
+ name: firstString(order, [["customer", "name"]]),
441
+ phone: firstString(order, [["customer", "phone", "number"]])
442
+ },
443
+ lines,
444
+ // The line sum is the FALLBACK: the stated total carries the fees and
445
+ // discounts the lines do not, and it is the number on the receipt.
446
+ totalCents: firstCents(order, [["total", "orderAmount", "value"]]) ?? lines.reduce((sum, line) => sum + line.unitPriceCents * line.quantity, 0),
447
+ commissionCents: null,
448
+ deliveryDueAt: firstDate(order, [
449
+ ["delivery", "estimatedDeliveryDateTime"],
450
+ ["takeout", "takeoutDateTime"],
451
+ ["schedule", "scheduledDateTimeEnd"]
452
+ ]),
453
+ placedAt: firstDate(order, [["createdAt"]]) ?? /* @__PURE__ */ new Date(),
454
+ orderType: readOrderType(order),
455
+ deliveredBy: readDeliveredBy(order),
456
+ deliveryAddress: readAddress(order, options.missingStreetNumber)
457
+ };
458
+ }
459
+ __name(normalizeOpenDeliveryOrderAs, "normalizeOpenDeliveryOrderAs");
460
+
461
+ export {
462
+ assertHttpsUrl,
463
+ openDeliveryCall,
464
+ isStop,
465
+ openDeliveryFetchOrder,
466
+ openDeliveryConfirm,
467
+ openDeliveryRequestCancellation,
468
+ openDeliveryStatus,
469
+ OPEN_DELIVERY_MERCHANT_REASON_CODES,
470
+ OPEN_DELIVERY_ITEM_UNAVAILABLE,
471
+ openDeliveryMenuDocument,
472
+ openDeliveryMerchantUpdate,
473
+ openDeliverySwitchAvailability,
474
+ verifyOpenDeliverySignature,
475
+ normalizeOpenDeliveryEventAs,
476
+ normalizeOpenDeliveryOrderAs
477
+ };
478
+ //# sourceMappingURL=chunk-PYHNM47K.js.map