@12-apps/marketplace 1.7.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 (67) 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 +32 -3
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-DOjTak1H.d.ts → adapter-CYJzu1c9.d.ts} +45 -1
  7. package/dist/{chunk-YVUZHXUF.js → chunk-6N2HEV3U.js} +4 -4
  8. package/dist/chunk-6N2HEV3U.js.map +1 -0
  9. package/dist/{chunk-SJUKBCVO.js → chunk-BMCERPQX.js} +198 -12
  10. package/dist/chunk-BMCERPQX.js.map +1 -0
  11. package/dist/{chunk-L3DCOZUU.js → chunk-HEXLCTOG.js} +1 -1
  12. package/dist/chunk-HEXLCTOG.js.map +1 -0
  13. package/dist/{chunk-UYFYGGCS.js → chunk-NP4EYKPO.js} +3 -1
  14. package/dist/chunk-NP4EYKPO.js.map +1 -0
  15. package/dist/{engine-DG1fg43Y.d.ts → engine-wmW-VuBL.d.ts} +107 -4
  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 +29 -3
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +104 -7
  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 +20 -3
  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 +45 -1
  35. package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
  36. package/src/99food/index.ts +6 -0
  37. package/src/99food/normalize.ts +7 -1
  38. package/src/99food/outbound.ts +55 -0
  39. package/src/core/adapter.ts +41 -1
  40. package/src/core/bulk.ts +1 -1
  41. package/src/core/engine.ts +9 -0
  42. package/src/core/ingest.ts +6 -0
  43. package/src/core/integration.ts +17 -0
  44. package/src/core/lifecycle-port.ts +16 -0
  45. package/src/core/lifecycle.ts +133 -0
  46. package/src/core/outbound-queue.ts +24 -4
  47. package/src/core/outbound-sweep.ts +49 -5
  48. package/src/core/outbound.ts +11 -0
  49. package/src/core/pipeline.ts +22 -2
  50. package/src/core/ports.ts +39 -3
  51. package/src/core/status-inform.ts +51 -0
  52. package/src/core/status-job.ts +207 -0
  53. package/src/core/status-store.ts +85 -0
  54. package/src/core/types.ts +14 -0
  55. package/src/ifood/index.ts +7 -1
  56. package/src/ifood/normalize.ts +17 -0
  57. package/src/ifood/outbound.ts +35 -0
  58. package/src/index.ts +6 -0
  59. package/src/rappi/index.ts +6 -1
  60. package/src/rappi/normalize.ts +6 -0
  61. package/src/rappi/outbound.ts +31 -2
  62. package/src/server/mcp.ts +2 -0
  63. package/src/server/webhook.ts +3 -1
  64. package/dist/chunk-L3DCOZUU.js.map +0 -1
  65. package/dist/chunk-SJUKBCVO.js.map +0 -1
  66. package/dist/chunk-UYFYGGCS.js.map +0 -1
  67. package/dist/chunk-YVUZHXUF.js.map +0 -1
@@ -7,6 +7,7 @@ import {
7
7
  type MarketplaceHttpResponse,
8
8
  type OutboundOrderRef,
9
9
  type OutboundResult,
10
+ type StatusFacts,
10
11
  } from "../core/adapter";
11
12
  import { RAPPI_PROVIDER } from "./normalize";
12
13
 
