@12-apps/marketplace 1.3.0 → 1.5.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 (59) hide show
  1. package/ADOPTING.md +47 -0
  2. package/README.md +122 -1
  3. package/dist/99food/index.d.ts +33 -2
  4. package/dist/99food/index.js +34 -2
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-0l_EmuJA.d.ts → adapter-CCWMqt2g.d.ts} +275 -3
  7. package/dist/{chunk-XUAFXNOH.js → chunk-FKUEFVVA.js} +396 -4
  8. package/dist/chunk-FKUEFVVA.js.map +1 -0
  9. package/dist/{chunk-RVBTARIY.js → chunk-RGMSD7S7.js} +1 -1
  10. package/dist/chunk-RGMSD7S7.js.map +1 -0
  11. package/dist/{chunk-AYYBRQJV.js → chunk-UONWZIBO.js} +43 -3
  12. package/dist/chunk-UONWZIBO.js.map +1 -0
  13. package/dist/chunk-WN2EK4KX.js +15 -0
  14. package/dist/chunk-WN2EK4KX.js.map +1 -0
  15. package/dist/{engine-CZsP8KWd.d.ts → engine-C3uq_BJd.d.ts} +252 -2
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +2 -2
  18. package/dist/ifood/index.d.ts +44 -2
  19. package/dist/ifood/index.js +441 -1
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +342 -3
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/server.d.ts +4 -2
  25. package/dist/manifest/server.js +2 -2
  26. package/dist/rappi/index.d.ts +15 -2
  27. package/dist/rappi/index.js +56 -2
  28. package/dist/rappi/index.js.map +1 -1
  29. package/dist/server/index.d.ts +18 -7
  30. package/dist/server/index.js +4 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +67 -1
  33. package/prisma/migrations/20261113230000_marketplace_store_pause/migration.sql +70 -0
  34. package/src/99food/index.ts +10 -0
  35. package/src/99food/pause.ts +56 -0
  36. package/src/core/adapter.ts +19 -2
  37. package/src/core/catalogue-read-port.ts +151 -0
  38. package/src/core/catalogue-read.ts +51 -0
  39. package/src/core/engine.ts +46 -0
  40. package/src/core/pause-job.ts +381 -0
  41. package/src/core/pause-port.ts +110 -0
  42. package/src/core/pause-retired.ts +139 -0
  43. package/src/core/pause-store.ts +151 -0
  44. package/src/core/pause-sweep.ts +148 -0
  45. package/src/core/pause.ts +316 -0
  46. package/src/core/ports.ts +11 -0
  47. package/src/ifood/catalogue-read.ts +187 -0
  48. package/src/ifood/catalogue-snapshot.ts +246 -0
  49. package/src/ifood/index.ts +9 -0
  50. package/src/ifood/pause.ts +257 -0
  51. package/src/index.ts +39 -0
  52. package/src/rappi/index.ts +11 -0
  53. package/src/rappi/outbound.ts +2 -2
  54. package/src/rappi/pause.ts +98 -0
  55. package/src/server/index.ts +1 -0
  56. package/src/server/jobs.ts +64 -4
  57. package/dist/chunk-AYYBRQJV.js.map +0 -1
  58. package/dist/chunk-RVBTARIY.js.map +0 -1
  59. package/dist/chunk-XUAFXNOH.js.map +0 -1
@@ -9,10 +9,11 @@ import {
9
9
  upsertMarketplaceMenuLinksBody
10
10
  } from "./chunk-UYFYGGCS.js";
11
11
  import {
12
+ AvailabilityRetryError,
12
13
  CatalogueRetryError,
13
14
  FetchOrderRetryError,
14
15
  OutboundRetryError
15
- } from "./chunk-XUAFXNOH.js";
16
+ } from "./chunk-FKUEFVVA.js";
16
17
  import {
17
18
  __name
18
19
  } from "./chunk-7QVYU63E.js";
@@ -404,6 +405,42 @@ var outboundSweep = {
404
405
  );
405
406
  }, "handle")
406
407
  };
