@12-apps/marketplace 1.6.0 → 1.8.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 (74) hide show
  1. package/ADOPTING.md +17 -0
  2. package/README.md +56 -0
  3. package/dist/99food/index.d.ts +4 -2
  4. package/dist/99food/index.js +38 -6
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-CCWMqt2g.d.ts → adapter-CYJzu1c9.d.ts} +81 -2
  7. package/dist/{chunk-4CJ7B5OR.js → chunk-6N2HEV3U.js} +4 -4
  8. package/dist/chunk-6N2HEV3U.js.map +1 -0
  9. package/dist/{chunk-NFZT5TWR.js → chunk-BMCERPQX.js} +214 -24
  10. package/dist/chunk-BMCERPQX.js.map +1 -0
  11. package/dist/{chunk-RGMSD7S7.js → chunk-HEXLCTOG.js} +7 -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/{engine-w2TgRrlc.d.ts → engine-wmW-VuBL.d.ts} +123 -9
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +3 -3
  18. package/dist/ifood/index.d.ts +1 -1
  19. package/dist/ifood/index.js +66 -6
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +119 -12
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/index.d.ts +3 -0
  25. package/dist/manifest/index.js +1 -1
  26. package/dist/manifest/server.d.ts +2 -2
  27. package/dist/manifest/server.js +3 -3
  28. package/dist/rappi/index.d.ts +7 -1
  29. package/dist/rappi/index.js +23 -5
  30. package/dist/rappi/index.js.map +1 -1
  31. package/dist/server/index.d.ts +6 -2
  32. package/dist/server/index.js +3 -3
  33. package/package.json +1 -1
  34. package/prisma/marketplace.prisma +48 -4
  35. package/prisma/migrations/20261125180000_marketplace_cancellation_failure_reason_widen/migration.sql +16 -0
  36. package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
  37. package/src/99food/index.ts +6 -0
  38. package/src/99food/normalize.ts +7 -1
  39. package/src/99food/outbound.ts +62 -2
  40. package/src/core/adapter.ts +58 -3
  41. package/src/core/bulk.ts +1 -1
  42. package/src/core/cancellation.ts +4 -1
  43. package/src/core/catalogue.ts +4 -3
  44. package/src/core/decisions.ts +3 -2
  45. package/src/core/engine.ts +9 -0
  46. package/src/core/fetch-order.ts +2 -2
  47. package/src/core/ingest.ts +6 -0
  48. package/src/core/integration.ts +17 -0
  49. package/src/core/lifecycle-port.ts +16 -0
  50. package/src/core/lifecycle.ts +133 -0
  51. package/src/core/order-fetch-marks.ts +13 -8
  52. package/src/core/outbound-queue.ts +24 -4
  53. package/src/core/outbound-sweep.ts +49 -5
  54. package/src/core/outbound.ts +26 -11
  55. package/src/core/pipeline.ts +35 -3
  56. package/src/core/ports.ts +54 -7
  57. package/src/core/state.ts +1 -1
  58. package/src/core/status-inform.ts +51 -0
  59. package/src/core/status-job.ts +207 -0
  60. package/src/core/status-store.ts +85 -0
  61. package/src/core/types.ts +39 -0
  62. package/src/ifood/index.ts +7 -1
  63. package/src/ifood/normalize.ts +70 -0
  64. package/src/ifood/outbound.ts +37 -1
  65. package/src/index.ts +9 -0
  66. package/src/rappi/index.ts +6 -1
  67. package/src/rappi/normalize.ts +6 -0
  68. package/src/rappi/outbound.ts +33 -3
  69. package/src/server/mcp.ts +2 -0
  70. package/src/server/webhook.ts +3 -1
  71. package/dist/chunk-4CJ7B5OR.js.map +0 -1
  72. package/dist/chunk-NFZT5TWR.js.map +0 -1
  73. package/dist/chunk-RGMSD7S7.js.map +0 -1
  74. package/dist/chunk-UYFYGGCS.js.map +0 -1
@@ -7,13 +7,13 @@ import {
7
7
  listMarketplaceMenuLinksQuery,
8
8
  upsertMarketplaceIntegrationsBody,
9
9
  upsertMarketplaceMenuLinksBody
10
- } from "./chunk-UYFYGGCS.js";
10
+ } from "./chunk-NP4EYKPO.js";
11
11
  import {
12
12
  AvailabilityRetryError,
13
13
  CatalogueRetryError,
14
14
  FetchOrderRetryError,
15
15
  OutboundRetryError
16
- } from "./chunk-NFZT5TWR.js";
16
+ } from "./chunk-BMCERPQX.js";
17
17
  import {
18
18
  __name
19
19
  } from "./chunk-7QVYU63E.js";
@@ -99,7 +99,7 @@ async function handleWebhook(config, request) {
99
99
  payload,
100
100
  // A DISABLED connection still stores its deliveries and ingests nothing;
101
101
  // the retry sweep ingests them if the store turns it back on.
102
- settings: target.enabled ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds } : null
102
+ settings: target.enabled ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds, followStatus: target.followStatus } : null
103
103
  });
