@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
@@ -0,0 +1,257 @@
1
+ import {
2
+ answered,
3
+ outboundResultOf,
4
+ type AdapterCallContext,
5
+ type MarketplaceHttpRequest,
6
+ type MarketplaceHttpResponse,
7
+ type OutboundResult,
8
+ } from "../core/adapter";
9
+ import type { MarketplaceAvailability, StorePauseRef, StorePauseRequest, StorePauseResult } from "../core/pause-port";
10
+ import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
11
+
12
+ /**
13
+ * iFood's half of the store pause (FUT-4851): the Merchant API's
14
+ * INTERRUPTIONS, a closure with its own id, a start and an end, that does not
15
+ * touch the store's opening hours.
16
+ *
17
+ * - List: `GET /merchant/v1.0/merchants/{merchantId}/interruptions`
18
+ * (active and future interruptions).
19
+ * - Create: `POST …/interruptions` with `{ id, description, start, end }`,
20
+ * 201 with the interruption.
21
+ * - Delete: `DELETE …/interruptions/{interruptionId}`, 204.
22
+ *
23
+ * iFood's developer portal refuses our reader (403), so the paths, verbs and
24
+ * the body's `description`/`start`/`end` come from two public third-party
25
+ * clients of the API (README, "Pausing a store"): ESTIMATED until the
26
+ * homologation run. Also ESTIMATED: that iFood takes the client's own `id`.
27
+ * It is sent, but the adapter does not rely on it: every create is preceded
28
+ * by a list, and an interruption is ours when it carries our id OR, where
29
+ * iFood assigned its own, exactly the end and the description the create
30
+ * sent, so a retry after a lost answer never makes a second one and a resume
31
+ * by key deletes the one that landed. An interruption the owner made by hand
32
+ * is neither. ESTIMATED too: that there is no call to move an interruption's
33
+ * end (so no `extend`: the engine creates the new one, then deletes the old);
34
+ * that iFood ACCEPTS the two overlapping for that moment (if it refuses an
35
+ * overlap, the renewal is FAILED with iFood's words and the old interruption
36
+ * still holds to its own end); and how iFood reads a
37
+ * time: one client says the offset is discarded and the time read as the
38
+ * store's own clock, so the time goes out as the store's wall clock WITH its
39
+ * offset, which reads the same either way. A 404 on delete is "already gone".
40
+ */
41
+
42
+ const interruptionsUrl = (merchantId: string): string =>
43
+ `${IFOOD_API}/merchant/v1.0/merchants/${encodeURIComponent(merchantId)}/interruptions`;
44
+
45
+ type Settled = Exclude<OutboundResult, { kind: "accepted" }>;
46
+
47
+ /** One authenticated call: the raw answer, or the result that ends it. */
48
+ async function call(
49
+ ctx: AdapterCallContext,
50
+ request: Omit<MarketplaceHttpRequest, "headers"> & { json?: unknown },
51
+ ): Promise<MarketplaceHttpResponse | Settled> {
52
+ const auth = await bearer(ctx);
53
+ if (!("token" in auth)) return auth.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : auth;
54
+ const response = await ctx.http({
55
+ method: request.method,
56
+ url: request.url,
57
+ headers: {
58
+ Authorization: `Bearer ${auth.token}`,
59
+ ...(request.json === undefined ? {} : { "Content-Type": "application/json" }),
60
+ },
61
+ ...(request.json === undefined ? {} : { body: JSON.stringify(request.json) }),
62
+ });
63
+ // A 401 is a token that went stale under us: forget it, and the retry fetches another.
64
+ if (response.status !== 401) return response;
65
+ ctx.tokens.delete(ifoodTokenKey(ctx));
66
+ return { kind: "retry", reason: "iFood refused the token" };
67
+ }
68
+
69
+ const settled = (value: MarketplaceHttpResponse | Settled): value is Settled => "kind" in value;
70
+
71
+ /** The answer as anything but 2xx, read the engine's way. */
72
+ function notOk(response: MarketplaceHttpResponse): Settled | null {
73
+ const result = outboundResultOf(response);
74
+ return result.kind === "accepted" ? null : result;
75
+ }
76
+
77
+ /** One interruption as the list answers it, read defensively. */
78
+ interface Interruption {
79
+ id: string;
80
+ end: string | null;
81
+ description: string | null;
82
+ }
83
+
84
+ /** The interruptions on the merchant, or the result that ends the call. */
85
+ async function listInterruptions(ctx: AdapterCallContext, merchantId: string): Promise<Interruption[] | Settled> {
86
+ const response = await call(ctx, { method: "GET", url: interruptionsUrl(merchantId) });
87
+ if (settled(response)) return response;
88
+ const failure = notOk(response);
89
+ if (failure) return failure;
90
+ try {
91
+ const parsed = JSON.parse(response.body === "" ? "[]" : response.body) as unknown;
92
+ if (!Array.isArray(parsed)) return [];
93
+ return parsed.flatMap((entry: unknown) => {
94
+ const value = (entry ?? {}) as { id?: unknown; end?: unknown; description?: unknown };
95
+ if (typeof value.id !== "string") return [];
96
+ return [
97
+ {
98
+ id: value.id,
99
+ end: typeof value.end === "string" ? value.end : null,
100
+ description: typeof value.description === "string" ? value.description : null,
101
+ },
102
+ ];
103
+ });
104
+ } catch {
105
+ return { kind: "retry", reason: "iFood answered the interruption list with something that is not JSON" };
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Whether iFood's `end` is the instant the create sent. An `end` that states
111
+ * its zone (`Z` or an offset) is compared as an instant, and only as one: an
112
+ * owner's interruption at another instant is never claimed because its digits
113
+ * look like ours. Only an `end` with no zone (iFood echoing the store's own
114
+ * clock) is compared as the store's wall clock.
115
+ */
116
+ function sameEnd(end: string, until: Date, timeZone: string): boolean {
117
+ const sent = ifoodLocalTime(until, timeZone);
118
+ if (end === sent) return true;
119
+ if (/(?:[zZ]|[+-]\d{2}:?\d{2})$/u.test(end)) {
120
+ const parsed = Date.parse(end);
121
+ return !Number.isNaN(parsed) && Math.floor(parsed / 1000) === Math.floor(until.getTime() / 1000);
122
+ }
123
+ return end.slice(0, 19) === sent.slice(0, 19);
124
+ }
125
+
126
+ /**
127
+ * The interruption the create under `key` made: by our id, or by the end and
128
+ * description it carried, never one the engine already holds (`keep`).
129
+ */
130
+ function ours(
131
+ list: readonly Interruption[],
132
+ key: string,
133
+ sent: { until: Date; reason: string; timeZone: string } | null,
134
+ keep: readonly string[] = [],
135
+ ): Interruption | undefined {
136
+ const candidates = list.filter((entry) => !keep.includes(entry.id));
137
+ const byKey = candidates.find((entry) => entry.id === key);
138
+ if (byKey || !sent) return byKey;
139
+ return candidates.find(
140
+ (entry) => entry.description === sent.reason && entry.end !== null && sameEnd(entry.end, sent.until, sent.timeZone),
141
+ );
142
+ }
143
+
144
+ interface WallClock {
145
+ year: number;
146
+ month: number;
147
+ day: number;
148
+ hour: number;
149
+ minute: number;
150
+ second: number;
151
+ }
152
+
153
+ /** The wall clock of `date` in `timeZone`. */
154
+ function wallClock(date: Date, timeZone: string): WallClock {
155
+ const format = new Intl.DateTimeFormat("en-US", {
156
+ timeZone,
157
+ hourCycle: "h23",
158
+ year: "numeric",
159
+ month: "2-digit",
160
+ day: "2-digit",
161
+ hour: "2-digit",
162
+ minute: "2-digit",
163
+ second: "2-digit",
164
+ });
165
+ const clock: WallClock = { year: 0, month: 1, day: 1, hour: 0, minute: 0, second: 0 };
166
+ for (const part of format.formatToParts(date)) {
167
+ if (part.type in clock) clock[part.type as keyof WallClock] = Number(part.value);
168
+ }
169
+ return clock;
170
+ }
171
+
172
+ const pad = (value: number, width = 2): string => String(value).padStart(width, "0");
173
+
174
+ /**
175
+ * `date` as the store's wall clock with its offset: `2026-11-13T15:30:00-03:00`.
176
+ * Read the same whether iFood honours the offset or reads the store's clock.
177
+ */
178
+ export function ifoodLocalTime(date: Date, timeZone: string): string {
179
+ const local = wallClock(date, timeZone);
180
+ const asUtc = Date.UTC(local.year, local.month - 1, local.day, local.hour, local.minute, local.second);
181
+ const offset = Math.round((asUtc - Math.floor(date.getTime() / 1000) * 1000) / 60_000);
182
+ const abs = Math.abs(offset);
183
+ return (
184
+ `${pad(local.year, 4)}-${pad(local.month)}-${pad(local.day)}` +
185
+ `T${pad(local.hour)}:${pad(local.minute)}:${pad(local.second)}` +
186
+ `${offset < 0 ? "-" : "+"}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`
187
+ );
188
+ }
189
+
190
+ /** The created interruption's id: iFood's answer, else the one the engine sent. */
191
+ function createdId(body: string, sent: string): string {
192
+ try {
193
+ const id = (JSON.parse(body) as { id?: unknown }).id;
194
+ return typeof id === "string" && id !== "" ? id : sent;
195
+ } catch {
196
+ return sent;
197
+ }
198
+ }
199
+
200
+ /** Close the store until `request.until`: find one a lost answer created under the key, else create it. */
201
+ export function ifoodPause(ctx: AdapterCallContext, request: StorePauseRequest): Promise<StorePauseResult> {
202
+ return answeredPause(async () => {
203
+ const list = await listInterruptions(ctx, request.merchantId);
204
+ if (!Array.isArray(list)) return list;
205
+ const landed = ours(list, request.key, { until: request.until, reason: request.reason, timeZone: request.timeZone }, request.keep);
206
+ if (landed) return { kind: "paused", externalId: landed.id, until: request.until };
207
+ const response = await call(ctx, {
208
+ method: "POST",
209
+ url: interruptionsUrl(request.merchantId),
210
+ json: {
211
+ id: request.key,
212
+ description: request.reason,
213
+ start: ifoodLocalTime(ctx.now, request.timeZone),
214
+ end: ifoodLocalTime(request.until, request.timeZone),
215
+ },
216
+ });
217
+ if (settled(response)) return response;
218
+ const failure = notOk(response);
219
+ if (failure) return failure;
220
+ return { kind: "paused", externalId: createdId(response.body, request.key), until: request.until };
221
+ });
222
+ }
223
+
224
+ /** Delete THIS interruption: by its id, or the one a lost answer created under the key (by id, or by its end and description). */
225
+ export function ifoodResume(ctx: AdapterCallContext, ref: StorePauseRef): Promise<OutboundResult> {
226
+ return answered(async () => {
227
+ let id = ref.externalId;
228
+ if (id === null && ref.key !== null) {
229
+ const list = await listInterruptions(ctx, ref.merchantId);
230
+ if (!Array.isArray(list)) return list;
231
+ id = ours(list, ref.key, ref.sent, ref.keep)?.id ?? null;
232
+ }
233
+ // Nothing of ours stands: there is nothing to delete.
234
+ if (id === null) return { kind: "accepted" };
235
+ const response = await call(ctx, { method: "DELETE", url: `${interruptionsUrl(ref.merchantId)}/${encodeURIComponent(id)}` });
236
+ if (settled(response)) return response;
237
+ // Already gone: it ended, or a person removed it.
238
+ if (response.status === 404) return { kind: "accepted" };
239
+ return outboundResultOf(response);
240
+ });
241
+ }
242
+
243
+ /** {@link answered} for a pause: a call that never got an answer is a retry. */
244
+ async function answeredPause(run: () => Promise<StorePauseResult>): Promise<StorePauseResult> {
245
+ try {
246
+ return await run();
247
+ } catch (error) {
248
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
249
+ }
250
+ }
251
+
252
+ /** iFood's availability capability: interruptions, no extend. */
253
+ export const IFOOD_AVAILABILITY: MarketplaceAvailability = {
254
+ kind: "interruption",
255
+ pause: ifoodPause,
256
+ resume: ifoodResume,
257
+ };
package/src/index.ts CHANGED
@@ -162,6 +162,21 @@ export type {
162
162
  PullCatalogue,
163
163
  PushCatalogue,
164
164
  } from "./core/catalogue-port";
165
+ export { centsFromMajor } from "./core/catalogue-read-port";
166
+ export type {
167
+ CatalogueReadContext,
168
+ CatalogueReader,
169
+ CatalogueReadNotice,
170
+ CatalogueReadRefusalCode,
171
+ CatalogueReadResult,
172
+ CatalogueReadWarning,
173
+ CatalogueReadWarningCode,
174
+ CatalogueSnapshot,
175
+ CatalogueSnapshotCategory,
176
+ CatalogueSnapshotItem,
177
+ CatalogueSnapshotOption,
178
+ CatalogueSnapshotOptionGroup,
179
+ } from "./core/catalogue-read-port";
165
180
  export type {
166
181
  CatalogueFailedAction,
167
182
  CatalogueFailureCode,
@@ -169,3 +184,27 @@ export type {
169
184
  CatalogueStatus,
170
185
  } from "./core/catalogue-store";
171
186
  export { CATALOGUE_GIVE_UP_MS, CATALOGUE_STALE_MS } from "./core/catalogue-sweep";
187
+ export type {
188
+ MarketplaceAvailability,
189
+ StorePauseRef,
190
+ StorePauseRequest,
191
+ StorePauseResult,
192
+ } from "./core/pause-port";
193
+ export type {
194
+ PauseOutcome,
195
+ PauseStoreInput,
196
+ PauseStoreResult,
197
+ ResumeOutcome,
198
+ StoreAvailabilityView,
199
+ } from "./core/pause";
200
+ export { AvailabilityRetryError, type AvailabilityOutcome } from "./core/pause-job";
201
+ export {
202
+ MARKETPLACE_AVAILABILITY_JOB,
203
+ STORE_PAUSE_LEASE_MS,
204
+ availabilityDedupeKey,
205
+ type AvailabilityJobPayload,
206
+ type StorePauseFailureCode,
207
+ type StorePauseState,
208
+ type StorePauseWanted,
209
+ } from "./core/pause-store";
210
+ export type { AvailabilitySweepResult } from "./core/pause-sweep";
@@ -8,6 +8,7 @@ import {
8
8
  type RappiAmountUnit,
9
9
  } from "./normalize";
10
10
  import { rappiReject, rappiTake, type RappiBaseUrls } from "./outbound";
11
+ import { rappiAvailability } from "./pause";
11
12
 
12
13
  /**
13
14
  * `@12-apps/marketplace/rappi` — Rappi, as one adapter on the engine.
@@ -86,6 +87,14 @@ export interface RappiAdapterConfig {
86
87
  portalUrl: string;
87
88
  /** How Rappi states money for this host's country (see {@link RappiAmountUnit}). Required: ESTIMATED for Brazil. */
88
89
  amountUnit: RappiAmountUnit;
90
+ /**
91
+ * OPTIONAL, off by default. Offer the store pause (FUT-4851) through Rappi's
92
+ * store on/off switch. A switch has no id, so the engine cannot tell its own
93
+ * closure from one the owner made by hand meanwhile: a store the owner also
94
+ * turned off on Rappi during the kitchen's pause is turned on with it. A
95
+ * host turns this on knowing that.
96
+ */
97
+ pauseByStoreSwitch?: boolean;
89
98
  }
90
99
 
91
100
  function assertHttps(name: string, url: string): void {
@@ -147,6 +156,7 @@ export function createRappiAdapter(config: RappiAdapterConfig): MarketplaceAdapt
147
156
  confirm: (ctx, order, input) => rappiTake(ctx, hosts, order, input),
148
157
  requestCancellation: (ctx, order, input) => rappiReject(ctx, hosts, order, input),
149
158
  appLink: () => config.portalUrl,
159
+ ...(config.pauseByStoreSwitch ? { availability: rappiAvailability(hosts) } : {}),
150
160
  };
151
161
  }
152
162
 
@@ -159,3 +169,4 @@ export {
159
169
  type RappiNormalizeOptions,
160
170
  } from "./normalize";
161
171
  export type { RappiBaseUrls, RappiHosts } from "./outbound";
172
+ export { rappiAvailability, rappiSetStoreEnabled } from "./pause";
@@ -57,7 +57,7 @@ const TOKEN_MARGIN_MS = 60_000;
57
57
  const DEFAULT_TOKEN_SECONDS = 7 * 24 * 60 * 60;
58
58
 
59
59
  /** A base URL with its trailing slashes cut, by a loop: a `/\/+$/` regex backtracks polynomially on many slashes. */
60
- function trimmed(base: string): string {
60
+ export function trimmed(base: string): string {
61
61
  let end = base.length;
62
62
  while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;
63
63
  return base.slice(0, end);
@@ -83,7 +83,7 @@ function tokenOf(body: string): { token: string; expiresInSeconds: number } | nu
83
83
  * (the M2M client credentials). Keyed by environment and client id; memory
84
84
  * only, written to no row or log.
85
85
  */
86
- async function bearer(
86
+ export async function bearer(
87
87
  ctx: AdapterCallContext,
88
88
  hosts: RappiHosts,
89
89
  ): Promise<{ token: string } | Exclude<OutboundResult, { kind: "accepted" }>> {
@@ -0,0 +1,98 @@
1
+ import {
2
+ answered,
3
+ outboundResultOf,
4
+ type AdapterCallContext,
5
+ type OutboundResult,
6
+ } from "../core/adapter";
7
+ import type { MarketplaceAvailability, StorePauseRequest, StorePauseResult } from "../core/pause-port";
8
+ import { RAPPI_PROVIDER } from "./normalize";
9
+ import { bearer, trimmed, type RappiHosts } from "./outbound";
10
+
11
+ /**
12
+ * Rappi's half of the store pause (FUT-4851): a store-wide SWITCH, from
13
+ * Rappi's public developer portal (dev-portal.rappi.com, api-reference
14
+ * "availability", read 2026-11-13):
15
+ *
16
+ * `PUT https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api/availability/stores/enable`,
17
+ * synchronous, with `{ stores: [{ store_id, is_enabled }] }`; 200 with a
18
+ * `results` array (`store_id`, `is_enabled`, `operation_result`,
19
+ * `operation_result_type`, `operation_result_message`, `suspended_reason`, …),
20
+ * 400, 403 "not allowed to update those stores", 422 too many stores, 502.
21
+ *
22
+ * A switch has no id and no end: the engine turns a store on only when its
23
+ * own record says it turned it off, and turns it on by itself once the
24
+ * kitchen's `until` has passed unrenewed. What it cannot tell apart is a store
25
+ * the owner ALSO closed by hand during the kitchen's pause, which is why the
26
+ * adapter offers this only when the host opts in (`pauseByStoreSwitch`).
27
+ *
28
+ * ESTIMATED: which id `store_id` is (the portal says "the one from your
29
+ * system" for this call; the engine sends the connection's merchant id, the
30
+ * store id Rappi's own events carry), and how a per-store failure reads in
31
+ * `results` (an `operation_result` of `false`, or a `operation_result_type`
32
+ * naming an error, is taken as a refusal with `operation_result_message`).
33
+ */
34
+
35
+ interface RappiStoreResult {
36
+ store_id?: unknown;
37
+ operation_result?: unknown;
38
+ operation_result_type?: unknown;
39
+ operation_result_message?: unknown;
40
+ }
41
+
42
+ /** This store's entry in the answer's `results`, judged; null when the answer names it as done. */
43
+ function refusalIn(body: string, storeId: string): Exclude<OutboundResult, { kind: "accepted" }> | null {
44
+ let results: RappiStoreResult[];
45
+ try {
46
+ const parsed = JSON.parse(body === "" ? "{}" : body) as { results?: unknown };
47
+ results = Array.isArray(parsed.results) ? (parsed.results as RappiStoreResult[]) : [];
48
+ } catch {
49
+ return null;
50
+ }
51
+ const entry = results.find((result) => String(result.store_id) === storeId);
52
+ if (!entry) return null;
53
+ const type = typeof entry.operation_result_type === "string" ? entry.operation_result_type : "";
54
+ const failed = entry.operation_result === false || /error|fail/iu.test(type);
55
+ if (!failed) return null;
56
+ const message = typeof entry.operation_result_message === "string" ? entry.operation_result_message : type;
57
+ return { kind: "refused", status: 200, message: message.slice(0, 300) };
58
+ }
59
+
60
+ const tokenKey = (ctx: AdapterCallContext): string => `${RAPPI_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;
61
+
62
+ /** Turn the store on or off; the answer judged for THIS store. */
63
+ export function rappiSetStoreEnabled(
64
+ ctx: AdapterCallContext,
65
+ hosts: RappiHosts,
66
+ storeId: string,
67
+ enabled: boolean,
68
+ ): Promise<OutboundResult> {
69
+ return answered(async () => {
70
+ const auth = await bearer(ctx, hosts);
71
+ if (!("token" in auth)) return auth;
72
+ const response = await ctx.http({
73
+ method: "PUT",
74
+ url: `${trimmed(hosts.api[ctx.environment])}/availability/stores/enable`,
75
+ headers: { "x-authorization": `Bearer ${auth.token}`, "Content-Type": "application/json" },
76
+ body: JSON.stringify({ stores: [{ store_id: storeId, is_enabled: enabled }] }),
77
+ });
78
+ if (response.status === 401) {
79
+ ctx.tokens.delete(tokenKey(ctx));
80
+ return { kind: "retry", reason: "Rappi refused the token" };
81
+ }
82
+ const result = outboundResultOf(response);
83
+ if (result.kind !== "accepted") return result;
84
+ return refusalIn(response.body, storeId) ?? result;
85
+ });
86
+ }
87
+
88
+ /** Rappi's availability capability: a switch, offered only when the host opts in. */
89
+ export function rappiAvailability(hosts: RappiHosts): MarketplaceAvailability {
90
+ return {
91
+ kind: "switch",
92
+ pause: async (ctx: AdapterCallContext, request: StorePauseRequest): Promise<StorePauseResult> => {
93
+ const result = await rappiSetStoreEnabled(ctx, hosts, request.merchantId, false);
94
+ return result.kind === "accepted" ? { kind: "paused", externalId: null, until: request.until } : result;
95
+ },
96
+ resume: (ctx, ref) => rappiSetStoreEnabled(ctx, hosts, ref.merchantId, true),
97
+ };
98
+ }
@@ -36,6 +36,7 @@ export {
36
36
  MARKETPLACE_PERMISSIONS,
37
37
  } from "./contribution";
38
38
  export {
39
+ MARKETPLACE_AVAILABILITY_ATTEMPTS,
39
40
  MARKETPLACE_FETCH_ORDER_ATTEMPTS,
40
41
  MARKETPLACE_JOBS,
41
42
  MARKETPLACE_OUTBOUND_ATTEMPTS,
@@ -5,9 +5,11 @@ import { CatalogueRetryError, type CatalogueJobPayload } from "../core/catalogue
5
5
  import { FetchOrderRetryError, type FetchOrderJobPayload } from "../core/fetch-order";
6
6
  import { OutboundRetryError } from "../core/outbound";
7
7
  import type { OutboundJobPayload } from "../core/outbound-queue";
8
+ import { AvailabilityRetryError } from "../core/pause-job";
9
+ import type { AvailabilityJobPayload } from "../core/pause-store";
8
10
 
9
11
  /**
10
- * The engine's three jobs, declared here because every number in them is the
12
+ * The engine's eight jobs, declared here because every number in them is the
11
13
  * engine's knowledge, not a host's:
12
14
  *
13
15
  * - `expire-acceptances`, every minute: the unit being measured is minutes (a
@@ -29,21 +31,36 @@ import type { OutboundJobPayload } from "../core/outbound-queue";
29
31
  * owes (a PENDING request, an accept with no confirm stamp, a catalogue
30
32
  * publish or withdraw on its way) once it is older than the job's own retry
31
33
  * span, so a refused enqueue or a dead process loses nothing.
34
+ * - `availability`, on demand: brings one marketplace in line with the host's
35
+ * last pause or resume ask for one store (FUT-4851). Three attempts with
36
+ * backoff; the last one stamps FAILED with a failure code.
37
+ * - `availability-sweep`, every five minutes: resumes a pause past its
38
+ * `until` (the host stopped renewing it), re-queues an ask still owed, and
39
+ * gives up on one older than a day.
32
40
  *
33
41
  * What stays the host's: whether to run them at all, on which runtime, and the
34
42
  * lease implementation. A host with no worker declines `jobs` in writing.
35
43
  *
36
44
  * Bound with `{ engine }`, these arrive at a runner as
37
45
  * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,
38
- * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.catalogue`
39
- * and `marketplace.outbound-sweep`.
46
+ * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.catalogue`,
47
+ * `marketplace.outbound-sweep`, `marketplace.availability` and
48
+ * `marketplace.availability-sweep`.
40
49
  */
41
50
 
42
51
  /** What the host closes over at bind time: the mounted engine. */
43
52
  export interface MarketplaceJobDeps {
44
53
  engine: Pick<
45
54
  MarketplaceEngine,
46
- "expireLapsed" | "retryable" | "reprocess" | "runOutbound" | "runFetchOrder" | "runCatalogue" | "sweepOutbound"
55
+ | "expireLapsed"
56
+ | "retryable"
57
+ | "reprocess"
58
+ | "runOutbound"
59
+ | "runFetchOrder"
60
+ | "runCatalogue"
61
+ | "sweepOutbound"
62
+ | "runAvailability"
63
+ | "sweepAvailability"
47
64
  >;
48
65
  }
49
66
 
@@ -181,6 +198,47 @@ const outboundSweep: WireJobBlueprint<void, MarketplaceJobDeps> = {
181
198
  },
182
199
  };
183
200
 
201
+ /** The availability job's attempts: the last one stamps FAILED. */
202
+ export const MARKETPLACE_AVAILABILITY_ATTEMPTS = 3;
203
+
204
+ const availability: WireJobBlueprint<AvailabilityJobPayload, MarketplaceJobDeps> = {
205
+ name: "availability",
206
+ attempts: MARKETPLACE_AVAILABILITY_ATTEMPTS,
207
+ // Short: a store is open on the marketplace while the kitchen is paused.
208
+ backoff: { type: "exponential", delayMs: 10_000 },
209
+ handle: async (payload, deps, context) => {
210
+ try {
211
+ const outcome = await deps.engine.runAvailability(payload, {
212
+ attempt: context.attempt,
213
+ maxAttempts: context.maxAttempts,
214
+ });
215
+ if (outcome.kind === "skipped") {
216
+ context.logger.info(`marketplace.availability: ${payload.provider} ${payload.clientId} skipped: ${outcome.reason}`);
217
+ }
218
+ } catch (error) {
219
+ if (error instanceof AvailabilityRetryError) context.logger.warn(`marketplace.availability: ${error.message}`);
220
+ throw error;
221
+ }
222
+ },
223
+ };
224
+
225
+ const availabilitySweep: WireJobBlueprint<void, MarketplaceJobDeps> = {
226
+ name: "availability-sweep",
227
+ queue: MARKETPLACE_SWEEP_QUEUE,
228
+ concurrency: 1,
229
+ schedule: { pattern: "*/5 * * * *", timezone: "UTC" },
230
+ attempts: 1,
231
+ lease: { ttlMs: SWEEP_LEASE_MS },
232
+ handle: async (_payload, deps, context) => {
233
+ const result = await deps.engine.sweepAvailability();
234
+ if (result.expired + result.requeued + result.givenUp === 0) return;
235
+ context.logger.info(
236
+ `marketplace.availability-sweep: resumed ${result.expired} expired pause(s), re-queued ${result.requeued}, ` +
237
+ `gave up on ${result.givenUp}.`,
238
+ );
239
+ },
240
+ };
241
+
184
242
  /** The jobs contribution. */
185
243
  export const MARKETPLACE_JOBS = {
186
244
  namespace: "marketplace",
@@ -191,5 +249,7 @@ export const MARKETPLACE_JOBS = {
191
249
  "fetch-order": fetchOrder,
192
250
  catalogue,
193
251
  "outbound-sweep": outboundSweep,
252
+ availability,
253
+ "availability-sweep": availabilitySweep,
194
254
  },
195
255
  } as const satisfies JobsContribution<MarketplaceJobDeps>;
@@ -1 +0,0 @@
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\";\n\n/**\n * The engine's three 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 *\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 * and `marketplace.outbound-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\" | \"retryable\" | \"reprocess\" | \"runOutbound\" | \"runFetchOrder\" | \"runCatalogue\" | \"sweepOutbound\"\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 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 },\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_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,E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