408
+ var MARKETPLACE_AVAILABILITY_ATTEMPTS = 3;
409
+ var availability = {
410
+ name: "availability",
411
+ attempts: MARKETPLACE_AVAILABILITY_ATTEMPTS,
412
+ // Short: a store is open on the marketplace while the kitchen is paused.
413
+ backoff: { type: "exponential", delayMs: 1e4 },
414
+ handle: /* @__PURE__ */ __name(async (payload, deps, context) => {
415
+ try {
416
+ const outcome = await deps.engine.runAvailability(payload, {
417
+ attempt: context.attempt,
418
+ maxAttempts: context.maxAttempts
419
+ });
420
+ if (outcome.kind === "skipped") {
421
+ context.logger.info(`marketplace.availability: ${payload.provider} ${payload.clientId} skipped: ${outcome.reason}`);
422
+ }
423
+ } catch (error) {
424
+ if (error instanceof AvailabilityRetryError) context.logger.warn(`marketplace.availability: ${error.message}`);
425
+ throw error;
426
+ }
427
+ }, "handle")
428
+ };
429
+ var availabilitySweep = {
430
+ name: "availability-sweep",
431
+ queue: MARKETPLACE_SWEEP_QUEUE,
432
+ concurrency: 1,
433
+ schedule: { pattern: "*/5 * * * *", timezone: "UTC" },
434
+ attempts: 1,
435
+ lease: { ttlMs: SWEEP_LEASE_MS },
436
+ handle: /* @__PURE__ */ __name(async (_payload, deps, context) => {
437
+ const result = await deps.engine.sweepAvailability();
438
+ if (result.expired + result.requeued + result.givenUp === 0) return;
439
+ context.logger.info(
440
+ `marketplace.availability-sweep: resumed ${result.expired} expired pause(s), re-queued ${result.requeued}, gave up on ${result.givenUp}.`
441
+ );
442
+ }, "handle")
443
+ };
407
444
  var MARKETPLACE_JOBS = {
408
445
  namespace: "marketplace",
409
446
  blueprints: {
@@ -412,7 +449,9 @@ var MARKETPLACE_JOBS = {
412
449
  outbound,
413
450
  "fetch-order": fetchOrder,
414
451
  catalogue,
415
- "outbound-sweep": outboundSweep
452
+ "outbound-sweep": outboundSweep,
453
+ availability,
454
+ "availability-sweep": availabilitySweep
416
455
  }
417
456
  };
418
457
 
@@ -430,7 +469,8 @@ export {
430
469
  MARKETPLACE_SWEEP_QUEUE,
431
470
  MARKETPLACE_OUTBOUND_ATTEMPTS,
432
471
  MARKETPLACE_FETCH_ORDER_ATTEMPTS,
472
+ MARKETPLACE_AVAILABILITY_ATTEMPTS,
433
473
  MARKETPLACE_JOBS,
434
474
  createApiMarketplace
435
475
  };
436
- //# sourceMappingURL=chunk-AYYBRQJV.js.map
476
+ //# sourceMappingURL=chunk-UONWZIBO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server/http.ts","../src/server/webhook.ts","../src/server/routes.ts","../src/server/jobs.ts","../src/server/index.ts"],"sourcesContent":["import type { z } from \"zod\";\n\nimport type { WireResponse } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceLogger } from \"../core/ports\";\nimport type { MarketplaceServerCopy } from \"./copy\";\n\n/**\n * What the route descriptors share: the config, the actor, and the two answer\n * shapes every handler uses.\n */\n\n/** Whoever the host resolved: the tenant this request may act inside. */\nexport interface MarketplaceActor {\n /** The tenant's id — every engine call is scoped to it. */\n clientId: string;\n /** The person, for the audit line an archive writes. Null for a system caller. */\n userId?: string | null;\n}\n\nexport interface MarketplaceApiConfig {\n /** The mounted engine (`createMarketplaceEngine`). */\n engine: MarketplaceEngine;\n /** Every sentence the routes answer a person with. Required, no defaults. */\n copy: MarketplaceServerCopy;\n /**\n * Which tenant a webhook's URL slug names, or null for none. The webhook is\n * unauthenticated by design (a marketplace cannot sign in), so the tenant\n * comes from the URL and is then proved by that tenant's signature secret.\n */\n tenantBySlug: (slug: string) => Promise<string | null>;\n /** Where the routes say what they refused. The manifest's `marketplace` namespace. */\n logger: MarketplaceLogger;\n}\n\n/** A 200 in the `{ data }` envelope. */\nexport function ok(data: unknown): WireResponse {\n return { status: 200, body: { data } };\n}\n\n/** A refusal in the `{ error }` envelope, with any extra fields beside it. */\nexport function refuse(status: number, error: string, extra: Record<string, unknown> = {}): WireResponse {\n return { status, body: { error, ...extra } };\n}\n\n/** The parsed value, or the 422 that names every problem and its path. */\nexport function parse<T>(\n schema: z.ZodType<T>,\n value: unknown,\n copy: MarketplaceServerCopy,\n): { ok: true; value: T } | { ok: false; response: WireResponse } {\n const parsed = schema.safeParse(value ?? {});\n if (parsed.success) return { ok: true, value: parsed.data };\n const problems = parsed.error.issues.map((issue) => ({\n path: issue.path.map((segment) => (typeof segment === \"number\" ? segment : String(segment))),\n code: \"INVALID_INPUT\",\n message: issue.message,\n }));\n return { ok: false, response: refuse(422, copy.invalidInput, { problems }) };\n}\n\n/** An ISO string, or null. */\nexport function iso(value: Date | null | undefined): string | null {\n return value ? value.toISOString() : null;\n}\n","import type { WireRequest, WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { IngestionTarget } from \"../core/integration\";\nimport type { MarketplaceApiConfig } from \"./http\";\n\n/**\n * `POST /webhooks/marketplace/:tenantSlug/:provider` — inbound deliveries for\n * ONE store, from any registered marketplace.\n *\n * PUBLIC by design (`kind: \"webhook\"`): a marketplace cannot authenticate as a\n * user. The store is attributed from the URL slug, then the delivery is\n * verified against THAT store's secret, through the provider's own adapter\n * (which header carries the signature, and how it is computed) — the route\n * itself knows no marketplace.\n *\n * It answers 2xx for almost everything, deliberately. A marketplace\n * redelivers on any non-2xx, so the only failures worth signalling are the\n * ones a redelivery could fix: a genuine processing failure answers 500, and\n * the inbox row it left is retried by the sweep regardless. Refusals (unknown\n * slug, no connection, bad signature) answer 401, indistinguishably, so a\n * prober cannot learn which stores exist. The bodies are machine codes: the\n * reader is a server, not a person.\n */\n\nconst UNAUTHORIZED: WireResponse = { status: 401, body: { error: \"unauthorized\" } };\n\n/**\n * The tenant the slug names and its connection to this marketplace, or the\n * 401 that ends the request. A blob that will not open is a 401 too, logged:\n * a key problem must never read as \"no secret configured\".\n */\nasync function connectionOf(\n config: MarketplaceApiConfig,\n tenantSlug: string,\n provider: string,\n): Promise<{ clientId: string; target: IngestionTarget } | WireResponse> {\n const clientId = await config.tenantBySlug(tenantSlug);\n if (!clientId) {\n config.logger.warn(`marketplace.webhook: unknown tenant slug \"${tenantSlug}\" (${provider})`);\n return UNAUTHORIZED;\n }\n try {\n const target = await config.engine.target(clientId, provider);\n // No connection at all: refused rather than stored — without one there is\n // no secret to verify against.\n return target ? { clientId, target } : UNAUTHORIZED;\n } catch (error) {\n config.logger.error(\n `marketplace.webhook: ${tenantSlug} ${provider} credentials do not open: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n return UNAUTHORIZED;\n }\n}\n\n/** The verified, parsed delivery, or the answer that ends the request. */\nasync function admit(\n config: MarketplaceApiConfig,\n request: WireRequest<unknown>,\n): Promise<{ clientId: string; provider: string; payload: unknown; target: IngestionTarget } | WireResponse> {\n const { tenantSlug = \"\", provider = \"\" } = request.params;\n const { engine } = config;\n if (!engine.knows(provider)) return { status: 404, body: { error: \"unknown_provider\" } };\n const raw = request.request;\n if (!raw) return { status: 400, body: { error: \"raw_request_required\" } };\n\n const connection = await connectionOf(config, tenantSlug, provider);\n if (\"status\" in connection) return connection;\n const rawBody = await raw.text();\n const signature = engine.readSignature(provider, (name) => raw.headers.get(name));\n if (!engine.verifySignature(provider, rawBody, signature, connection.target.webhookSecret)) {\n config.logger.warn(`marketplace.webhook: ${tenantSlug} ${provider} signature rejected`);\n return UNAUTHORIZED;\n }\n try {\n return { ...connection, provider, payload: JSON.parse(rawBody) as unknown };\n } catch {\n return { status: 400, body: { error: \"invalid_json\" } };\n }\n}\n\n/** Record and act on one verified delivery. */\nasync function handleWebhook(config: MarketplaceApiConfig, request: WireRequest<unknown>): Promise<WireResponse> {\n const admitted = await admit(config, request);\n if (\"status\" in admitted) return admitted;\n const { clientId, provider, payload, target } = admitted;\n const { engine } = config;\n\n const event = engine.normalize(provider, payload);\n if (!event) {\n // Nothing the adapter can key on. 200: redelivering an unreadable payload\n // produces an identical unreadable payload.\n config.logger.warn(`marketplace.webhook: ${provider} payload did not normalize`);\n return { status: 200, body: { received: true, ignored: \"unrecognized_payload\" } };\n }\n const outcome = await engine.deliver({\n clientId,\n event,\n payload,\n // A DISABLED connection still stores its deliveries and ingests nothing;\n // the retry sweep ingests them if the store turns it back on.\n settings: target.enabled ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds } : null,\n });\n if (outcome.kind === \"failed\") {\n return { status: 500, body: { received: true, error: outcome.reason } };\n }\n return { status: 200, body: { received: true, outcome: outcome.kind } };\n}\n\n/** The webhook descriptor. Raw body required: signatures are computed over bytes. */\nexport function webhookRoute(config: MarketplaceApiConfig): WireRoute<unknown> {\n return {\n method: \"POST\",\n path: \"/webhooks/marketplace/:tenantSlug/:provider\",\n kind: \"webhook\",\n handle: (request) => handleWebhook(config, request),\n };\n}\n","import type { WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { BulkProblem } from \"../core/bulk\";\nimport type { DecisionProblem } from \"../core/cancellation\";\nimport type { MarketplaceIntegrationView } from \"../core/integration\";\nimport type { MarketplaceMenuLinkView } from \"../core/menu-links\";\nimport { MARKETPLACE_DECIDE, MARKETPLACE_MANAGE } from \"./contribution\";\nimport type { MarketplaceServerCopy } from \"./copy\";\nimport { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from \"./http\";\nimport {\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nimport { webhookRoute } from \"./webhook\";\n\n/**\n * The marketplace HTTP surface as framework-neutral wiring descriptors: the\n * webhook every marketplace posts to, and, per entity, one read and one bulk\n * write — connections, SKU links, decisions — for a store's staff and its MCP\n * tools alike.\n *\n * There is no authentication, tenant resolution or RBAC in here: each\n * descriptor DECLARES the permission it needs and the host's guard answers it;\n * the actor arrives already resolved. Paths are relative to the host's mount.\n */\n\nexport type MarketplaceRoute = WireRoute<MarketplaceActor> | WireRoute<unknown>;\n\nconst BASE = \"/admin/:tenantSlug/marketplace\";\n\n/** The 409 code of a decision on an order that is no longer on the clock. */\nexport const ORDER_NOT_PENDING_CODE = \"MARKETPLACE_ORDER_NOT_PENDING\";\n\nconst NOT_PENDING = new Set([\"NOT_FOUND\", \"ALREADY_DECIDED\", \"EXPIRED\", \"CONFLICT\"]);\n\n/** A connection as the read returns it: dates as ISO, the adapter's half beside it. */\nfunction integrationOut(config: MarketplaceApiConfig, row: MarketplaceIntegrationView) {\n const adapter = config.engine.adapter(row.provider);\n return {\n ...row,\n lastEventAt: iso(row.lastEventAt),\n lastVerifiedAt: iso(row.lastVerifiedAt),\n archivedAt: iso(row.archivedAt),\n capabilities: adapter ? adapter.capabilities : null,\n reasons: adapter ? [...adapter.cancellationReasons()] : [],\n };\n}\n\nfunction linkOut(link: MarketplaceMenuLinkView) {\n return { ...link, lastSeenAt: link.lastSeenAt.toISOString() };\n}\n\n/** Each problem with its sentence; a host refusal keeps the host's own words. */\nfunction problemsOut(copy: MarketplaceServerCopy, problems: readonly (BulkProblem | DecisionProblem)[]) {\n return problems.map((problem) => {\n const host = \"host\" in problem ? problem.host : undefined;\n return {\n ...problem,\n message: host?.message ?? copy.problems[problem.code],\n ...(host ? { hostCode: host.code, details: host.details } : {}),\n };\n });\n}\n\n/** A refused bulk write: 422, nothing saved, every problem with its path. */\nfunction refusedBulk(copy: MarketplaceServerCopy, problems: readonly BulkProblem[]): WireResponse {\n return refuse(422, copy.nothingSaved, { problems: problemsOut(copy, problems) });\n}\n\n/**\n * A refused decision call. The host's own refusal is a 409 carrying ITS code\n * (`MARKETPLACE_STOCK_ASK` and the short lines in `details`); an order no\n * longer on the clock a 409; anything else (a reason, an item) a 422.\n */\nfunction refusedDecisions(copy: MarketplaceServerCopy, problems: readonly DecisionProblem[]): WireResponse {\n const out = problemsOut(copy, problems);\n const host = problems.find((problem) => problem.code === \"HOST_REFUSED\")?.host;\n if (host) return refuse(409, host.message, { code: host.code, details: host.details, problems: out });\n if (problems.some((problem) => NOT_PENDING.has(problem.code))) {\n return refuse(409, copy.orderNoLongerPending, { code: ORDER_NOT_PENDING_CODE, problems: out });\n }\n return refuse(422, copy.nothingSaved, { problems: out });\n}\n\nfunction integrationRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceIntegrationsQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const rows = await engine.integrations(actor.clientId, {\n providers: parsed.value.ids,\n includeArchived: parsed.value.includeArchived === \"true\",\n });\n return ok(rows.map((row) => integrationOut(config, row)));\n },\n },\n {\n method: \"PUT\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceIntegrationsBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertIntegrations({\n clientId: actor.clientId,\n actorId: actor.userId ?? null,\n validateOnly: parsed.value.validateOnly,\n rows: parsed.value.integrations.map((row) =>\n \"credentials\" in row && row.credentials\n ? { ...row, credentials: { ...row.credentials, webhookSecret: row.credentials.webhookSecret ?? null } }\n : row,\n ) as Parameters<typeof engine.upsertIntegrations>[0][\"rows\"],\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, integrations: result.rows.map((row) => integrationOut(config, row)) });\n },\n },\n ];\n}\n\nfunction menuLinkRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceMenuLinksQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const links = await engine.menuLinks({\n clientId: actor.clientId,\n provider: parsed.value.provider,\n unmappedOnly: parsed.value.unmapped === \"true\",\n ids: parsed.value.ids,\n });\n return ok(links.map(linkOut));\n },\n },\n {\n method: \"PUT\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceMenuLinksBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertMenuLinks({\n clientId: actor.clientId,\n rows: parsed.value.links,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, links: result.rows.map(linkOut) });\n },\n },\n ];\n}\n\nfunction acceptanceRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceAcceptancesQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const pending = await engine.pending(actor.clientId, parsed.value.ids);\n return ok(\n pending.map((order) => ({\n ...order,\n acknowledgeBy: iso(order.acknowledgeBy),\n externalDueAt: iso(order.externalDueAt),\n })),\n );\n },\n },\n {\n method: \"POST\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, body }) => {\n const parsed = parse(decideMarketplaceOrdersBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.decideMany({\n clientId: actor.clientId,\n decisions: parsed.value.decisions,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedDecisions(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, decisions: result.rows });\n },\n },\n ];\n}\n\n/** The whole surface, in mount order. */\nexport function marketplaceRoutes(config: MarketplaceApiConfig): MarketplaceRoute[] {\n return [\n webhookRoute(config),\n ...integrationRoutes(config),\n ...menuLinkRoutes(config),\n ...acceptanceRoutes(config),\n ];\n}\n","import type { JobsContribution, WireJobBlueprint } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport { CatalogueRetryError, type CatalogueJobPayload } from \"../core/catalogue-job\";\nimport { FetchOrderRetryError, type FetchOrderJobPayload } from \"../core/fetch-order\";\nimport { OutboundRetryError } from \"../core/outbound\";\nimport type { OutboundJobPayload } from \"../core/outbound-queue\";\nimport { AvailabilityRetryError } from \"../core/pause-job\";\nimport type { AvailabilityJobPayload } from \"../core/pause-store\";\n\n/**\n * The engine's eight jobs, declared here because every number in them is the\n * engine's knowledge, not a host's:\n *\n * - `expire-acceptances`, every minute: the unit being measured is minutes (a\n * default window is five), so a coarser tick would make \"expired\" mean\n * anywhere from five to twenty.\n * - `reconcile-inbox`, every five minutes: nothing races a deadline here, and\n * each pass re-runs real ingestion work; the engine's attempt bound retires\n * a payload that will never succeed.\n * - `outbound`, on demand: one call to a marketplace, three attempts with\n * backoff. Its idempotency is the ROW's (the engine re-reads it), never the\n * queue's dedupe alone.\n * - `fetch-order`, on demand: one GET of an order a marketplace's event only\n * announced (`orderToFetch`), then the one ingest path. Three attempts with\n * backoff; the reconciliation sweep re-queues a row still owed.\n * - `catalogue`, on demand: one publish or withdraw of one product on one\n * marketplace's catalogue (FUT-4768). Three attempts with backoff; the\n * last one stamps FAILED with a failure code.\n * - `outbound-sweep`, every five minutes: re-queues every call a row still\n * owes (a PENDING request, an accept with no confirm stamp, a catalogue\n * publish or withdraw on its way) once it is older than the job's own retry\n * span, so a refused enqueue or a dead process loses nothing.\n * - `availability`, on demand: brings one marketplace in line with the host's\n * last pause or resume ask for one store (FUT-4851). Three attempts with\n * backoff; the last one stamps FAILED with a failure code.\n * - `availability-sweep`, every five minutes: resumes a pause past its\n * `until` (the host stopped renewing it), re-queues an ask still owed, and\n * gives up on one older than a day.\n *\n * What stays the host's: whether to run them at all, on which runtime, and the\n * lease implementation. A host with no worker declines `jobs` in writing.\n *\n * Bound with `{ engine }`, these arrive at a runner as\n * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,\n * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.catalogue`,\n * `marketplace.outbound-sweep`, `marketplace.availability` and\n * `marketplace.availability-sweep`.\n */\n\n/** What the host closes over at bind time: the mounted engine. */\nexport interface MarketplaceJobDeps {\n engine: Pick<\n MarketplaceEngine,\n | \"expireLapsed\"\n | \"retryable\"\n | \"reprocess\"\n | \"runOutbound\"\n | \"runFetchOrder\"\n | \"runCatalogue\"\n | \"sweepOutbound\"\n | \"runAvailability\"\n | \"sweepAvailability\"\n >;\n}\n\n/** The single-flight queue name (`@12-apps/jobs`' `SWEEP_QUEUE`), as a literal. */\nexport const MARKETPLACE_SWEEP_QUEUE = \"sweeps\";\n\n/** How long one sweep pass may hold its name. */\nconst SWEEP_LEASE_MS = 5 * 60_000;\n\n/** The outbound job's attempts: the last one stamps the failure. */\nexport const MARKETPLACE_OUTBOUND_ATTEMPTS = 3;\n\nconst expireAcceptances: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"expire-acceptances\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"* * * * *\", timezone: \"UTC\" },\n // Never retried by the queue: the next tick re-finds everything from the rows.\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.expireLapsed();\n if (result.expired === 0) return;\n context.logger.info(\n `marketplace.expire-acceptances: expired ${result.expired} order(s) across ${result.tenants} tenant(s).`,\n );\n },\n};\n\nconst reconcileInbox: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"reconcile-inbox\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const pending = await deps.engine.retryable();\n let ingested = 0;\n // One event's failure never wedges the batch: `reprocess` never throws.\n for (const event of pending) {\n const outcome = await deps.engine.reprocess(event);\n if (outcome.kind === \"ingested\") ingested += 1;\n }\n if (pending.length === 0) return;\n context.logger.info(\n `marketplace.reconcile-inbox: re-ran ${pending.length} stored delivery(ies), ${ingested} became order(s).`,\n );\n },\n};\n\nconst outbound: WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps> = {\n name: \"outbound\",\n attempts: MARKETPLACE_OUTBOUND_ATTEMPTS,\n backoff: { type: \"exponential\", delayMs: 30_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runOutbound(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.outbound: ${payload.action} ${payload.orderId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof OutboundRetryError) context.logger.warn(`marketplace.outbound: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The fetch job's attempts: the last one settles the inbox row FAILED. */\nexport const MARKETPLACE_FETCH_ORDER_ATTEMPTS = 3;\n\nconst fetchOrder: WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps> = {\n name: \"fetch-order\",\n attempts: MARKETPLACE_FETCH_ORDER_ATTEMPTS,\n // Short: an order waiting for its body is on the store's acceptance clock.\n backoff: { type: \"exponential\", delayMs: 5_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runFetchOrder(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.fetch-order: inbox ${payload.inboxId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof FetchOrderRetryError) context.logger.warn(`marketplace.fetch-order: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The catalogue job's attempts: the last one stamps FAILED. */\nconst MARKETPLACE_CATALOGUE_ATTEMPTS = 3;\n\nconst catalogue: WireJobBlueprint<CatalogueJobPayload, MarketplaceJobDeps> = {\n name: \"catalogue\",\n attempts: MARKETPLACE_CATALOGUE_ATTEMPTS,\n // Short: a person is watching the switch say \"sending\".\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runCatalogue(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.catalogue: ${payload.action} ${payload.publicationId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof CatalogueRetryError) context.logger.warn(`marketplace.catalogue: ${error.message}`);\n throw error;\n }\n },\n};\n\nconst outboundSweep: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"outbound-sweep\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.sweepOutbound();\n const idle = result.requeued + result.givenUp + result.timedOut + result.catalogueRequeued === 0;\n if (idle) return;\n context.logger.info(\n `marketplace.outbound-sweep: re-queued ${result.requeued} call(s) and ${result.catalogueRequeued} catalogue ` +\n `call(s), timed out ${result.timedOut} cancellation request(s), gave up on ${result.givenUp}.`,\n );\n },\n};\n\n/** The availability job's attempts: the last one stamps FAILED. */\nexport const MARKETPLACE_AVAILABILITY_ATTEMPTS = 3;\n\nconst availability: WireJobBlueprint<AvailabilityJobPayload, MarketplaceJobDeps> = {\n name: \"availability\",\n attempts: MARKETPLACE_AVAILABILITY_ATTEMPTS,\n // Short: a store is open on the marketplace while the kitchen is paused.\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runAvailability(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.availability: ${payload.provider} ${payload.clientId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof AvailabilityRetryError) context.logger.warn(`marketplace.availability: ${error.message}`);\n throw error;\n }\n },\n};\n\nconst availabilitySweep: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"availability-sweep\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.sweepAvailability();\n if (result.expired + result.requeued + result.givenUp === 0) return;\n context.logger.info(\n `marketplace.availability-sweep: resumed ${result.expired} expired pause(s), re-queued ${result.requeued}, ` +\n `gave up on ${result.givenUp}.`,\n );\n },\n};\n\n/** The jobs contribution. */\nexport const MARKETPLACE_JOBS = {\n namespace: \"marketplace\",\n blueprints: {\n \"expire-acceptances\": expireAcceptances,\n \"reconcile-inbox\": reconcileInbox,\n outbound,\n \"fetch-order\": fetchOrder,\n catalogue,\n \"outbound-sweep\": outboundSweep,\n availability,\n \"availability-sweep\": availabilitySweep,\n },\n} as const satisfies JobsContribution<MarketplaceJobDeps>;\n","import type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceApiConfig } from \"./http\";\nimport { marketplaceRoutes, type MarketplaceRoute } from \"./routes\";\n\n/**\n * `@12-apps/marketplace/server` — the engine's HTTP surface, jobs, MCP tools\n * and permissions, as wiring-contract values.\n *\n * ```ts\n * const engine = createMarketplaceEngine({ …ports, adapters });\n * const api = createApiMarketplace({ engine, copy, tenantBySlug, logger });\n * // api.routes: mount under `/api` (the hono adapter does it in one line)\n * ```\n */\n\n/** What `createApiMarketplace` hands back: the routes, and the engine they serve. */\nexport interface ApiMarketplace {\n routes: MarketplaceRoute[];\n engine: MarketplaceEngine;\n}\n\n/** Build the route table over a mounted engine. */\nexport function createApiMarketplace(config: MarketplaceApiConfig): ApiMarketplace {\n if (!config.logger) {\n throw new Error(\"@12-apps/marketplace: the observability namespace needs a logger; pass `logger`.\");\n }\n return { routes: marketplaceRoutes(config), engine: config.engine };\n}\n\nexport type { MarketplaceActor, MarketplaceApiConfig } from \"./http\";\nexport type { MarketplaceRoute } from \"./routes\";\nexport type { MarketplaceServerCopy } from \"./copy\";\nexport {\n MARKETPLACE_DECIDE,\n MARKETPLACE_MANAGE,\n MARKETPLACE_PERMISSIONS,\n} from \"./contribution\";\nexport {\n MARKETPLACE_AVAILABILITY_ATTEMPTS,\n MARKETPLACE_FETCH_ORDER_ATTEMPTS,\n MARKETPLACE_JOBS,\n MARKETPLACE_OUTBOUND_ATTEMPTS,\n MARKETPLACE_SWEEP_QUEUE,\n type MarketplaceJobDeps,\n} from \"./jobs\";\nexport {\n MARKETPLACE_MCP_TOOLS,\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n marketplaceParams,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nexport { ORDER_NOT_PENDING_CODE } from \"./routes\";\nexport type { MarketplaceProblemCode } from \"./copy\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqCO,SAAS,GAAG,MAA6B;AAC9C,SAAO,EAAE,QAAQ,KAAK,MAAM,EAAE,KAAK,EAAE;AACvC;AAFgB;AAKT,SAAS,OAAO,QAAgB,OAAe,QAAiC,CAAC,GAAiB;AACvG,SAAO,EAAE,QAAQ,MAAM,EAAE,OAAO,GAAG,MAAM,EAAE;AAC7C;AAFgB;AAKT,SAAS,MACd,QACA,OACA,MACgE;AAChE,QAAM,SAAS,OAAO,UAAU,SAAS,CAAC,CAAC;AAC3C,MAAI,OAAO,QAAS,QAAO,EAAE,IAAI,MAAM,OAAO,OAAO,KAAK;AAC1D,QAAM,WAAW,OAAO,MAAM,OAAO,IAAI,CAAC,WAAW;AAAA,IACnD,MAAM,MAAM,KAAK,IAAI,CAAC,YAAa,OAAO,YAAY,WAAW,UAAU,OAAO,OAAO,CAAE;AAAA,IAC3F,MAAM;AAAA,IACN,SAAS,MAAM;AAAA,EACjB,EAAE;AACF,SAAO,EAAE,IAAI,OAAO,UAAU,OAAO,KAAK,KAAK,cAAc,EAAE,SAAS,CAAC,EAAE;AAC7E;AAbgB;AAgBT,SAAS,IAAI,OAA+C;AACjE,SAAO,QAAQ,MAAM,YAAY,IAAI;AACvC;AAFgB;;;ACvChB,IAAM,eAA6B,EAAE,QAAQ,KAAK,MAAM,EAAE,OAAO,eAAe,EAAE;AAOlF,eAAe,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IACF,SAAS,OAAO;AACd,UAAI,iBAAiB,uBAAwB,SAAQ,OAAO,KAAK,6BAA6B,MAAM,OAAO,EAAE;AAC7G,YAAM;AAAA,IACR;AAAA,EACF,GAbQ;AAcV;AAEA,IAAM,oBAAgE;AAAA,EACpE,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AAAA,EACb,UAAU,EAAE,SAAS,eAAe,UAAU,MAAM;AAAA,EACpD,UAAU;AAAA,EACV,OAAO,EAAE,OAAO,eAAe;AAAA,EAC/B,QAAQ,8BAAO,UAAU,MAAM,YAAY;AACzC,UAAM,SAAS,MAAM,KAAK,OAAO,kBAAkB;AACnD,QAAI,OAAO,UAAU,OAAO,WAAW,OAAO,YAAY,EAAG;AAC7D,YAAQ,OAAO;AAAA,MACb,2CAA2C,OAAO,OAAO,gCAAgC,OAAO,QAAQ,gBACxF,OAAO,OAAO;AAAA,IAChC;AAAA,EACF,GAPQ;AAQV;AAGO,IAAM,mBAAmB;AAAA,EAC9B,WAAW;AAAA,EACX,YAAY;AAAA,IACV,sBAAsB;AAAA,IACtB,mBAAmB;AAAA,IACnB;AAAA,IACA,eAAe;AAAA,IACf;AAAA,IACA,kBAAkB;AAAA,IAClB;AAAA,IACA,sBAAsB;AAAA,EACxB;AACF;;;ACxOO,SAAS,qBAAqB,QAA8C;AACjF,MAAI,CAAC,OAAO,QAAQ;AAClB,UAAM,IAAI,MAAM,kFAAkF;AAAA,EACpG;AACA,SAAO,EAAE,QAAQ,kBAAkB,MAAM,GAAG,QAAQ,OAAO,OAAO;AACpE;AALgB;","names":[]}
@@ -0,0 +1,15 @@
1
+ import {
2
+ __name
3
+ } from "./chunk-7QVYU63E.js";
4
+
5
+ // src/core/catalogue-read-port.ts
6
+ function centsFromMajor(value) {
7
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return null;
8
+ return Math.round(Number((value * 100).toPrecision(12)));
9
+ }
10
+ __name(centsFromMajor, "centsFromMajor");
11
+
12
+ export {
13
+ centsFromMajor
14
+ };
15
+ //# sourceMappingURL=chunk-WN2EK4KX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/catalogue-read-port.ts"],"sourcesContent":["import type { AdapterCallContext } from \"./adapter\";\n\n/**\n * The catalogue READ half of the adapter port (FUT-951): the menu a store\n * already keeps on a marketplace, read through the store's own connection, so\n * the host can import it (onboarding: \"bring my menu over\").\n *\n * The opposite direction of `catalogue-port.ts` and independent of it: an\n * adapter may read a menu it cannot publish to, or publish to one it cannot\n * read. Nothing here names a marketplace; each adapter maps its own catalogue\n * into the {@link CatalogueSnapshot} below.\n *\n * Money is integer cents of the menu's currency ({@link centsFromMajor}).\n * Nothing the adapter cannot map is dropped silently: a field it could not read\n * is a {@link CatalogueReadWarning} on the item, and an item or category it\n * could not read at all is a {@link CatalogueReadNotice} on the snapshot.\n */\n\n/** Why part of an item could not be mapped. Vocabulary, not copy: the host words it. */\nexport type CatalogueReadWarningCode =\n /** The item carries no readable price: `priceCents` is null. */\n | \"PRICE_MISSING\"\n /** An option carries no readable price: its `priceDeltaCents` is null. */\n | \"OPTION_PRICE_MISSING\"\n /** A group of choices could not be read (no name, no options, bounds that make no sense): left out. */\n | \"OPTION_GROUP_UNREADABLE\"\n /** One choice of a group could not be read (no name): left out of its group. */\n | \"OPTION_UNREADABLE\"\n /** The photo reference is there but is not a path or URL the adapter can resolve: `photoUrl` is null. */\n | \"PHOTO_UNREADABLE\"\n /** The item is of a kind this reader maps only partly (a combo, a pizza by halves): read as a plain item. */\n | \"ITEM_TYPE_UNSUPPORTED\";\n\n/** One thing about an item the read could not map. */\nexport interface CatalogueReadWarning {\n code: CatalogueReadWarningCode;\n /** The marketplace's id of the group or option concerned, or null when it is the item itself. */\n subject: string | null;\n /** What the marketplace sent, for a developer (never shown as copy). */\n detail: string | null;\n}\n\n/** One choice of a group: a size, a flavour, an add-on. */\nexport interface CatalogueSnapshotOption {\n externalId: string;\n /** The store's own code for it on the marketplace, when it set one. */\n externalCode: string | null;\n name: string;\n description: string | null;\n /** What choosing it adds to the item's price, in cents (0 = free); null when the marketplace sent none. */\n priceDeltaCents: number | null;\n photoUrl: string | null;\n available: boolean;\n}\n\n/** A group of choices on an item: \"Size\" (min 1, max 1), \"Extras\" (min 0, max 3). */\nexport interface CatalogueSnapshotOptionGroup {\n externalId: string;\n externalCode: string | null;\n name: string;\n /** At least this many choices (0 = optional). */\n min: number;\n /** At most this many choices (always >= `min` and >= 1). */\n max: number;\n available: boolean;\n options: CatalogueSnapshotOption[];\n}\n\n/** One item as the marketplace sells it. */\nexport interface CatalogueSnapshotItem {\n externalId: string;\n externalCode: string | null;\n name: string;\n description: string | null;\n /** The item's own price in cents; null when the marketplace sent none (with a PRICE_MISSING warning). */\n priceCents: number | null;\n /** An absolute https URL of the photo, or null when the item has none. */\n photoUrl: string | null;\n /** Whether the marketplace sells it now (a paused item is still read). */\n available: boolean;\n optionGroups: CatalogueSnapshotOptionGroup[];\n warnings: CatalogueReadWarning[];\n}\n\n/** One category, its items in the marketplace's order. */\nexport interface CatalogueSnapshotCategory {\n externalId: string;\n externalCode: string | null;\n name: string;\n available: boolean;\n items: CatalogueSnapshotItem[];\n}\n\n/** An item or a category the read could not map at all, said rather than dropped. */\nexport interface CatalogueReadNotice {\n code: \"ITEM_UNREADABLE\" | \"CATEGORY_UNREADABLE\";\n /** The category it was found in (the category itself for CATEGORY_UNREADABLE), or null when it had no id. */\n categoryExternalId: string | null;\n /** The item's id, when it had one; null for a category. */\n externalId: string | null;\n detail: string;\n}\n\n/** The store's menu on a marketplace, as read. */\nexport interface CatalogueSnapshot {\n categories: CatalogueSnapshotCategory[];\n notices: CatalogueReadNotice[];\n}\n\n/**\n * Why a read failed for good. Vocabulary, not copy.\n * - `UNSUPPORTED`: the marketplace's adapter states no catalogue read.\n * - `NOT_CONNECTED`: no live connection with a merchant id for that marketplace.\n * - `CREDENTIALS`: no credentials on file, they do not open, or the marketplace refused them.\n * - `NOT_AUTHORIZED`: the marketplace refused this merchant to this app (not\n * authorized, the catalogue module not enabled, an unknown merchant id).\n * - `REFUSED`: any other final refusal.\n */\nexport type CatalogueReadRefusalCode = \"UNSUPPORTED\" | \"NOT_CONNECTED\" | \"CREDENTIALS\" | \"NOT_AUTHORIZED\" | \"REFUSED\";\n\n/** What a read answers: the snapshot, a final refusal, or a failure worth asking again later (429, 5xx, a timeout). */\nexport type CatalogueReadResult =\n | { kind: \"snapshot\"; snapshot: CatalogueSnapshot }\n /** `status` and `message` are the marketplace's answer; null when the engine refused before calling. */\n | { kind: \"refused\"; code: CatalogueReadRefusalCode; status: number | null; message: string | null }\n | { kind: \"retry\"; reason: string };\n\n/** What one catalogue read is handed: the outbound context plus the connection's merchant id. */\nexport interface CatalogueReadContext extends AdapterCallContext {\n externalMerchantId: string;\n}\n\n/** A marketplace whose menu can be read. */\nexport interface CatalogueReader {\n /** Read the whole menu. Never throws: a call with no answer is a `retry`. */\n read(ctx: CatalogueReadContext): Promise<CatalogueReadResult>;\n}\n\n/**\n * A price in the currency's MAJOR unit (`25.9`) as integer cents (`2590`), or\n * null when it is not a finite, non-negative number.\n *\n * Rounding is explicit: the product is first cut to 12 significant digits,\n * which removes binary floating-point error (`1.005 * 100` is\n * `100.49999999999999`), and then rounded half up to the cent (`1.005` →\n * `101`, `0.125` → `13`).\n */\nexport function centsFromMajor(value: unknown): number | null {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) return null;\n return Math.round(Number((value * 100).toPrecision(12)));\n}\n"],"mappings":";;;;;AAmJO,SAAS,eAAe,OAA+B;AAC5D,MAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,EAAG,QAAO;AAC9E,SAAO,KAAK,MAAM,QAAQ,QAAQ,KAAK,YAAY,EAAE,CAAC,CAAC;AACzD;AAHgB;","names":[]}
@@ -1,4 +1,4 @@
1
- import { m as CatalogueItem, l as CatalogueImage, a as NormalizedMarketplaceOrder, v as MarketplaceHttp, M as MarketplaceAdapter, e as MarketplaceProvider, t as MarketplaceCredentials, q as CatalogueWarningCode, f as CancellationReason, O as OutboundOrderRef, N as NormalizedEvent, b as CatalogueMenuOptions } from './adapter-0l_EmuJA.js';
1
+ import { q as CatalogueItem, p as CatalogueImage, a as NormalizedMarketplaceOrder, R as MarketplaceHttp, c as MarketplaceAdapter, i as MarketplaceProvider, L as MarketplaceCredentials, H as CatalogueWarningCode, j as CancellationReason, Z as OutboundOrderRef, N as NormalizedEvent, b as CatalogueMenuOptions, w as CatalogueReadResult } from './adapter-CCWMqt2g.js';
2
2
 
3
3
  /**
4
4
  * What the engine needs FROM its host, and nothing more.
@@ -76,6 +76,19 @@ interface MarketplaceDb {
76
76
  count: number;
77
77
  }>;
78
78
  };
79
+ /**
80
+ * OPTIONAL in the type, so a host on 1.x that has not yet composed the
81
+ * pause model still compiles; `pauseStore` refuses without it (FUT-4851,
82
+ * migration `20261113230000_marketplace_store_pause`).
83
+ */
84
+ marketplaceStorePause?: {
85
+ findFirst(args: unknown): Promise<unknown>;
86
+ findMany(args: unknown): Promise<unknown[]>;
87
+ upsert(args: unknown): Promise<unknown>;
88
+ updateMany(args: unknown): Promise<{
89
+ count: number;
90
+ }>;
91
+ };
79
92
  }