104
104
  if (outcome.kind === "failed") {
105
105
  return { status: 500, body: { received: true, error: outcome.reason } };
@@ -473,4 +473,4 @@ export {
473
473
  MARKETPLACE_JOBS,
474
474
  createApiMarketplace
475
475
  };
476
- //# sourceMappingURL=chunk-4CJ7B5OR.js.map
476
+ //# sourceMappingURL=chunk-6N2HEV3U.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server/http.ts","../src/server/webhook.ts","../src/server/routes.ts","../src/server/jobs.ts","../src/server/index.ts"],"sourcesContent":["import type { z } from \"zod\";\n\nimport type { WireResponse } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceLogger } from \"../core/ports\";\nimport type { MarketplaceServerCopy } from \"./copy\";\n\n/**\n * What the route descriptors share: the config, the actor, and the two answer\n * shapes every handler uses.\n */\n\n/** Whoever the host resolved: the tenant this request may act inside. */\nexport interface MarketplaceActor {\n /** The tenant's id — every engine call is scoped to it. */\n clientId: string;\n /** The person, for the audit line an archive writes. Null for a system caller. */\n userId?: string | null;\n}\n\nexport interface MarketplaceApiConfig {\n /** The mounted engine (`createMarketplaceEngine`). */\n engine: MarketplaceEngine;\n /** Every sentence the routes answer a person with. Required, no defaults. */\n copy: MarketplaceServerCopy;\n /**\n * Which tenant a webhook's URL slug names, or null for none. The webhook is\n * unauthenticated by design (a marketplace cannot sign in), so the tenant\n * comes from the URL and is then proved by that tenant's signature secret.\n */\n tenantBySlug: (slug: string) => Promise<string | null>;\n /** Where the routes say what they refused. The manifest's `marketplace` namespace. */\n logger: MarketplaceLogger;\n}\n\n/** A 200 in the `{ data }` envelope. */\nexport function ok(data: unknown): WireResponse {\n return { status: 200, body: { data } };\n}\n\n/** A refusal in the `{ error }` envelope, with any extra fields beside it. */\nexport function refuse(status: number, error: string, extra: Record<string, unknown> = {}): WireResponse {\n return { status, body: { error, ...extra } };\n}\n\n/** The parsed value, or the 422 that names every problem and its path. */\nexport function parse<T>(\n schema: z.ZodType<T>,\n value: unknown,\n copy: MarketplaceServerCopy,\n): { ok: true; value: T } | { ok: false; response: WireResponse } {\n const parsed = schema.safeParse(value ?? {});\n if (parsed.success) return { ok: true, value: parsed.data };\n const problems = parsed.error.issues.map((issue) => ({\n path: issue.path.map((segment) => (typeof segment === \"number\" ? segment : String(segment))),\n code: \"INVALID_INPUT\",\n message: issue.message,\n }));\n return { ok: false, response: refuse(422, copy.invalidInput, { problems }) };\n}\n\n/** An ISO string, or null. */\nexport function iso(value: Date | null | undefined): string | null {\n return value ? value.toISOString() : null;\n}\n","import type { WireRequest, WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { IngestionTarget } from \"../core/integration\";\nimport type { MarketplaceApiConfig } from \"./http\";\n\n/**\n * `POST /webhooks/marketplace/:tenantSlug/:provider` — inbound deliveries for\n * ONE store, from any registered marketplace.\n *\n * PUBLIC by design (`kind: \"webhook\"`): a marketplace cannot authenticate as a\n * user. The store is attributed from the URL slug, then the delivery is\n * verified against THAT store's secret, through the provider's own adapter\n * (which header carries the signature, and how it is computed) — the route\n * itself knows no marketplace.\n *\n * It answers 2xx for almost everything, deliberately. A marketplace\n * redelivers on any non-2xx, so the only failures worth signalling are the\n * ones a redelivery could fix: a genuine processing failure answers 500, and\n * the inbox row it left is retried by the sweep regardless. Refusals (unknown\n * slug, no connection, bad signature) answer 401, indistinguishably, so a\n * prober cannot learn which stores exist. The bodies are machine codes: the\n * reader is a server, not a person.\n */\n\nconst UNAUTHORIZED: WireResponse = { status: 401, body: { error: \"unauthorized\" } };\n\n/**\n * The tenant the slug names and its connection to this marketplace, or the\n * 401 that ends the request. A blob that will not open is a 401 too, logged:\n * a key problem must never read as \"no secret configured\".\n */\nasync function connectionOf(\n config: MarketplaceApiConfig,\n tenantSlug: string,\n provider: string,\n): Promise<{ clientId: string; target: IngestionTarget } | WireResponse> {\n const clientId = await config.tenantBySlug(tenantSlug);\n if (!clientId) {\n config.logger.warn(`marketplace.webhook: unknown tenant slug \"${tenantSlug}\" (${provider})`);\n return UNAUTHORIZED;\n }\n try {\n const target = await config.engine.target(clientId, provider);\n // No connection at all: refused rather than stored — without one there is\n // no secret to verify against.\n return target ? { clientId, target } : UNAUTHORIZED;\n } catch (error) {\n config.logger.error(\n `marketplace.webhook: ${tenantSlug} ${provider} credentials do not open: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n return UNAUTHORIZED;\n }\n}\n\n/** The verified, parsed delivery, or the answer that ends the request. */\nasync function admit(\n config: MarketplaceApiConfig,\n request: WireRequest<unknown>,\n): Promise<{ clientId: string; provider: string; payload: unknown; target: IngestionTarget } | WireResponse> {\n const { tenantSlug = \"\", provider = \"\" } = request.params;\n const { engine } = config;\n if (!engine.knows(provider)) return { status: 404, body: { error: \"unknown_provider\" } };\n const raw = request.request;\n if (!raw) return { status: 400, body: { error: \"raw_request_required\" } };\n\n const connection = await connectionOf(config, tenantSlug, provider);\n if (\"status\" in connection) return connection;\n const rawBody = await raw.text();\n const signature = engine.readSignature(provider, (name) => raw.headers.get(name));\n if (!engine.verifySignature(provider, rawBody, signature, connection.target.webhookSecret)) {\n config.logger.warn(`marketplace.webhook: ${tenantSlug} ${provider} signature rejected`);\n return UNAUTHORIZED;\n }\n try {\n return { ...connection, provider, payload: JSON.parse(rawBody) as unknown };\n } catch {\n return { status: 400, body: { error: \"invalid_json\" } };\n }\n}\n\n/** Record and act on one verified delivery. */\nasync function handleWebhook(config: MarketplaceApiConfig, request: WireRequest<unknown>): Promise<WireResponse> {\n const admitted = await admit(config, request);\n if (\"status\" in admitted) return admitted;\n const { clientId, provider, payload, target } = admitted;\n const { engine } = config;\n\n const event = engine.normalize(provider, payload);\n if (!event) {\n // Nothing the adapter can key on. 200: redelivering an unreadable payload\n // produces an identical unreadable payload.\n config.logger.warn(`marketplace.webhook: ${provider} payload did not normalize`);\n return { status: 200, body: { received: true, ignored: \"unrecognized_payload\" } };\n }\n const outcome = await engine.deliver({\n clientId,\n event,\n payload,\n // A DISABLED connection still stores its deliveries and ingests nothing;\n // the retry sweep ingests them if the store turns it back on.\n settings: target.enabled\n ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds, followStatus: target.followStatus }\n : null,\n });\n if (outcome.kind === \"failed\") {\n return { status: 500, body: { received: true, error: outcome.reason } };\n }\n return { status: 200, body: { received: true, outcome: outcome.kind } };\n}\n\n/** The webhook descriptor. Raw body required: signatures are computed over bytes. */\nexport function webhookRoute(config: MarketplaceApiConfig): WireRoute<unknown> {\n return {\n method: \"POST\",\n path: \"/webhooks/marketplace/:tenantSlug/:provider\",\n kind: \"webhook\",\n handle: (request) => handleWebhook(config, request),\n };\n}\n","import type { WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { BulkProblem } from \"../core/bulk\";\nimport type { DecisionProblem } from \"../core/cancellation\";\nimport type { MarketplaceIntegrationView } from \"../core/integration\";\nimport type { MarketplaceMenuLinkView } from \"../core/menu-links\";\nimport { MARKETPLACE_DECIDE, MARKETPLACE_MANAGE } from \"./contribution\";\nimport type { MarketplaceServerCopy } from \"./copy\";\nimport { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from \"./http\";\nimport {\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nimport { webhookRoute } from \"./webhook\";\n\n/**\n * The marketplace HTTP surface as framework-neutral wiring descriptors: the\n * webhook every marketplace posts to, and, per entity, one read and one bulk\n * write — connections, SKU links, decisions — for a store's staff and its MCP\n * tools alike.\n *\n * There is no authentication, tenant resolution or RBAC in here: each\n * descriptor DECLARES the permission it needs and the host's guard answers it;\n * the actor arrives already resolved. Paths are relative to the host's mount.\n */\n\nexport type MarketplaceRoute = WireRoute<MarketplaceActor> | WireRoute<unknown>;\n\nconst BASE = \"/admin/:tenantSlug/marketplace\";\n\n/** The 409 code of a decision on an order that is no longer on the clock. */\nexport const ORDER_NOT_PENDING_CODE = \"MARKETPLACE_ORDER_NOT_PENDING\";\n\nconst NOT_PENDING = new Set([\"NOT_FOUND\", \"ALREADY_DECIDED\", \"EXPIRED\", \"CONFLICT\"]);\n\n/** A connection as the read returns it: dates as ISO, the adapter's half beside it. */\nfunction integrationOut(config: MarketplaceApiConfig, row: MarketplaceIntegrationView) {\n const adapter = config.engine.adapter(row.provider);\n return {\n ...row,\n lastEventAt: iso(row.lastEventAt),\n lastVerifiedAt: iso(row.lastVerifiedAt),\n archivedAt: iso(row.archivedAt),\n capabilities: adapter ? adapter.capabilities : null,\n reasons: adapter ? [...adapter.cancellationReasons()] : [],\n };\n}\n\nfunction linkOut(link: MarketplaceMenuLinkView) {\n return { ...link, lastSeenAt: link.lastSeenAt.toISOString() };\n}\n\n/** Each problem with its sentence; a host refusal keeps the host's own words. */\nfunction problemsOut(copy: MarketplaceServerCopy, problems: readonly (BulkProblem | DecisionProblem)[]) {\n return problems.map((problem) => {\n const host = \"host\" in problem ? problem.host : undefined;\n return {\n ...problem,\n message: host?.message ?? copy.problems[problem.code],\n ...(host ? { hostCode: host.code, details: host.details } : {}),\n };\n });\n}\n\n/** A refused bulk write: 422, nothing saved, every problem with its path. */\nfunction refusedBulk(copy: MarketplaceServerCopy, problems: readonly BulkProblem[]): WireResponse {\n return refuse(422, copy.nothingSaved, { problems: problemsOut(copy, problems) });\n}\n\n/**\n * A refused decision call. The host's own refusal is a 409 carrying ITS code\n * (`MARKETPLACE_STOCK_ASK` and the short lines in `details`); an order no\n * longer on the clock a 409; anything else (a reason, an item) a 422.\n */\nfunction refusedDecisions(copy: MarketplaceServerCopy, problems: readonly DecisionProblem[]): WireResponse {\n const out = problemsOut(copy, problems);\n const host = problems.find((problem) => problem.code === \"HOST_REFUSED\")?.host;\n if (host) return refuse(409, host.message, { code: host.code, details: host.details, problems: out });\n if (problems.some((problem) => NOT_PENDING.has(problem.code))) {\n return refuse(409, copy.orderNoLongerPending, { code: ORDER_NOT_PENDING_CODE, problems: out });\n }\n return refuse(422, copy.nothingSaved, { problems: out });\n}\n\nfunction integrationRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceIntegrationsQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const rows = await engine.integrations(actor.clientId, {\n providers: parsed.value.ids,\n includeArchived: parsed.value.includeArchived === \"true\",\n });\n return ok(rows.map((row) => integrationOut(config, row)));\n },\n },\n {\n method: \"PUT\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceIntegrationsBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertIntegrations({\n clientId: actor.clientId,\n actorId: actor.userId ?? null,\n validateOnly: parsed.value.validateOnly,\n rows: parsed.value.integrations.map((row) =>\n \"credentials\" in row && row.credentials\n ? { ...row, credentials: { ...row.credentials, webhookSecret: row.credentials.webhookSecret ?? null } }\n : row,\n ) as Parameters<typeof engine.upsertIntegrations>[0][\"rows\"],\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, integrations: result.rows.map((row) => integrationOut(config, row)) });\n },\n },\n ];\n}\n\nfunction menuLinkRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceMenuLinksQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const links = await engine.menuLinks({\n clientId: actor.clientId,\n provider: parsed.value.provider,\n unmappedOnly: parsed.value.unmapped === \"true\",\n ids: parsed.value.ids,\n });\n return ok(links.map(linkOut));\n },\n },\n {\n method: \"PUT\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceMenuLinksBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertMenuLinks({\n clientId: actor.clientId,\n rows: parsed.value.links,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, links: result.rows.map(linkOut) });\n },\n },\n ];\n}\n\nfunction acceptanceRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceAcceptancesQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const pending = await engine.pending(actor.clientId, parsed.value.ids);\n return ok(\n pending.map((order) => ({\n ...order,\n acknowledgeBy: iso(order.acknowledgeBy),\n externalDueAt: iso(order.externalDueAt),\n })),\n );\n },\n },\n {\n method: \"POST\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, body }) => {\n const parsed = parse(decideMarketplaceOrdersBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.decideMany({\n clientId: actor.clientId,\n decisions: parsed.value.decisions,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedDecisions(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, decisions: result.rows });\n },\n },\n ];\n}\n\n/** The whole surface, in mount order. */\nexport function marketplaceRoutes(config: MarketplaceApiConfig): MarketplaceRoute[] {\n return [\n webhookRoute(config),\n ...integrationRoutes(config),\n ...menuLinkRoutes(config),\n ...acceptanceRoutes(config),\n ];\n}\n","import type { JobsContribution, WireJobBlueprint } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport { CatalogueRetryError, type CatalogueJobPayload } from \"../core/catalogue-job\";\nimport { FetchOrderRetryError, type FetchOrderJobPayload } from \"../core/fetch-order\";\nimport { OutboundRetryError } from \"../core/outbound\";\nimport type { OutboundJobPayload } from \"../core/outbound-queue\";\nimport { AvailabilityRetryError } from \"../core/pause-job\";\nimport type { AvailabilityJobPayload } from \"../core/pause-store\";\n\n/**\n * The engine's eight jobs, declared here because every number in them is the\n * engine's knowledge, not a host's:\n *\n * - `expire-acceptances`, every minute: the unit being measured is minutes (a\n * default window is five), so a coarser tick would make \"expired\" mean\n * anywhere from five to twenty.\n * - `reconcile-inbox`, every five minutes: nothing races a deadline here, and\n * each pass re-runs real ingestion work; the engine's attempt bound retires\n * a payload that will never succeed.\n * - `outbound`, on demand: one call to a marketplace, three attempts with\n * backoff. Its idempotency is the ROW's (the engine re-reads it), never the\n * queue's dedupe alone.\n * - `fetch-order`, on demand: one GET of an order a marketplace's event only\n * announced (`orderToFetch`), then the one ingest path. Three attempts with\n * backoff; the reconciliation sweep re-queues a row still owed.\n * - `catalogue`, on demand: one publish or withdraw of one product on one\n * marketplace's catalogue (FUT-4768). Three attempts with backoff; the\n * last one stamps FAILED with a failure code.\n * - `outbound-sweep`, every five minutes: re-queues every call a row still\n * owes (a PENDING request, an accept with no confirm stamp, a catalogue\n * publish or withdraw on its way) once it is older than the job's own retry\n * span, so a refused enqueue or a dead process loses nothing.\n * - `availability`, on demand: brings one marketplace in line with the host's\n * last pause or resume ask for one store (FUT-4851). Three attempts with\n * backoff; the last one stamps FAILED with a failure code.\n * - `availability-sweep`, every five minutes: resumes a pause past its\n * `until` (the host stopped renewing it), re-queues an ask still owed, and\n * gives up on one older than a day.\n *\n * What stays the host's: whether to run them at all, on which runtime, and the\n * lease implementation. A host with no worker declines `jobs` in writing.\n *\n * Bound with `{ engine }`, these arrive at a runner as\n * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,\n * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.catalogue`,\n * `marketplace.outbound-sweep`, `marketplace.availability` and\n * `marketplace.availability-sweep`.\n */\n\n/** What the host closes over at bind time: the mounted engine. */\nexport interface MarketplaceJobDeps {\n engine: Pick<\n MarketplaceEngine,\n | \"expireLapsed\"\n | \"retryable\"\n | \"reprocess\"\n | \"runOutbound\"\n | \"runFetchOrder\"\n | \"runCatalogue\"\n | \"sweepOutbound\"\n | \"runAvailability\"\n | \"sweepAvailability\"\n >;\n}\n\n/** The single-flight queue name (`@12-apps/jobs`' `SWEEP_QUEUE`), as a literal. */\nexport const MARKETPLACE_SWEEP_QUEUE = \"sweeps\";\n\n/** How long one sweep pass may hold its name. */\nconst SWEEP_LEASE_MS = 5 * 60_000;\n\n/** The outbound job's attempts: the last one stamps the failure. */\nexport const MARKETPLACE_OUTBOUND_ATTEMPTS = 3;\n\nconst expireAcceptances: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"expire-acceptances\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"* * * * *\", timezone: \"UTC\" },\n // Never retried by the queue: the next tick re-finds everything from the rows.\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.expireLapsed();\n if (result.expired === 0) return;\n context.logger.info(\n `marketplace.expire-acceptances: expired ${result.expired} order(s) across ${result.tenants} tenant(s).`,\n );\n },\n};\n\nconst reconcileInbox: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"reconcile-inbox\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const pending = await deps.engine.retryable();\n let ingested = 0;\n // One event's failure never wedges the batch: `reprocess` never throws.\n for (const event of pending) {\n const outcome = await deps.engine.reprocess(event);\n if (outcome.kind === \"ingested\") ingested += 1;\n }\n if (pending.length === 0) return;\n context.logger.info(\n `marketplace.reconcile-inbox: re-ran ${pending.length} stored delivery(ies), ${ingested} became order(s).`,\n );\n },\n};\n\nconst outbound: WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps> = {\n name: \"outbound\",\n attempts: MARKETPLACE_OUTBOUND_ATTEMPTS,\n backoff: { type: \"exponential\", delayMs: 30_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runOutbound(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.outbound: ${payload.action} ${payload.orderId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof OutboundRetryError) context.logger.warn(`marketplace.outbound: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The fetch job's attempts: the last one settles the inbox row FAILED. */\nexport const MARKETPLACE_FETCH_ORDER_ATTEMPTS = 3;\n\nconst fetchOrder: WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps> = {\n name: \"fetch-order\",\n attempts: MARKETPLACE_FETCH_ORDER_ATTEMPTS,\n // Short: an order waiting for its body is on the store's acceptance clock.\n backoff: { type: \"exponential\", delayMs: 5_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runFetchOrder(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.fetch-order: inbox ${payload.inboxId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof FetchOrderRetryError) context.logger.warn(`marketplace.fetch-order: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The catalogue job's attempts: the last one stamps FAILED. */\nconst MARKETPLACE_CATALOGUE_ATTEMPTS = 3;\n\nconst catalogue: WireJobBlueprint<CatalogueJobPayload, MarketplaceJobDeps> = {\n name: \"catalogue\",\n attempts: MARKETPLACE_CATALOGUE_ATTEMPTS,\n // Short: a person is watching the switch say \"sending\".\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runCatalogue(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.catalogue: ${payload.action} ${payload.publicationId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof CatalogueRetryError) context.logger.warn(`marketplace.catalogue: ${error.message}`);\n throw error;\n }\n },\n};\n\nconst outboundSweep: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"outbound-sweep\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.sweepOutbound();\n const idle = result.requeued + result.givenUp + result.timedOut + result.catalogueRequeued === 0;\n if (idle) return;\n context.logger.info(\n `marketplace.outbound-sweep: re-queued ${result.requeued} call(s) and ${result.catalogueRequeued} catalogue ` +\n `call(s), timed out ${result.timedOut} cancellation request(s), gave up on ${result.givenUp}.`,\n );\n },\n};\n\n/** The availability job's attempts: the last one stamps FAILED. */\nexport const MARKETPLACE_AVAILABILITY_ATTEMPTS = 3;\n\nconst availability: WireJobBlueprint<AvailabilityJobPayload, MarketplaceJobDeps> = {\n name: \"availability\",\n attempts: MARKETPLACE_AVAILABILITY_ATTEMPTS,\n // Short: a store is open on the marketplace while the kitchen is paused.\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runAvailability(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.availability: ${payload.provider} ${payload.clientId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof AvailabilityRetryError) context.logger.warn(`marketplace.availability: ${error.message}`);\n throw error;\n }\n },\n};\n\nconst availabilitySweep: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"availability-sweep\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.sweepAvailability();\n if (result.expired + result.requeued + result.givenUp === 0) return;\n context.logger.info(\n `marketplace.availability-sweep: resumed ${result.expired} expired pause(s), re-queued ${result.requeued}, ` +\n `gave up on ${result.givenUp}.`,\n );\n },\n};\n\n/** The jobs contribution. */\nexport const MARKETPLACE_JOBS = {\n namespace: \"marketplace\",\n blueprints: {\n \"expire-acceptances\": expireAcceptances,\n \"reconcile-inbox\": reconcileInbox,\n outbound,\n \"fetch-order\": fetchOrder,\n catalogue,\n \"outbound-sweep\": outboundSweep,\n availability,\n \"availability-sweep\": availabilitySweep,\n },\n} as const satisfies JobsContribution<MarketplaceJobDeps>;\n","import type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceApiConfig } from \"./http\";\nimport { marketplaceRoutes, type MarketplaceRoute } from \"./routes\";\n\n/**\n * `@12-apps/marketplace/server` — the engine's HTTP surface, jobs, MCP tools\n * and permissions, as wiring-contract values.\n *\n * ```ts\n * const engine = createMarketplaceEngine({ …ports, adapters });\n * const api = createApiMarketplace({ engine, copy, tenantBySlug, logger });\n * // api.routes: mount under `/api` (the hono adapter does it in one line)\n * ```\n */\n\n/** What `createApiMarketplace` hands back: the routes, and the engine they serve. */\nexport interface ApiMarketplace {\n routes: MarketplaceRoute[];\n engine: MarketplaceEngine;\n}\n\n/** Build the route table over a mounted engine. */\nexport function createApiMarketplace(config: MarketplaceApiConfig): ApiMarketplace {\n if (!config.logger) {\n throw new Error(\"@12-apps/marketplace: the observability namespace needs a logger; pass `logger`.\");\n }\n return { routes: marketplaceRoutes(config), engine: config.engine };\n}\n\nexport type { MarketplaceActor, MarketplaceApiConfig } from \"./http\";\nexport type { MarketplaceRoute } from \"./routes\";\nexport type { MarketplaceServerCopy } from \"./copy\";\nexport {\n MARKETPLACE_DECIDE,\n MARKETPLACE_MANAGE,\n MARKETPLACE_PERMISSIONS,\n} from \"./contribution\";\nexport {\n MARKETPLACE_AVAILABILITY_ATTEMPTS,\n MARKETPLACE_FETCH_ORDER_ATTEMPTS,\n MARKETPLACE_JOBS,\n MARKETPLACE_OUTBOUND_ATTEMPTS,\n MARKETPLACE_SWEEP_QUEUE,\n type MarketplaceJobDeps,\n} from \"./jobs\";\nexport {\n MARKETPLACE_MCP_TOOLS,\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n marketplaceParams,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nexport { ORDER_NOT_PENDING_CODE } from \"./routes\";\nexport type { MarketplaceProblemCode } from \"./copy\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqCO,SAAS,GAAG,MAA6B;AAC9C,SAAO,EAAE,QAAQ,KAAK,MAAM,EAAE,KAAK,EAAE;AACvC;AAFgB;AAKT,SAAS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CAA2C,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":[]}
@@ -79,13 +79,17 @@ __name(suggestReason, "suggestReason");
79
79
  // src/core/outbound-queue.ts
80
80
  var MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
81
81
  function outboundDedupeKey(payload) {
82
- return `${MARKETPLACE_OUTBOUND_JOB}:${payload.action}:${payload.orderId}`;
82
+ return `${MARKETPLACE_OUTBOUND_JOB}:${payload.action}:${payload.step ? `${payload.step}:` : ""}${payload.orderId}`;
83
83
  }
84
84
  __name(outboundDedupeKey, "outboundDedupeKey");
85
+ function statusDedupeKey(step, orderId, at) {
86
+ return `${MARKETPLACE_OUTBOUND_JOB}:status:${step}:${orderId}:${at.getTime()}`;
87
+ }
88
+ __name(statusDedupeKey, "statusDedupeKey");
85
89
  async function enqueueOutbound(ctx, payload, provider, dedupeKey = outboundDedupeKey(payload)) {
86
90
  const adapter = ctx.registry.get(provider);
87
91
  if (!adapter) return false;
88
- const able = payload.action === "confirm" ? adapter.capabilities.apiConfirm : adapter.capabilities.apiCancel;
92
+ const able = payload.action === "status" ? Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step)) : payload.action === "confirm" ? adapter.capabilities.apiConfirm : adapter.capabilities.apiCancel;
89
93
  if (!able) return false;