@@ -110,12 +111,12 @@ export async function bearer(
110
111
  async function putOrder(
111
112
  ctx: AdapterCallContext,
112
113
  hosts: RappiHosts,
113
- request: { externalOrderId: string; action: string; body?: unknown },
114
+ request: { externalOrderId: string; action: string; body?: unknown; method?: "PUT" | "POST" },
114
115
  ): Promise<MarketplaceHttpResponse | Exclude<OutboundResult, { kind: "accepted" }>> {
115
116
  const auth = await bearer(ctx, hosts);
116
117
  if (!("token" in auth)) return auth;
117
118
  const response = await ctx.http({
118
- method: "PUT",
119
+ method: request.method ?? "PUT",
119
120
  url: `${trimmed(hosts.api[ctx.environment])}/orders/${encodeURIComponent(request.externalOrderId)}/${request.action}`,
120
121
  headers: {
121
122
  "x-authorization": `Bearer ${auth.token}`,
@@ -181,3 +182,31 @@ export function rappiReject(
181
182
  return "kind" in response ? response : outboundResultOf(response);
182
183
  });
183
184
  }
185
+
186
+ /**
187
+ * What Rappi is told per step (FUT-4653). READY only: `POST {api}/orders/{id}/ready-for-pickup`
188
+ * (Rappi's dev portal, https://dev-portal.rappi.com/, "Managing User Orders",
189
+ * read 2026-11-25), which the portal says is for a store on MANUAL
190
+ * notification (Rappi recommends Automatic): any other store's call may be
191
+ * refused, which ends FAILED and logged, never retried. ESTIMATED: the verb is
192
+ * POST in the portal while the other order calls here are PUT. No endpoint
193
+ * was found for DISPATCHED (Rappi's own couriers carry the order) nor for
194
+ * HANDED_OVER, so those are unsupported.
195
+ */
196
+ export function rappiStatusSupported(facts: StatusFacts): boolean {
197
+ return facts.step === "READY";
198
+ }
199
+
200
+ /** Tell Rappi a step happened. `unsupported` for every step but READY. */
201
+ export function rappiInformStatus(
202
+ ctx: AdapterCallContext,
203
+ hosts: RappiHosts,
204
+ order: OutboundOrderRef,
205
+ facts: StatusFacts,
206
+ ): Promise<OutboundResult | { kind: "unsupported" }> {
207
+ if (facts.step !== "READY") return Promise.resolve({ kind: "unsupported" });
208
+ return answered(async () => {
209
+ const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: "ready-for-pickup", method: "POST" });
210
+ return "kind" in response ? response : outboundResultOf(response);
211
+ });
212
+ }
package/src/server/mcp.ts CHANGED
@@ -72,6 +72,7 @@ const integrationUpsertInput = z.strictObject({
72
72
  environment: environmentSchema.optional(),
73
73
  externalMerchantId: z.string().trim().min(1).nullable().optional(),
74
74
  autoAccept: z.boolean().optional(),
75
+ followStatus: z.boolean().optional(),
75
76
  // Below a minute nothing human can answer in time; above an hour the
76
77
  // deadline has stopped describing anything a marketplace would wait for.
77
78
  ackSlaSeconds: z.number().int().min(60).max(3600).optional(),
@@ -186,6 +187,7 @@ const integrationSchema = z.object({
186
187
  status: z.enum(["UNVERIFIED", "VERIFIED", "FAILED"]),
187
188
  externalMerchantId: z.string().nullable(),
188
189
  autoAccept: z.boolean(),
190
+ followStatus: z.boolean(),
189
191
  ackSlaSeconds: z.number().int(),
190
192
  connected: z.boolean(),
191
193
  lastEventAt: z.string().nullable(),
@@ -99,7 +99,9 @@ async function handleWebhook(config: MarketplaceApiConfig, request: WireRequest<
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
103
+ ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds, followStatus: target.followStatus }
104
+ : null,
103
105
  });
104
106
  if (outcome.kind === "failed") {
105
107
  return { status: 500, body: { received: true, error: outcome.reason } };
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { MarketplaceCatalogue } from \"./catalogue-port\";\nimport type { CatalogueReader } from \"./catalogue-read-port\";\nimport type { MarketplaceAvailability } from \"./pause-port\";\nimport type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from \"./types\";\n\n/**\n * The adapter port: everything one marketplace is, behind one shape.\n *\n * The owner's rule, which this file exists to make true: \"the integration\n * engine must be the same for all integrations: iFood, Rappi, 99. Only an\n * adapter is made for each one, to connect to the base engine.\"\n *\n * A marketplace differs from the next in five ways that matter to a store:\n * how its deliveries look and are signed (`normalize`, `readSignature`,\n * `verifySignature`), what it lets a store answer through its API (`confirm`,\n * `requestCancellation`), which reasons a refusal may carry\n * (`cancellationReasons`), and where a person goes when the API cannot do it\n * (`appLink`). Everything else — the inbox, the clock, the SKU map, the\n * outbound bookkeeping and its retries — is the engine's and does not change\n * with the marketplace.\n *\n * What a marketplace CAN do is stated by its adapter as\n * {@link MarketplaceCapabilities} and read by the engine and the host. It is\n * never inferred from the provider's id: a branch on the id outside an adapter\n * would make the next marketplace a code change instead of an adapter.\n *\n * The HTTP client is a host port ({@link MarketplaceHttp}), handed to every\n * outbound call. An adapter never reaches the network on its own, so tests\n * answer the seam and nothing else, and the host owns the timeout, the proxy\n * and the CA.\n */\n\n/** A marketplace's credentials, as the merchant supplies them. Sealed at rest. */\nexport interface MarketplaceCredentials {\n clientId: string;\n clientSecret: string;\n /**\n * The shared secret a delivery's signature is verified against. Separate\n * from the OAuth pair: a merchant rotating their webhook secret has not\n * re-onboarded.\n */\n webhookSecret: string | null;\n}\n\n/** What the host's HTTP client takes. */\nexport interface MarketplaceHttpRequest {\n /**\n * `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it.\n * `DELETE` since FUT-4851: iFood removes an interruption with it.\n */\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: string;\n}\n\n/** What the host's HTTP client answers: any status, never a throw for a 4xx or 5xx. */\nexport interface MarketplaceHttpResponse {\n status: number;\n body: string;\n}\n\n/** The host's HTTP client. It throws only when no answer arrived (a timeout, a network error). */\nexport type MarketplaceHttp = (request: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>;\n\n/** What a marketplace can do, stated by its adapter. */\nexport interface MarketplaceCapabilities {\n /** Accepting is answered through the API. */\n apiConfirm: boolean;\n /** A cancellation can be requested through the API at all. */\n apiCancel: boolean;\n /** …and still once the order was accepted. */\n cancelAfterAccept: boolean;\n /** The cancellation's outcome arrives later as an event rather than in the answer. */\n asyncCancellationOutcome: boolean;\n /** `appLink` names this order, rather than only the marketplace's portal. */\n perOrderAppLink: boolean;\n /** Confirming states a preparation time. */\n confirmTakesPreparationTime: boolean;\n /**\n * OPTIONAL. How long the marketplace takes, at most, to answer a store's\n * cancellation request, in milliseconds: past it the outbound sweep fails\n * the request as TIMEOUT. Absent: only the 24-hour give-up applies.\n */\n cancellationAnswerWindowMs?: number;\n}\n\n/** One reason a store may give for refusing or cancelling an order. */\nexport interface CancellationReason {\n /** The marketplace's own code, sent verbatim. */\n code: string;\n /** The label the host was configured with for this code (a named pack). */\n label: string;\n /** This reason means \"an item is unavailable\": the host preselects it when stock is short. */\n itemUnavailable: boolean;\n /** The marketplace requires the offending SKUs with this reason. */\n needsItems: boolean;\n}\n\n/** The order an outbound call is about, as the engine knows it. */\nexport interface OutboundOrderRef {\n externalOrderId: string;\n externalDisplayId: string | null;\n /** The host's own id for the order. */\n hostOrderCode: string;\n /** When the engine recorded the order. */\n placedAt: Date;\n}\n\n/** A per-engine token cache an adapter reads and fills. Never persisted. */\nexport type AdapterTokenCache = Map<string, { token: string; expiresAt: number }>;\n\n/** What one outbound call is handed. */\nexport interface AdapterCallContext {\n http: MarketplaceHttp;\n credentials: MarketplaceCredentials;\n environment: \"SANDBOX\" | \"PRODUCTION\";\n /** Written to no row, log or audit entry: memory only, per process. */\n tokens: AdapterTokenCache;\n now: Date;\n}\n\n/** One outbound call's answer, in the three shapes the engine acts on. */\nexport type OutboundResult =\n /** 2xx. For a marketplace whose outcome is asynchronous, \"the request was taken\". */\n | { kind: \"accepted\" }\n /**\n * A final 4xx (not 408/425/429): never retried. `own` marks a refusal that\n * is not the marketplace's judgement of the order: our credentials were not\n * accepted, or our request was malformed. A cancellation request that ends\n * so fails as UNREACHABLE, not REFUSED.\n */\n | { kind: \"refused\"; status: number; message: string; own?: true }\n /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */\n | { kind: \"retry\"; reason: string };\n\n/**\n * One order-body fetch's answer: the order, normalized, or the same refusal and\n * retry shapes an outbound call answers with (a 404 for an expired order is a\n * refusal; a 5xx, a timeout or a 429 is a retry).\n */\nexport type FetchOrderResult =\n | { kind: \"order\"; order: NormalizedMarketplaceOrder }\n | Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** What a cancellation request carries. */\nexport interface CancellationRequestInput {\n reason: CancellationReason;\n /** Free text from the store; empty means \"the reason's own label\". */\n text: string;\n mode: \"MANUAL\" | \"AUTO\";\n offendingSkus: readonly string[];\n}\n\n/** One marketplace, in and out. */\nexport interface MarketplaceAdapter {\n readonly provider: MarketplaceProvider;\n readonly capabilities: MarketplaceCapabilities;\n /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */\n normalize(payload: unknown): NormalizedEvent | null;\n /** Which header carries this marketplace's signature, read off the request. */\n readSignature(header: (name: string) => string | null): string | null;\n /** Is this delivery's signature the one this store's secret would produce? */\n verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;\n /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */\n cancellationReasons(): readonly CancellationReason[];\n /** Tell the marketplace the store accepted the order. */\n confirm(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n ): Promise<OutboundResult>;\n /** Ask the marketplace to cancel the order, with one of its own reasons. */\n requestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n ): Promise<OutboundResult>;\n /**\n * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a\n * marketplace whose events carry no order body). Called only from the\n * `marketplace.fetch-order` job. An adapter whose events always carry the\n * order (iFood) leaves it out.\n */\n fetchOrder?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<FetchOrderResult>;\n /**\n * OPTIONAL. Publishing the store's products to this marketplace's catalogue\n * (FUT-4768): `push` (the adapter writes each item) or `pull` (the\n * marketplace reads a menu document the host serves). Absent: the\n * marketplace cannot be published to, and the host says so.\n */\n readonly catalogue?: MarketplaceCatalogue;\n /**\n * OPTIONAL. Reading the menu the store already keeps on this marketplace,\n * through its own connection, for the host to import (FUT-951). Absent: the\n * menu cannot be read through an API, and the host says so.\n */\n readonly catalogueReader?: CatalogueReader;\n /**\n * OPTIONAL. Closing the store on this marketplace for a while, and opening\n * it again (FUT-4851). Absent: the marketplace cannot be paused through an\n * API, and the host says so.\n */\n readonly availability?: MarketplaceAvailability;\n /** Where \"open it on the marketplace\" goes: the order when `perOrderAppLink`, else the portal. Always https. */\n appLink(order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string;\n}\n\n/**\n * The 4xx statuses that are NOT a refusal: a request timeout (408), \"too\n * early\" (425) and a rate limit (429) say \"ask again later\" by HTTP's own\n * semantics, and a marketplace rate-limits its merchant API.\n */\nconst TRANSIENT_CLIENT_STATUSES = new Set([408, 425, 429]);\n\n/**\n * Read one HTTP answer the way the engine acts on it. Shared by every adapter\n * whose API speaks plain status codes, so the rule is one rule rather than one\n * per marketplace: 2xx accepted; a 4xx other than 408/425/429 refused and\n * final; everything else (408, 425, 429, 5xx, anything unexpected) retried.\n */\nexport function outboundResultOf(response: MarketplaceHttpResponse): OutboundResult {\n if (response.status >= 200 && response.status < 300) return { kind: \"accepted\" };\n const message = response.body.slice(0, 300);\n const refusal = response.status >= 400 && response.status < 500 && !TRANSIENT_CLIENT_STATUSES.has(response.status);\n if (refusal) return { kind: \"refused\", status: response.status, message };\n return { kind: \"retry\", reason: `status ${response.status}: ${message}` };\n}\n\n/**\n * {@link outboundResultOf} for a token grant: a final 4xx there says our\n * credentials were not accepted, never a judgement of any order, so it is an\n * `own` refusal.\n */\nexport function tokenGrantResultOf(response: MarketplaceHttpResponse): OutboundResult {\n const result = outboundResultOf(response);\n return result.kind === \"refused\" ? { ...result, own: true } : result;\n}\n\n/** A call that never got an answer is a retry, with the reason a log can read. */\nexport async function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n"],"mappings":";;;;;AAqNA,IAAM,4BAA4B,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAQlD,SAAS,iBAAiB,UAAmD;AAClF,MAAI,SAAS,UAAU,OAAO,SAAS,SAAS,IAAK,QAAO,EAAE,MAAM,WAAW;AAC/E,QAAM,UAAU,SAAS,KAAK,MAAM,GAAG,GAAG;AAC1C,QAAM,UAAU,SAAS,UAAU,OAAO,SAAS,SAAS,OAAO,CAAC,0BAA0B,IAAI,SAAS,MAAM;AACjH,MAAI,QAAS,QAAO,EAAE,MAAM,WAAW,QAAQ,SAAS,QAAQ,QAAQ;AACxE,SAAO,EAAE,MAAM,SAAS,QAAQ,UAAU,SAAS,MAAM,KAAK,OAAO,GAAG;AAC1E;AANgB;AAaT,SAAS,mBAAmB,UAAmD;AACpF,QAAM,SAAS,iBAAiB,QAAQ;AACxC,SAAO,OAAO,SAAS,YAAY,EAAE,GAAG,QAAQ,KAAK,KAAK,IAAI;AAChE;AAHgB;AAMhB,eAAsB,SAAS,MAA8D;AAC3F,MAAI;AACF,WAAO,MAAM,KAAK;AAAA,EACpB,SAAS,OAAO;AACd,WAAO,EAAE,MAAM,SAAS,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE;AAAA,EACzF;AACF;AANsB;","names":[]}