80
93
  /**
81
94
  * One order line after the engine has matched it against the SKU map.
@@ -929,6 +942,210 @@ interface OutboundAttempt {
929
942
  maxAttempts: number;
930
943
  }
931
944
 
945
+ /**
946
+ * The pause record: one row per (store, marketplace), the engine's memory of
947
+ * what it asked the marketplace and what the marketplace holds (FUT-4851).
948
+ *
949
+ * Two fields say two different things, and the job reconciles them:
950
+ *
951
+ * - `wanted` is the host's LAST ask (PAUSED or OPEN). The last ask wins: a
952
+ * resume that lands while a pause is in flight, or a pause while a resume
953
+ * is, only rewrites `wanted`, and the job re-reads it after every call.
954
+ * - `state` is where the marketplace stands as far as the engine knows:
955
+ * OPEN → PAUSING → PAUSED → RESUMING → OPEN, or FAILED with a code.
956
+ *
957
+ * What the engine holds on the marketplace is `externalId` (the closure's id,
958
+ * for an `interruption`), `sentUntil` (the end the marketplace was given; the
959
+ * only proof of a `switch` the engine turned off) and `attemptKey` with
960
+ * `attemptUntil` (the key a create goes out under, written BEFORE the call,
961
+ * and the end it carried, kept while its answer is in doubt).
962
+ * `retiredExternalIds` are the closures a renewal replaced, still to be
963
+ * deleted. Nothing else is ever deleted: a closure the owner made by hand is
964
+ * in none of them.
965
+ */
966
+ /** Where the marketplace stands, as far as the engine knows. Vocabulary, not copy. */
967
+ type StorePauseState = "OPEN" | "PAUSING" | "PAUSED" | "RESUMING" | "FAILED";
968
+ /** The host's last ask. */
969
+ type StorePauseWanted = "PAUSED" | "OPEN";
970
+ /**
971
+ * Why a record is FAILED. Machine codes, never a sentence: the host renders
972
+ * them, and the marketplace's own words travel in `failureDetail`.
973
+ *
974
+ * - `UNSUPPORTED`: the marketplace's adapter has no availability capability.
975
+ * - `NOT_CONNECTED`: no credentials or no merchant id on the connection.
976
+ * - `PAUSE_REFUSED` / `RESUME_REFUSED`: the marketplace said no (a final 4xx).
977
+ * - `PAUSE_UNANSWERED` / `RESUME_UNANSWERED`: every attempt failed without an
978
+ * answer (5xx, a timeout, a rate limit), or the sweep gave up waiting.
979
+ */
980
+ type StorePauseFailureCode = "UNSUPPORTED" | "NOT_CONNECTED" | "PAUSE_REFUSED" | "PAUSE_UNANSWERED" | "RESUME_REFUSED" | "RESUME_UNANSWERED";
981
+ /** One record as the engine reads it. */
982
+ interface StorePauseRow {
983
+ id: string;
984
+ clientId: string;
985
+ provider: string;
986
+ state: StorePauseState;
987
+ wanted: StorePauseWanted;
988
+ until: Date | null;
989
+ reason: string | null;
990
+ timeZone: string | null;
991
+ externalId: string | null;
992
+ sentUntil: Date | null;
993
+ attemptKey: string | null;
994
+ attemptUntil: Date | null;
995
+ /** The replaced closures still to delete, oldest first (`./pause-retired.ts` reads and writes it); null when none. */
996
+ retiredExternalIds: string | null;
997
+ failureCode: StorePauseFailureCode | null;
998
+ failureDetail: string | null;
999
+ requestedAt: Date;
1000
+ leaseUntil: Date | null;
1001
+ pausedAt: Date | null;
1002
+ resumedAt: Date | null;
1003
+ failedAt: Date | null;
1004
+ updatedAt: Date | null;
1005
+ }
1006
+ /** The job's wire name. */
1007
+ declare const MARKETPLACE_AVAILABILITY_JOB = "marketplace.availability";
1008
+ /** The job's payload: identifiers only; the ask lives on the row. */
1009
+ interface AvailabilityJobPayload {
1010
+ clientId: string;
1011
+ provider: MarketplaceProvider;
1012
+ }
1013
+ /** How long one run holds a record, so two runs never call the marketplace for it at once. */
1014
+ declare const STORE_PAUSE_LEASE_MS: number;
1015
+ /** The dedupe key of one ask: per record and per ask instant, so a new ask is never swallowed. */
1016
+ declare function availabilityDedupeKey(payload: AvailabilityJobPayload, requestedAt: Date, suffix?: string): string;
1017
+
1018
+ /**
1019
+ * The store pause, as the host calls it (FUT-4851): `pauseStore` when the
1020
+ * kitchen pauses and on every renewal, `resumeStore` the moment the pause is
1021
+ * over, `availabilityState` for the screen. The host owns the debounce; these
1022
+ * calls only record the ask and queue `marketplace.availability`, whose job
1023
+ * makes the calls (`./pause-job.ts`). No path that answers a request reaches
1024
+ * a marketplace.
1025
+ */
1026
+ /** What `pauseStore` did on one marketplace. */
1027
+ type PauseOutcome =
1028
+ /** The ask was recorded and the job queued. */
1029
+ "queued"
1030
+ /** A pause with exactly this end already stands or is on its way. */
1031
+ | "unchanged"
1032
+ /** The marketplace's adapter cannot pause a store: the host says so. */
1033
+ | "unsupported"
1034
+ /** The connection has no credentials or no merchant id. */
1035
+ | "not-connected";
1036
+ /** What `resumeStore` did on one marketplace. */
1037
+ type ResumeOutcome =
1038
+ /** Something of ours stands on the marketplace: the job deletes it. */
1039
+ "queued"
1040
+ /** Nothing of ours stands there: the record is OPEN, and nobody is called. */
1041
+ | "open"
1042
+ /** A resume is already on its way. */
1043
+ | "unchanged";
1044
+ interface PauseStoreInput {
1045
+ clientId: string;
1046
+ /** The kitchen's estimated reopening time: the end every marketplace is given. */
1047
+ until: Date;
1048
+ /** The host's words for the closure (its copy, in the store's language). */
1049
+ reason: string;
1050
+ /** The store's IANA time zone. */
1051
+ timeZone: string;
1052
+ now?: Date;
1053
+ }
1054
+ type PauseStoreResult = {
1055
+ kind: "invalid";
1056
+ code: "UNTIL_NOT_FUTURE" | "TIME_ZONE_INVALID";
1057
+ } | {
1058
+ kind: "ok";
1059
+ marketplaces: {
1060
+ provider: MarketplaceProvider;
1061
+ outcome: PauseOutcome;
1062
+ }[];
1063
+ };
1064
+ /** One marketplace's pause as the screen shows it. */
1065
+ interface StoreAvailabilityView {
1066
+ provider: MarketplaceProvider;
1067
+ /** The adapter can pause a store at all. */
1068
+ supported: boolean;
1069
+ /** `interruption` (an id and an end) or `switch` (on/off); null when unsupported. */
1070
+ kind: "interruption" | "switch" | null;
1071
+ /** The connection has credentials and a merchant id. */
1072
+ connected: boolean;
1073
+ state: StorePauseState;
1074
+ wanted: StorePauseWanted;
1075
+ /** The end the host asked for. */
1076
+ until: Date | null;
1077
+ /** The end the marketplace was given and confirmed. */
1078
+ sentUntil: Date | null;
1079
+ failureCode: StorePauseFailureCode | null;
1080
+ /** The marketplace's own words, verbatim and cut; never copy to show as is. */
1081
+ failureDetail: string | null;
1082
+ pausedAt: Date | null;
1083
+ resumedAt: Date | null;
1084
+ updatedAt: Date | null;
1085
+ }
1086
+
1087
+ /**
1088
+ * The `marketplace.availability` job: bring one marketplace in line with the
1089
+ * host's last ask for one store (FUT-4851).
1090
+ *
1091
+ * The job re-reads the record before every call and after it, so the last ask
1092
+ * wins: a resume that lands while a pause call is in flight finds the closure
1093
+ * that call created recorded, and deletes it on the next step. A run holds a
1094
+ * short lease on the record, so two runs never call one marketplace for one
1095
+ * store at once. The answer rule is the outbound engine's: 2xx done, a final
1096
+ * 4xx FAILED with the marketplace's words, anything else retried by the queue
1097
+ * until the last attempt, which stamps `*_UNANSWERED`.
1098
+ */
1099
+ /** What one run did. */
1100
+ type AvailabilityOutcome = {
1101
+ kind: "skipped";
1102
+ reason: string;
1103
+ } | {
1104
+ kind: "done";
1105
+ state: StorePauseRow["state"];
1106
+ } | {
1107
+ kind: "failed";
1108
+ code: StorePauseFailureCode;
1109
+ };
1110
+ /** Thrown so the queue retries. Its message is what the job log reads. */
1111
+ declare class AvailabilityRetryError extends Error {
1112
+ constructor(message: string);
1113
+ }
1114
+
1115
+ /**
1116
+ * The availability sweep (`marketplace.availability-sweep`, every five
1117
+ * minutes): nothing the engine owes a marketplace for a store's pause is lost,
1118
+ * and no store stays closed past the kitchen's pause (FUT-4851).
1119
+ *
1120
+ * - **Expired**: a pause whose `until` has passed without a renewal is over.
1121
+ * The host stopped renewing (it died, or forgot to resume), so the engine
1122
+ * resumes on its own: the owner's "never closed on a marketplace longer than
1123
+ * the kitchen's own pause". An interruption has already ended on the
1124
+ * marketplace (its delete answers "gone", which is done); a switch would
1125
+ * otherwise stay off for good.
1126
+ * - **Stale**: an ask still PAUSING or RESUMING after the job's own retry span
1127
+ * (a refused enqueue, a dead process) is re-queued; past
1128
+ * {@link OUTBOUND_GIVE_UP_MS} it is FAILED as unanswered.
1129
+ * - **A failed resume that still holds something** is retried each pass until
1130
+ * the give-up: a store must not stay closed because one delete failed.
1131
+ * - **A replaced closure** an extend could not delete is retried.
1132
+ * - **An OPEN record that still holds something** (a pause call whose answer
1133
+ * was lost after a resume landed) goes back to RESUMING and is re-queued.
1134
+ *
1135
+ * Re-queued under a key of its own per pass, as the outbound sweep does. The
1136
+ * job is idempotent by the row and leased, so a duplicate run calls nobody
1137
+ * twice.
1138
+ */
1139
+ /** What one pass did. */
1140
+ interface AvailabilitySweepResult {
1141
+ /** Pauses past their `until`, turned into resumes. */
1142
+ expired: number;
1143
+ /** Asks re-queued. */
1144
+ requeued: number;
1145
+ /** Asks failed as unanswered past the give-up. */
1146
+ givenUp: number;
1147
+ }
1148
+
932
1149
  /** How a delivery ended. `duplicate` and `ignored` are both ordinary outcomes. */