90
94
  const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
91
95
  if (!outcome.enqueued) {
@@ -165,6 +169,7 @@ var VIEW_SELECT = {
165
169
  status: true,
166
170
  externalMerchantId: true,
167
171
  autoAccept: true,
172
+ followStatus: true,
168
173
  ackSlaSeconds: true,
169
174
  credentials: true,
170
175
  lastEventAt: true,
@@ -179,6 +184,7 @@ function toView(row) {
179
184
  status: row.status,
180
185
  externalMerchantId: row.externalMerchantId,
181
186
  autoAccept: row.autoAccept,
187
+ followStatus: row.followStatus ?? true,
182
188
  ackSlaSeconds: row.ackSlaSeconds,
183
189
  connected: row.credentials !== "",
184
190
  lastEventAt: row.lastEventAt,
@@ -208,6 +214,7 @@ async function saveMarketplaceIntegration(ctx, input, db) {
208
214
  ...input.environment === void 0 ? {} : { environment: input.environment },
209
215
  ...input.externalMerchantId === void 0 ? {} : { externalMerchantId: input.externalMerchantId },
210
216
  ...input.autoAccept === void 0 ? {} : { autoAccept: input.autoAccept },
217
+ ...input.followStatus === void 0 ? {} : { followStatus: input.followStatus },
211
218
  ...input.ackSlaSeconds === void 0 ? {} : { ackSlaSeconds: input.ackSlaSeconds },
212
219
  ...sealed === void 0 ? {} : { credentials: sealed, status: "UNVERIFIED" }
213
220
  };
@@ -242,6 +249,7 @@ async function resolveIngestionTarget(ctx, clientId, provider) {
242
249
  select: {
243
250
  enabled: true,
244
251
  autoAccept: true,
252
+ followStatus: true,
245
253
  ackSlaSeconds: true,
246
254
  credentials: true,
247
255
  archivedAt: true,
@@ -252,6 +260,7 @@ async function resolveIngestionTarget(ctx, clientId, provider) {
252
260
  return {
253
261
  enabled: row.enabled,
254
262
  autoAccept: row.autoAccept,
263
+ followStatus: row.followStatus ?? true,
255
264
  ackSlaSeconds: row.ackSlaSeconds,
256
265
  externalMerchantId: row.externalMerchantId ?? null,
257
266
  // An unopenable blob must not read as "no secret configured" — that would
@@ -942,6 +951,7 @@ function refusalData(plan, fromStatus, now) {
942
951
  cancellationReasonCode: plan.reason?.code ?? null,
943
952
  cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
944
953
  cancellationRequestedAt: plan.status === "PENDING" ? now : null,
954
+ // FAILED here means the adapter has no cancellation API to call: the marketplace's own limit, REFUSED.
945
955
  cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null
946
956
  };
947
957
  }
@@ -952,6 +962,7 @@ function requestData(plan, now) {
952
962
  cancellationReasonCode: plan.reason?.code ?? null,
953
963
  cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
954
964
  cancellationRequestedAt: plan.status === "PENDING" ? now : null,
965
+ // FAILED here means the adapter has no cancellation API to call: the marketplace's own limit, REFUSED.
955
966
  cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null
956
967
  };
957
968
  }
@@ -1066,10 +1077,10 @@ async function cancelAcceptance(ctx, input) {
1066
1077
  __name(cancelAcceptance, "cancelAcceptance");
1067
1078
 
1068
1079
  // src/core/order-fetch-marks.ts
1080
+ var CANCELLED_BEFORE_INGEST_REASON = "cancelled before its order body arrived";
1069
1081
  var MARKER_TYPE = "ENGINE_CANCELLED_BEFORE_INGEST";
1070
1082
  var markerId = /* @__PURE__ */ __name((externalOrderId) => `engine:cancelled:${externalOrderId}`, "markerId");
1071
1083
  async function markCancelledBeforeIngest(ctx, input) {
1072
- if (!ctx.registry.get(input.provider)?.fetchOrder) return;
1073
1084
  const db = await ctx.ports.db();
1074
1085
  try {
1075
1086
  await db.marketplaceInboxEvent.create({
@@ -1171,7 +1182,7 @@ async function fetchThroughAdapter(ctx, clientId, provider, externalOrderId) {
1171
1182
  __name(fetchThroughAdapter, "fetchThroughAdapter");
1172
1183
  async function refusalOf(ctx, clientId, order, connectionMerchantId2) {
1173
1184
  if (await cancelledBeforeIngest(ctx, { clientId, provider: order.provider, externalOrderId: order.externalOrderId })) {
1174
- return { settle: "IGNORED", reason: "cancelled before its order body arrived", failed: false };
1185
+ return { settle: "IGNORED", reason: CANCELLED_BEFORE_INGEST_REASON, failed: false };
1175
1186
  }
1176
1187
  const mismatch = merchantMismatch(order, connectionMerchantId2);
1177
1188
  return mismatch ? { settle: "FAILED", reason: mismatch, failed: true } : null;
@@ -1253,20 +1264,58 @@ async function sweepCatalogue(ctx, now) {
1253
1264
  }
1254
1265
  __name(sweepCatalogue, "sweepCatalogue");
1255
1266
 
1267
+ // src/core/status-store.ts
1268
+ function statusTable(db) {
1269
+ return db.marketplaceStatusUpdate ?? null;
1270
+ }
1271
+ __name(statusTable, "statusTable");
1272
+ async function readStatusRows(table, orderId, steps2) {
1273
+ return await table.findMany({
1274
+ where: { orderId, step: { in: [...steps2] } },
1275
+ select: { orderId: true, step: true, source: true, state: true, claimKey: true }
1276
+ });
1277
+ }
1278
+ __name(readStatusRows, "readStatusRows");
1279
+ async function insertStatusRow(table, row) {
1280
+ try {
1281
+ await table.create({ data: row });
1282
+ return true;
1283
+ } catch (error) {
1284
+ if (error.code === "P2002") return false;
1285
+ throw error;
1286
+ }
1287
+ }
1288
+ __name(insertStatusRow, "insertStatusRow");
1289
+ async function noteMarketplaceStep(ctx, row) {
1290
+ const table = statusTable(await ctx.ports.db());
1291
+ if (table) await insertStatusRow(table, { ...row, source: "MARKETPLACE", state: "NOTED", claimKey: "" });
1292
+ }
1293
+ __name(noteMarketplaceStep, "noteMarketplaceStep");
1294
+ async function settleStatusRow(table, where, state) {
1295
+ return (await table.updateMany({ where: { ...where, state: "SENDING" }, data: { state } })).count;
1296
+ }
1297
+ __name(settleStatusRow, "settleStatusRow");
1298
+
1256
1299
  // src/core/outbound-sweep.ts
1257
1300
  var OUTBOUND_STALE_MS = 10 * 6e4;
1258
1301
  var OUTBOUND_GIVE_UP_MS = 24 * 60 * 6e4;
1259
1302
  var WAITING = ["PENDING", "REQUESTED"];
1260
1303
  var OWED_SELECT = { clientId: true, orderId: true, provider: true };
1261
- function sweepDedupeKey(action, orderId, now) {
1262
- return `${MARKETPLACE_OUTBOUND_JOB}:${action}:${orderId}:sweep:${now.getTime()}`;
1304
+ function sweepDedupeKey(action, orderId, now, step) {
1305
+ return `${MARKETPLACE_OUTBOUND_JOB}:${action}:${step ? `${step}:` : ""}${orderId}:sweep:${now.getTime()}`;
1263
1306
  }
1264
1307
  __name(sweepDedupeKey, "sweepDedupeKey");
1265
1308
  async function requeue(ctx, rows, action, now) {
1266
1309
  let queued = 0;
1267
1310
  for (const row of rows) {
1268
- const payload = { clientId: row.clientId, orderId: row.orderId, action };
1269
- if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now))) queued += 1;
1311
+ const payload = {
1312
+ clientId: row.clientId,
1313
+ orderId: row.orderId,
1314
+ action,
1315
+ ...row.step ? { step: row.step } : {},
1316
+ ...row.claimKey === void 0 ? {} : { claimKey: row.claimKey }
1317
+ };
1318
+ if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now, row.step))) queued += 1;
1270
1319
  }
1271
1320
  return queued;
1272
1321
  }
@@ -1308,6 +1357,29 @@ async function expireUnanswered(ctx, now) {
1308
1357
  return expired;
1309
1358
  }
1310
1359
  __name(expireUnanswered, "expireUnanswered");
1360
+ async function sweepStatus(ctx, now) {
1361
+ const table = statusTable(await ctx.ports.db());
1362
+ if (!table) return { requeued: 0, givenUp: 0 };
1363
+ const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);
1364
+ const giveUp = new Date(now.getTime() - OUTBOUND_GIVE_UP_MS);
1365
+ const givenUp = (await table.updateMany({ where: { state: "SENDING", updatedAt: { lt: giveUp } }, data: { state: "FAILED" } })).count;
1366
+ if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} status call(s).`);
1367
+ const owed = await table.findMany({
1368
+ where: { state: "SENDING", source: "STORE", updatedAt: { lt: stale, gte: giveUp } },
1369
+ select: { clientId: true, orderId: true, provider: true, step: true, claimKey: true }
1370
+ });
1371
+ const claimed = [];
1372
+ for (const row of owed) {
1373
+ const fresh = `sweep:${now.getTime()}`;
1374
+ const taken = await table.updateMany({
1375
+ where: { orderId: row.orderId, step: row.step, state: "SENDING", claimKey: row.claimKey, updatedAt: { lt: stale } },
1376
+ data: { claimKey: fresh }
1377
+ });
1378
+ if (taken.count > 0) claimed.push({ ...row, claimKey: fresh });
1379
+ }
1380
+ return { requeued: await requeue(ctx, claimed, "status", now), givenUp };
1381
+ }
1382
+ __name(sweepStatus, "sweepStatus");
1311
1383
  async function sweepOutbound(ctx, now) {
1312
1384
  const db = await ctx.ports.db();
1313
1385
  const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);
@@ -1332,10 +1404,113 @@ async function sweepOutbound(ctx, now) {
1332
1404
  const requeued = await requeue(ctx, cancellations, "requestCancellation", now) + await requeue(ctx, confirms, "confirm", now);
1333
1405
  if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} cancellation request(s).`);
1334
1406
  const catalogueRequeued = await sweepCatalogue(ctx, now);
1335
- return { requeued, givenUp, timedOut, catalogueRequeued };
1407
+ const status = await sweepStatus(ctx, now);
1408
+ return { requeued: requeued + status.requeued, givenUp: givenUp + status.givenUp, timedOut, catalogueRequeued };
1336
1409
  }
1337
1410
  __name(sweepOutbound, "sweepOutbound");
1338
1411
 
1412
+ // src/core/status-job.ts
1413
+ function deliveredByOf(row) {
1414
+ return row.deliveredBy === "MERCHANT" || row.deliveredBy === "MARKETPLACE" ? row.deliveredBy : null;
1415
+ }
1416
+ __name(deliveredByOf, "deliveredByOf");
1417
+ var skipped = /* @__PURE__ */ __name((reason) => ({ kind: "skipped", reason }), "skipped");
1418
+ function acceptanceSkip(row) {
1419
+ if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
1420
+ const standing = row.cancellationStatus !== null && row.cancellationStatus !== "FAILED";
1421
+ return standing ? `a cancellation request is ${row.cancellationStatus}` : null;
1422
+ }
1423
+ __name(acceptanceSkip, "acceptanceSkip");
1424
+ async function adapterAndHostSkip(ctx, payload, step, row, adapter) {
1425
+ const takes = adapter.informStatus !== void 0 && adapter.capabilities.statusSteps?.includes(step) === true && adapter.statusSupported?.({ step, deliveredBy: deliveredByOf(row) }) !== false;
1426
+ if (!takes) return `the marketplace does not take ${step} for this order`;
1427
+ const holds2 = ctx.ports.order.statusHolds;
1428
+ if (!holds2) return "the host binds no statusHolds, so it cannot say the order still holds the step";
1429
+ return await holds2.call(ctx.ports.order, payload.clientId, row.orderId, step) ? null : `the order no longer holds ${step}`;
1430
+ }
1431
+ __name(adapterAndHostSkip, "adapterAndHostSkip");
1432
+ async function connectionOf(ctx, clientId, provider) {
1433
+ try {
1434
+ return await readOutboundConnection(ctx, clientId, provider) ?? "no credentials on file";
1435
+ } catch (error) {
1436
+ return `credentials do not open: ${error instanceof Error ? error.message : String(error)}`;
1437
+ }
1438
+ }
1439
+ __name(connectionOf, "connectionOf");
1440
+ function callAdapter(ctx, connection, adapter, row, step, ref) {
1441
+ const now = ctx.ports.clock.now();
1442
+ return adapter.informStatus({ http: ctx.ports.http, tokens: ctx.tokens, now, ...connection }, ref, {
1443
+ step,
1444
+ deliveredBy: deliveredByOf(row)
1445
+ });
1446
+ }
1447
+ __name(callAdapter, "callAdapter");
1448
+ async function settle2(ctx, db, where, result, deps) {
1449
+ const table = statusTable(db);
1450
+ if (result.kind === "accepted") {
1451
+ await settleStatusRow(table, where, "SENT");
1452
+ return { kind: "done", action: "status" };
1453
+ }
1454
+ const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.kind === "retry" ? result.reason : "the adapter answered unsupported after the claim";
1455
+ if (result.kind === "retry" && deps.attempt.attempt < deps.attempt.maxAttempts) {
1456
+ throw deps.retryError(`status ${where.step} for order ${where.orderId}: ${reason}`);
1457
+ }
1458
+ await settleStatusRow(table, where, "FAILED");
1459
+ ctx.ports.logger.error(`${MARKETPLACE_OUTBOUND_JOB}: status ${where.step} for order ${where.orderId} failed: ${reason}`);
1460
+ return { kind: "failed", action: "status", reason };
1461
+ }
1462
+ __name(settle2, "settle");
1463
+ function ownsClaim(found, key) {
1464
+ return found.source === "STORE" && found.state === "SENDING" && found.claimKey === key;
1465
+ }
1466
+ __name(ownsClaim, "ownsClaim");
1467
+ async function claim2(table, payload, row, step, key) {
1468
+ const rows = await readStatusRows(table, row.orderId, [step, "CONCLUDED"]);
1469
+ if (rows.some((found) => found.step === "CONCLUDED" && found.source === "MARKETPLACE")) {
1470
+ return "the marketplace concluded this order";
1471
+ }
1472
+ const own = rows.find((found) => found.step === step);
1473
+ if (own) return ownsClaim(own, key) ? null : `${step} is already ${own.state}${own.state === "SENDING" ? ", held by another run" : ""}`;
1474
+ const claimed = await insertStatusRow(table, {
1475
+ clientId: payload.clientId,
1476
+ orderId: row.orderId,
1477
+ provider: row.provider,
1478
+ step,
1479
+ source: "STORE",
1480
+ state: "SENDING",
1481
+ claimKey: key
1482
+ });
1483
+ return claimed ? null : `another run holds the claim on ${step}`;
1484
+ }
1485
+ __name(claim2, "claim");
1486
+ async function runStatus(ctx, payload, row, adapter, deps) {
1487
+ const step = payload.step;
1488
+ if (!step) return skipped("a status call names no step");
1489
+ const stopped = acceptanceSkip(row) ?? await adapterAndHostSkip(ctx, payload, step, row, adapter);
1490
+ if (stopped) return skipped(stopped);
1491
+ const db = await ctx.ports.db();
1492
+ const table = statusTable(db);
1493
+ if (!table) return skipped("the host has not composed the status model");
1494
+ const connection = await connectionOf(ctx, payload.clientId, row.provider);
1495
+ if (typeof connection === "string") {
1496
+ ctx.ports.logger.info(`${MARKETPLACE_OUTBOUND_JOB}: status ${step} for order ${row.orderId} not sent: ${connection}`);
1497
+ return skipped(connection);
1498
+ }
1499
+ const key = payload.claimKey ?? "";
1500
+ const unclaimed = await claim2(table, payload, row, step, key);
1501
+ if (unclaimed) return skipped(unclaimed);
1502
+ const result = await callAdapter(ctx, connection, adapter, row, step, deps.ref);
1503
+ return settle2(ctx, db, { orderId: row.orderId, step, claimKey: key }, result, deps);
1504
+ }
1505
+ __name(runStatus, "runStatus");
1506
+ async function failStatusRow(ctx, payload) {
1507
+ const table = statusTable(await ctx.ports.db());
1508
+ if (table && payload.step) {
1509
+ await settleStatusRow(table, { orderId: payload.orderId, step: payload.step, claimKey: payload.claimKey ?? "" }, "FAILED");
1510
+ }
1511
+ }
1512
+ __name(failStatusRow, "failStatusRow");
1513
+
1339
1514
  // src/core/outbound.ts
1340
1515
  var OutboundRetryError = class extends Error {
1341
1516
  static {
@@ -1354,6 +1529,7 @@ var ROW_SELECT = {
1354
1529
  status: true,
1355
1530
  confirmedAt: true,
1356
1531
  confirmFailedAt: true,
1532
+ deliveredBy: true,
1357
1533
  cancellationStatus: true,
1358
1534
  cancellationReasonCode: true,
1359
1535
  cancellationOffendingSkus: true,
@@ -1388,15 +1564,15 @@ async function stampConfirm(ctx, row, succeeded, now) {
1388
1564
  });
1389
1565
  }
1390
1566
  __name(stampConfirm, "stampConfirm");
1391
- async function stampCancellation(ctx, row, status, clientId) {
1567
+ async function stampCancellation(ctx, row, status, clientId, failure = "REFUSED") {
1392
1568
  if (status === "CONFIRMED") return stampConfirmedCancellation(ctx, row, clientId);
1393
1569
  const db = await ctx.ports.db();
1394
- const data = status === "FAILED" ? failedRequestData("REFUSED") : { cancellationStatus: status };
1570
+ const data = status === "FAILED" ? failedRequestData(failure) : { cancellationStatus: status };
1395
1571
  const moved = await db.marketplaceAcceptance.updateMany({
1396
1572
  where: { orderId: row.orderId, cancellationStatus: "PENDING" },
1397
1573
  data
1398
1574
  });
1399
- if (moved.count > 0 && status === "FAILED") await tellCancellationFailed(ctx, clientId, row.orderId, "REFUSED");
1575
+ if (moved.count > 0 && status === "FAILED") await tellCancellationFailed(ctx, clientId, row.orderId, failure);
1400
1576
  }
1401
1577
  __name(stampCancellation, "stampCancellation");
1402
1578
  function answerableRequest(row) {
@@ -1435,7 +1611,7 @@ async function connectionFor(ctx, clientId, provider) {
1435
1611
  }
1436
1612
  }
1437
1613
  __name(connectionFor, "connectionFor");
1438
- async function settle2(ctx, payload, row, result, attempt, succeed, fail3) {
1614
+ async function settle3(ctx, payload, row, result, attempt, succeed, fail3) {
1439
1615
  if (result.kind === "accepted") {
1440
1616
  await succeed();
1441
1617
  ctx.ports.publishChanged(payload.clientId);
@@ -1445,24 +1621,24 @@ async function settle2(ctx, payload, row, result, attempt, succeed, fail3) {
1445
1621
  if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
1446
1622
  throw new OutboundRetryError(`${payload.action} for order ${row.orderId}: ${reason}`);
1447
1623
  }
1448
- await fail3();
1624
+ await fail3(result.kind === "refused" && !result.own ? "REFUSED" : "UNREACHABLE");
1449
1625
  ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${row.orderId} failed: ${reason}`);
1450
1626
  ctx.ports.publishChanged(payload.clientId);
1451
1627
  return { kind: "failed", action: payload.action, reason };
1452
1628
  }
1453
- __name(settle2, "settle");
1629
+ __name(settle3, "settle");
1454
1630
  async function runConfirm(ctx, payload, row, adapter, attempt) {
1455
1631
  const skip = confirmSkip(row, adapter);
1456
1632
  if (skip) return { kind: "skipped", reason: skip };
1457
1633
  const now = ctx.ports.clock.now();
1458
1634
  const connection = await connectionFor(ctx, payload.clientId, row.provider);
1459
- const result = typeof connection === "string" ? { kind: "refused", status: 0, message: connection } : await adapter.confirm(
1635
+ const result = typeof connection === "string" ? { kind: "refused", status: 0, message: connection, own: true } : await adapter.confirm(
1460
1636
  { http: ctx.ports.http, tokens: ctx.tokens, now, ...connection },
1461
1637
  refOf(row),
1462
1638
  // The stated preparation time, for a marketplace whose confirm takes one.
1463
1639
  { preparationMinutes: adapter.capabilities.confirmTakesPreparationTime ? row.preparationMinutes : null }
1464
1640
  );
1465
- return settle2(
1641
+ return settle3(
1466
1642
  ctx,
1467
1643
  payload,
1468
1644
  row,
@@ -1495,8 +1671,8 @@ async function runCancellation(ctx, payload, row, adapter, attempt) {
1495
1671
  const reason = resolveReason(adapter, row.cancellationReasonCode);
1496
1672
  const connection = await connectionFor(ctx, payload.clientId, row.provider);
1497
1673
  let result;
1498
- if (!reason) result = { kind: "refused", status: 0, message: "the stored reason is not the marketplace's" };
1499
- else if (typeof connection === "string") result = { kind: "refused", status: 0, message: connection };
1674
+ if (!reason) result = { kind: "refused", status: 0, message: "the stored reason is not the marketplace's", own: true };
1675
+ else if (typeof connection === "string") result = { kind: "refused", status: 0, message: connection, own: true };
1500
1676
  else {
1501
1677
  result = await adapter.requestCancellation(
1502
1678
  { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
@@ -1505,31 +1681,36 @@ async function runCancellation(ctx, payload, row, adapter, attempt) {
1505
1681
  );
1506
1682
  }
1507
1683
  const taken = adapter.capabilities.asyncCancellationOutcome ? "REQUESTED" : "CONFIRMED";
1508
- return settle2(
1684
+ return settle3(
1509
1685
  ctx,
1510
1686
  payload,
1511
1687
  row,
1512
1688
  result,
1513
1689
  attempt,
1514
1690
  () => stampCancellation(ctx, row, taken, payload.clientId),
1515
- () => stampCancellation(ctx, row, "FAILED", payload.clientId)
1691
+ (failure) => stampCancellation(ctx, row, "FAILED", payload.clientId, failure)
1516
1692
  );
1517
1693
  }
1518
1694
  __name(runCancellation, "runCancellation");
1519
1695
  async function stampLastAttemptFailure(ctx, payload, error) {
1520
1696
  const reason = error instanceof Error ? error.message : String(error);
1697
+ if (payload.action === "status") {
1698
+ await failStatusRow(ctx, payload);
1699
+ ctx.ports.logger.error(`marketplace.outbound: status ${payload.step ?? ""} for order ${payload.orderId} failed: ${reason}`);
1700
+ return { kind: "failed", action: payload.action, reason };
1701
+ }
1521
1702
  const db = await ctx.ports.db();
1522
1703
  const moved = await (payload.action === "confirm" ? db.marketplaceAcceptance.updateMany({
1523
1704
  where: { orderId: payload.orderId, clientId: payload.clientId, confirmedAt: null, confirmFailedAt: null },
1524
1705
  data: { confirmFailedAt: ctx.ports.clock.now() }
1525
1706
  }) : db.marketplaceAcceptance.updateMany({
1526
1707
  where: { orderId: payload.orderId, clientId: payload.clientId, cancellationStatus: "PENDING" },
1527
- data: failedRequestData("REFUSED")
1708
+ data: failedRequestData("UNREACHABLE")
1528
1709
  }));
1529
1710
  ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${payload.orderId} failed: ${reason}`);
1530
1711
  ctx.ports.publishChanged(payload.clientId);
1531
1712
  if (payload.action === "requestCancellation" && moved.count > 0) {
1532
- await tellCancellationFailed(ctx, payload.clientId, payload.orderId, "REFUSED");
1713
+ await tellCancellationFailed(ctx, payload.clientId, payload.orderId, "UNREACHABLE");
1533
1714
  }
1534
1715
  return { kind: "failed", action: payload.action, reason };
1535
1716
  }
@@ -1543,6 +1724,9 @@ async function runOnce2(ctx, payload, attempt) {
1543
1724
  if (!row) return { kind: "skipped", reason: "no acceptance for this order" };
1544
1725
  const adapter = ctx.registry.get(row.provider);
1545
1726
  if (!adapter) return { kind: "skipped", reason: `no adapter for ${row.provider}` };
1727
+ if (payload.action === "status") {
1728
+ return runStatus(ctx, payload, row, adapter, { attempt, ref: refOf(row), retryError: /* @__PURE__ */ __name((m) => new OutboundRetryError(m), "retryError") });
1729
+ }
1546
1730
  return payload.action === "confirm" ? runConfirm(ctx, payload, row, adapter, attempt) : runCancellation(ctx, payload, row, adapter, attempt);
1547
1731
  }
1548
1732
  __name(runOnce2, "runOnce");
@@ -1965,6 +2149,7 @@ export {
1965
2149
  upsertLink,
1966
2150
  MARKETPLACE_OUTBOUND_JOB,
1967
2151
  outboundDedupeKey,
2152
+ statusDedupeKey,
1968
2153
  enqueueOutbound,
1969
2154
  CATALOGUE_ROW_SELECT,
1970
2155
  catalogueTable,
@@ -1981,7 +2166,9 @@ export {
1981
2166
  deferInboxEvent,
1982
2167
  listRetryableInboxEvents,
1983
2168
  ingestMarketplaceOrder,
2169
+ CANCELLED_BEFORE_INGEST_REASON,
1984
2170
  markCancelledBeforeIngest,
2171
+ cancelledBeforeIngest,
1985
2172
  MARKETPLACE_FETCH_ORDER_JOB,
1986
2173
  FetchOrderRetryError,
1987
2174
  awaitOrderBody,
@@ -1990,6 +2177,9 @@ export {
1990
2177
  runFetchOrder,
1991
2178
  CATALOGUE_STALE_MS,
1992
2179
  CATALOGUE_GIVE_UP_MS,
2180
+ statusTable,
2181
+ readStatusRows,
2182
+ noteMarketplaceStep,
1993
2183
  OUTBOUND_STALE_MS,
1994
2184
  OUTBOUND_GIVE_UP_MS,
1995
2185
  sweepOutbound,
@@ -2006,4 +2196,4 @@ export {
2006
2196
  AvailabilityRetryError,
2007
2197
  runAvailability
2008
2198
  };
2009
- //# sourceMappingURL=chunk-NFZT5TWR.js.map
2199
+ //# sourceMappingURL=chunk-BMCERPQX.js.map