933
1150
  type DeliveryOutcome = {
934
1151
  kind: "ingested";
@@ -1110,8 +1327,41 @@ interface MarketplaceEngine {
1110
1327
  provider: MarketplaceProvider;
1111
1328
  options: CatalogueMenuOptions;
1112
1329
  }): Promise<CatalogueDocumentResult>;
1330
+ /**
1331
+ * Read the menu the store keeps on a marketplace, through its own
1332
+ * connection (FUT-951): the snapshot, a final refusal, or a `retry` (429,
1333
+ * 5xx, a timeout). Calls the marketplace at once; nothing is queued.
1334
+ */
1335
+ readCatalogue(input: {
1336
+ clientId: string;
1337
+ provider: MarketplaceProvider;
1338
+ now?: Date;
1339
+ }): Promise<CatalogueReadResult>;
1113
1340
  /** Run one queued publish or withdraw (the `marketplace.catalogue` job's body). */
1114
1341
  runCatalogue(payload: CatalogueJobPayload, attempt: OutboundAttempt): Promise<CatalogueOutcome>;
1342
+ /**
1343
+ * The kitchen paused (or renewed its pause): close the store until `until`
1344
+ * on every live connection whose marketplace can be paused (FUT-4851).
1345
+ * Idempotent: the `until` already standing does nothing; any other, an
1346
+ * earlier one included, renews the closure.
1347
+ */
1348
+ pauseStore(input: PauseStoreInput): Promise<PauseStoreResult>;
1349
+ /** The kitchen's pause is over: delete every closure the engine created, and nothing else. */
1350
+ resumeStore(input: {
1351
+ clientId: string;
1352
+ now?: Date;
1353
+ }): Promise<{
1354
+ marketplaces: {
1355
+ provider: MarketplaceProvider;
1356
+ outcome: ResumeOutcome;
1357
+ }[];
1358
+ }>;
1359
+ /** Where the store's pause stands on each marketplace, for the screen. */
1360
+ availabilityState(clientId: string): Promise<StoreAvailabilityView[]>;
1361
+ /** Bring one marketplace in line with the last ask (the `marketplace.availability` job's body). */
1362
+ runAvailability(payload: AvailabilityJobPayload, attempt: OutboundAttempt): Promise<AvailabilityOutcome>;
1363
+ /** Expire, re-queue and give up on store pauses (the `marketplace.availability-sweep` job's body). */
1364
+ sweepAvailability(now?: Date): Promise<AvailabilitySweepResult>;
1115
1365
  }
1116
1366
  /**
1117
1367
  * Mount the engine onto a host.
@@ -1123,4 +1373,4 @@ interface MarketplaceEngine {
1123
1373
  */
1124
1374
  declare function createMarketplaceEngine(config: MarketplaceEngineConfig): MarketplaceEngine;
1125
1375
 
1126
- export { type MarketplaceOrderState as $, type AcceptanceDecision as A, type BulkProblem as B, type CancellationFailureReason as C, type DecideManyResult as D, type ExpirySweepResult as E, type FetchOrderJobPayload as F, type IngestionTarget as G, type IntegrationRowInput as H, type IngestResult as I, MARKETPLACE_FETCH_ORDER_JOB as J, MARKETPLACE_OUTBOUND_JOB as K, type MarketplaceAdmission as L, MARKETPLACE_CATALOGUE_JOB as M, type MarketplaceAdmissionRequest as N, type MarketplaceAdmissionResult as O, type MarketplaceAuditEntry as P, type MarketplaceAuditPort as Q, type MarketplaceCataloguePort as R, type MarketplaceClockPort as S, type MarketplaceDb as T, type MarketplaceEngine as U, type MarketplaceEngineConfig as V, type MarketplaceEnqueuePort as W, type MarketplaceIntegrationView as X, type MarketplaceLogger as Y, type MarketplaceMenuLinkView as Z, type MarketplaceOrderPort as _, type AcceptanceStatus as a, type MarketplaceOrderSummary as a0, type MarketplacePorts as a1, type MarketplaceRefusal as a2, type MarketplaceSecretsPort as a3, type MenuLinkRowInput as a4, OUTBOUND_GIVE_UP_MS as a5, OUTBOUND_STALE_MS as a6, type OutboundAction as a7, type OutboundAttempt as a8, type OutboundJobPayload as a9, type OutboundOutcome as aa, OutboundRetryError as ab, type OutboundSweepResult as ac, type PendingAcceptance as ad, type PendingInboxEvent as ae, type ResolvedOrderLine as af, type SaveMarketplaceIntegrationInput as ag, catalogueDedupeKey as ah, createMarketplaceEngine as ai, outboundDedupeKey as aj, type BulkProblemCode as b, type BulkResult as c, type CancellationStatus as d, type CatalogueAction as e, type CatalogueActionResult as f, type CatalogueDocumentResult as g, type CatalogueFailedAction as h, type CatalogueFailureCode as i, type CatalogueJobPayload as j, type CatalogueOutcome as k, type CataloguePublicationView as l, type CataloguePublishInput as m, type CatalogueRefusalCode as n, CatalogueRetryError as o, type CatalogueStatus as p, type CatalogueTarget as q, type DecidedRow as r, type DecisionInput as s, type DecisionProblem as t, type DecisionProblemCode as u, type DecisionResult as v, type DeliveryOutcome as w, type FetchOrderOutcome as x, FetchOrderRetryError as y, type IngestSettings as z };
1376
+ export { type MarketplaceEnqueuePort as $, type AcceptanceDecision as A, type BulkProblem as B, type CancellationFailureReason as C, type DecideManyResult as D, type DeliveryOutcome as E, type ExpirySweepResult as F, type FetchOrderJobPayload as G, type FetchOrderOutcome as H, FetchOrderRetryError as I, type IngestResult as J, type IngestSettings as K, type IngestionTarget as L, type IntegrationRowInput as M, MARKETPLACE_AVAILABILITY_JOB as N, MARKETPLACE_CATALOGUE_JOB as O, MARKETPLACE_FETCH_ORDER_JOB as P, MARKETPLACE_OUTBOUND_JOB as Q, type MarketplaceAdmission as R, type MarketplaceAdmissionRequest as S, type MarketplaceAdmissionResult as T, type MarketplaceAuditEntry as U, type MarketplaceAuditPort as V, type MarketplaceCataloguePort as W, type MarketplaceClockPort as X, type MarketplaceDb as Y, type MarketplaceEngine as Z, type MarketplaceEngineConfig as _, type AcceptanceStatus as a, type MarketplaceIntegrationView as a0, type MarketplaceLogger as a1, type MarketplaceMenuLinkView as a2, type MarketplaceOrderPort as a3, type MarketplaceOrderState as a4, type MarketplaceOrderSummary as a5, type MarketplacePorts as a6, type MarketplaceRefusal as a7, type MarketplaceSecretsPort as a8, type MenuLinkRowInput as a9, OUTBOUND_GIVE_UP_MS as aa, OUTBOUND_STALE_MS as ab, type OutboundAction as ac, type OutboundAttempt as ad, type OutboundJobPayload as ae, type OutboundOutcome as af, OutboundRetryError as ag, type OutboundSweepResult as ah, type PauseOutcome as ai, type PauseStoreInput as aj, type PauseStoreResult as ak, type PendingAcceptance as al, type PendingInboxEvent as am, type ResolvedOrderLine as an, type ResumeOutcome as ao, STORE_PAUSE_LEASE_MS as ap, type SaveMarketplaceIntegrationInput as aq, type StoreAvailabilityView as ar, type StorePauseFailureCode as as, type StorePauseState as at, type StorePauseWanted as au, availabilityDedupeKey as av, catalogueDedupeKey as aw, createMarketplaceEngine as ax, outboundDedupeKey as ay, type AvailabilityJobPayload as b, type AvailabilityOutcome as c, AvailabilityRetryError as d, type AvailabilitySweepResult as e, type BulkProblemCode as f, type BulkResult as g, type CancellationStatus as h, type CatalogueAction as i, type CatalogueActionResult as j, type CatalogueDocumentResult as k, type CatalogueFailedAction as l, type CatalogueFailureCode as m, type CatalogueJobPayload as n, type CatalogueOutcome as o, type CataloguePublicationView as p, type CataloguePublishInput as q, type CatalogueRefusalCode as r, CatalogueRetryError as s, type CatalogueStatus as t, type CatalogueTarget as u, type DecidedRow as v, type DecisionInput as w, type DecisionProblem as x, type DecisionProblemCode as y, type DecisionResult as z };
@@ -1,7 +1,7 @@
1
1
  import { Hono, Context } from 'hono';
2
2
  import { ApiMarketplace, MarketplaceApiConfig, MarketplaceActor } from '../server/index.js';
3
- import '../engine-CZsP8KWd.js';
4
- import '../adapter-0l_EmuJA.js';
3
+ import '../engine-C3uq_BJd.js';
4
+ import '../adapter-CCWMqt2g.js';
5
5
  import '@12-apps/wiring';
6
6
  import 'zod';
7
7
 
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  createApiMarketplace
3
- } from "../chunk-AYYBRQJV.js";
3
+ } from "../chunk-UONWZIBO.js";
4
4
  import "../chunk-UYFYGGCS.js";
5
- import "../chunk-XUAFXNOH.js";
5
+ import "../chunk-FKUEFVVA.js";
6
6
  import {
7
7
  __name
8
8
  } from "../chunk-7QVYU63E.js";
@@ -1,4 +1,4 @@
1
- import { N as NormalizedEvent, c as PushCatalogue, d as CatalogueItemOut, M as MarketplaceAdapter } from '../adapter-0l_EmuJA.js';
1
+ import { N as NormalizedEvent, d as PushCatalogue, e as CatalogueItemOut, f as CatalogueReader, M as MarketplaceAvailability, A as AdapterCallContext, S as StorePauseRequest, g as StorePauseResult, h as StorePauseRef, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CCWMqt2g.js';
2
2
 
3
3
  /**
4
4
  * The words the iFood adapter needs from its host, and nothing else.
@@ -50,6 +50,48 @@ declare function ifoodItemBody(item: CatalogueItemOut, category: string, image:
50
50
  /** iFood's catalogue capability. */
51
51
  declare const IFOOD_CATALOGUE: PushCatalogue;
52
52
 
53
+ /** iFood's catalogue read. */
54
+ declare const IFOOD_CATALOGUE_READER: CatalogueReader;
55
+
56
+ /**
57
+ * iFood's catalogue answer mapped into the engine's {@link CatalogueSnapshotItem}
58
+ * (FUT-951). Pure and offline: `./catalogue-read.ts` makes the calls.
59
+ *
60
+ * The shapes are the Catalog API v2.0's `PUT /items` payload, which the
61
+ * portal's Introduction shows whole (read 2026-11-16): an `item` (id, type,
62
+ * categoryId, status, `price { value }`, externalCode), `products` (id, name,
63
+ * description, externalCode, and `optionGroups: [{ id, min, max }]` linking a
64
+ * product to its groups), `optionGroups` (id, name, status, `optionIds`) and
65
+ * `options` (id, `productId` naming the product that holds its name, status,
66
+ * `price { value }`). The package README's "Catalogue reading" table marks
67
+ * each fact CONFIRMED with its URL or ESTIMATED. ESTIMATED here, and said
68
+ * beside each use:
69
+ * - that `GET /categories/{categoryId}/items` answers the same four lists
70
+ * (`items` plural) the PUT takes;
71
+ * - that `item.productId` names the item's product (the field the push sends);
72
+ * - that `products[].imagePath` holds the photo, a path under
73
+ * {@link IFOOD_IMAGE_BASE_URL}.
74
+ */
75
+ /**
76
+ * Where iFood serves a catalogue photo's `imagePath`. ESTIMATED: the Catalog
77
+ * pages read name `imagePath` but not its host; this is the host iFood's own
78
+ * app loads dish photos from. A path that is already an absolute https URL is
79
+ * used as it is.
80
+ */
81
+ declare const IFOOD_IMAGE_BASE_URL = "https://static-images.ifood.com.br/image/upload/t_high/pratos/";
82
+
83
+ /**
84
+ * `date` as the store's wall clock with its offset: `2026-11-13T15:30:00-03:00`.
85
+ * Read the same whether iFood honours the offset or reads the store's clock.
86
+ */
87
+ declare function ifoodLocalTime(date: Date, timeZone: string): string;
88
+ /** Close the store until `request.until`: find one a lost answer created under the key, else create it. */
89
+ declare function ifoodPause(ctx: AdapterCallContext, request: StorePauseRequest): Promise<StorePauseResult>;
90
+ /** Delete THIS interruption: by its id, or the one a lost answer created under the key (by id, or by its end and description). */
91
+ declare function ifoodResume(ctx: AdapterCallContext, ref: StorePauseRef): Promise<OutboundResult>;
92
+ /** iFood's availability capability: interruptions, no extend. */
93
+ declare const IFOOD_AVAILABILITY: MarketplaceAvailability;
94
+
53
95
  /**
54
96
  * `@12-apps/marketplace/ifood` — iFood, as one adapter on the engine.
55
97
  *
@@ -76,4 +118,4 @@ interface IfoodAdapterConfig {
76
118
  /** Build the iFood adapter. Its reasons are static: a dialog never waits on iFood. */
77
119
  declare function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapter;
78
120
 
79
- export { IFOOD_CANCELLATION_ANSWER_WINDOW_MS, IFOOD_CATALOGUE, IFOOD_PROVIDER, IFOOD_REASON_CODES, type IfoodAdapterConfig, type IfoodAdapterCopy, type IfoodReasonCode, createIfoodAdapter, ifoodItemBody, ifoodItemId, ifoodProductId, normalizeIfoodEvent, verifyIfoodSignature };
121
+ export { IFOOD_AVAILABILITY, IFOOD_CANCELLATION_ANSWER_WINDOW_MS, IFOOD_CATALOGUE, IFOOD_CATALOGUE_READER, IFOOD_IMAGE_BASE_URL, IFOOD_PROVIDER, IFOOD_REASON_CODES, type IfoodAdapterConfig, type IfoodAdapterCopy, type IfoodReasonCode, createIfoodAdapter, ifoodItemBody, ifoodItemId, ifoodLocalTime, ifoodPause, ifoodProductId, ifoodResume, normalizeIfoodEvent, verifyIfoodSignature };