@12-apps/marketplace 1.2.0 → 1.3.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.
- package/ADOPTING.md +29 -4
- package/README.md +92 -3
- package/dist/99food/index.d.ts +48 -2
- package/dist/99food/index.js +84 -1
- package/dist/99food/index.js.map +1 -1
- package/dist/{adapter-_iuSxvVD.d.ts → adapter-0l_EmuJA.d.ts} +172 -2
- package/dist/{chunk-CRYFYDQ2.js → chunk-AYYBRQJV.js} +28 -4
- package/dist/chunk-AYYBRQJV.js.map +1 -0
- package/dist/chunk-M2V4RFMA.js +23 -0
- package/dist/chunk-M2V4RFMA.js.map +1 -0
- package/dist/{chunk-24RQZPSV.js → chunk-RVBTARIY.js} +1 -1
- package/dist/chunk-RVBTARIY.js.map +1 -0
- package/dist/{chunk-D2X7TOR6.js → chunk-XUAFXNOH.js} +449 -85
- package/dist/chunk-XUAFXNOH.js.map +1 -0
- package/dist/{engine-D-a4mttc.d.ts → engine-CZsP8KWd.d.ts} +222 -2
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +10 -2
- package/dist/ifood/index.js +246 -69
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +30 -4
- package/dist/index.js +148 -9
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +3 -2
- package/dist/manifest/server.js +2 -2
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +7 -1
- package/dist/rappi/index.js.map +1 -1
- package/dist/server/index.d.ts +12 -8
- package/dist/server/index.js +2 -2
- package/package.json +1 -1
- package/prisma/marketplace.prisma +92 -1
- package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
- package/src/99food/catalogue.ts +117 -0
- package/src/99food/index.ts +4 -0
- package/src/99food/outbound.ts +3 -3
- package/src/core/adapter.ts +10 -1
- package/src/core/catalogue-category.ts +119 -0
- package/src/core/catalogue-ids.ts +23 -0
- package/src/core/catalogue-job.ts +332 -0
- package/src/core/catalogue-port.ts +173 -0
- package/src/core/catalogue-store.ts +172 -0
- package/src/core/catalogue-sweep.ts +43 -0
- package/src/core/catalogue.ts +226 -0
- package/src/core/engine.ts +46 -0
- package/src/core/outbound-sweep.ts +7 -2
- package/src/core/ports.ts +36 -0
- package/src/ifood/catalogue.ts +273 -0
- package/src/ifood/index.ts +4 -0
- package/src/ifood/outbound.ts +9 -6
- package/src/index.ts +40 -0
- package/src/rappi/index.ts +6 -0
- package/src/server/jobs.ts +39 -9
- package/dist/chunk-24RQZPSV.js.map +0 -1
- package/dist/chunk-CRYFYDQ2.js.map +0 -1
- package/dist/chunk-D2X7TOR6.js.map +0 -1
|
@@ -1,3 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The catalogue half of the adapter port (FUT-4768): a store turns one of its
|
|
3
|
+
* products ON or OFF per connected marketplace, with an optional price for
|
|
4
|
+
* that marketplace, and the engine keeps the marketplace's catalogue in step.
|
|
5
|
+
*
|
|
6
|
+
* Marketplaces differ in exactly one way that shapes the engine: who moves the
|
|
7
|
+
* menu.
|
|
8
|
+
*
|
|
9
|
+
* - **push** — the store's software writes each item to the marketplace's API
|
|
10
|
+
* (iFood's Catalog API v2.0). The adapter publishes and withdraws ONE item.
|
|
11
|
+
* - **pull** — the marketplace reads the menu from the store's software (Open
|
|
12
|
+
* Delivery's `GET /v1/merchant`, which 99Food implements). The adapter turns
|
|
13
|
+
* the published items into the marketplace's menu document, which the HOST
|
|
14
|
+
* serves, and tells the marketplace the menu changed.
|
|
15
|
+
*
|
|
16
|
+
* A marketplace whose adapter states no `catalogue` cannot be published to,
|
|
17
|
+
* and the host says so (`engine.catalogueMode(provider)` is null). Everything
|
|
18
|
+
* else — the publication record and its states, the job, its retries, the
|
|
19
|
+
* sweep, the price rule — is the engine's and does not change with the
|
|
20
|
+
* marketplace.
|
|
21
|
+
*/
|
|
22
|
+
/** One product as it goes out to a marketplace. The host maps its product into this shape. */
|
|
23
|
+
interface CatalogueItem {
|
|
24
|
+
name: string;
|
|
25
|
+
description: string | null;
|
|
26
|
+
/**
|
|
27
|
+
* An absolute https URL of the product's photo, or null. It must CHANGE when
|
|
28
|
+
* the photo changes (a versioned URL: a content hash or an upload id in it):
|
|
29
|
+
* a marketplace that holds an uploaded copy reuses it while the URL is the
|
|
30
|
+
* same, so new bytes at an old URL are never sent.
|
|
31
|
+
*/
|
|
32
|
+
imageUrl: string | null;
|
|
33
|
+
/** The name of the host category the product sits in; the adapter finds or creates it. */
|
|
34
|
+
categoryName: string;
|
|
35
|
+
/** The store's own price, in the smallest currency unit. */
|
|
36
|
+
priceCents: number;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* What the adapter is handed to publish: the host's item with `priceCents`
|
|
40
|
+
* already the price for THIS marketplace (the connection's own price when the
|
|
41
|
+
* store set one, else the store's), and the engine's stable reference.
|
|
42
|
+
*/
|
|
43
|
+
interface CatalogueItemOut extends CatalogueItem {
|
|
44
|
+
/**
|
|
45
|
+
* The engine's stable id for this (connection, product) publication. The
|
|
46
|
+
* same across retries and re-publishes, so an adapter that must invent the
|
|
47
|
+
* marketplace's id (iFood wants a UUID it does not issue) derives it from
|
|
48
|
+
* this and a lost answer never creates a second item.
|
|
49
|
+
*/
|
|
50
|
+
ref: string;
|
|
51
|
+
/** The host's product id: the item's external code on the marketplace. */
|
|
52
|
+
productId: string;
|
|
53
|
+
/** The marketplace's id from the last publish, or null before the first. */
|
|
54
|
+
externalId: string | null;
|
|
55
|
+
/**
|
|
56
|
+
* The photo this marketplace already holds for the item, from an earlier
|
|
57
|
+
* publish: the adapter's own reference (iFood's `imagePath`) and the
|
|
58
|
+
* `imageUrl` it was made from. Reuse it while `sourceUrl` is still the
|
|
59
|
+
* item's `imageUrl` rather than uploading again; null when none is held.
|
|
60
|
+
*/
|
|
61
|
+
storedImage: CatalogueStoredImage | null;
|
|
62
|
+
}
|
|
63
|
+
/** A photo a marketplace holds: the adapter's reference to it, and the URL it was made from. */
|
|
64
|
+
interface CatalogueStoredImage {
|
|
65
|
+
ref: string;
|
|
66
|
+
sourceUrl: string;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Something a publish that SUCCEEDED could not do, for the host to say:
|
|
70
|
+
* the photo was too large for the marketplace, or it refused the photo.
|
|
71
|
+
*/
|
|
72
|
+
type CatalogueWarningCode = "IMAGE_TOO_LARGE" | "IMAGE_REFUSED";
|
|
73
|
+
/** What the adapter is handed to withdraw. */
|
|
74
|
+
type CatalogueItemRef = Pick<CatalogueItemOut, "ref" | "productId" | "externalId">;
|
|
75
|
+
/** An image's bytes, for a marketplace that takes an upload rather than a URL. */
|
|
76
|
+
interface CatalogueImage {
|
|
77
|
+
contentType: string;
|
|
78
|
+
/** The file, base64-encoded, no data-URL prefix. */
|
|
79
|
+
base64: string;
|
|
80
|
+
}
|
|
81
|
+
/** An outbound call's answer when it is not a success: refused (final) or retry. */
|
|
82
|
+
type CatalogueFailure = Exclude<OutboundResult, {
|
|
83
|
+
kind: "accepted";
|
|
84
|
+
}>;
|
|
85
|
+
/** What one catalogue call is handed: the outbound context plus the store's merchant id and the image loader. */
|
|
86
|
+
interface CatalogueCallContext extends AdapterCallContext {
|
|
87
|
+
/** The connection's merchant id on the marketplace. */
|
|
88
|
+
externalMerchantId: string;
|
|
89
|
+
/** The host's image loader: the bytes behind an item's `imageUrl`, or null when it cannot load them. */
|
|
90
|
+
loadImage(url: string): Promise<CatalogueImage | null>;
|
|
91
|
+
/**
|
|
92
|
+
* The marketplace's id for the host category `name`: the one the engine
|
|
93
|
+
* stored for this connection, else `resolve()` (the adapter's find-or-create)
|
|
94
|
+
* run by ONE publish at a time and stored. A second publish into a category
|
|
95
|
+
* being created is answered `retry`, so a new category is created once.
|
|
96
|
+
*/
|
|
97
|
+
category(name: string, resolve: () => Promise<{
|
|
98
|
+
id: string;
|
|
99
|
+
} | CatalogueFailure>): Promise<{
|
|
100
|
+
id: string;
|
|
101
|
+
} | CatalogueFailure>;
|
|
102
|
+
/**
|
|
103
|
+
* Forget the id stored for the host category `name` (the marketplace no
|
|
104
|
+
* longer has it: the store deleted it on the marketplace's portal), so the
|
|
105
|
+
* next `category` finds or creates it again.
|
|
106
|
+
*/
|
|
107
|
+
forgetCategory(name: string): Promise<void>;
|
|
108
|
+
}
|
|
109
|
+
/** A publish's answer: the marketplace's id for the item, or the refusal and retry shapes of every outbound call. */
|
|
110
|
+
type CataloguePublishResult = {
|
|
111
|
+
kind: "published";
|
|
112
|
+
externalId: string;
|
|
113
|
+
/**
|
|
114
|
+
* OPTIONAL. The SKU this marketplace's orders will carry for the item,
|
|
115
|
+
* when it is not the host's product id (the item's external code). The
|
|
116
|
+
* engine maps it to the product, so its orders arrive mapped.
|
|
117
|
+
*/
|
|
118
|
+
sku?: string;
|
|
119
|
+
/**
|
|
120
|
+
* OPTIONAL. The photo the marketplace now holds (stored for the next
|
|
121
|
+
* publish to reuse), null when it holds none; absent leaves the stored one.
|
|
122
|
+
*/
|
|
123
|
+
image?: CatalogueStoredImage | null;
|
|
124
|
+
/** OPTIONAL. What the publish could not do although it succeeded. */
|
|
125
|
+
warning?: CatalogueWarningCode;
|
|
126
|
+
} | CatalogueFailure;
|
|
127
|
+
/** A marketplace the store's software writes to. */
|
|
128
|
+
interface PushCatalogue {
|
|
129
|
+
readonly mode: "push";
|
|
130
|
+
/** Create or replace ONE item in the marketplace's catalogue, available for sale. Idempotent by `item.ref`. */
|
|
131
|
+
publishItem(ctx: CatalogueCallContext, item: CatalogueItemOut): Promise<CataloguePublishResult>;
|
|
132
|
+
/** Take ONE item out of the marketplace's catalogue. An item already absent is `accepted`. */
|
|
133
|
+
withdrawItem(ctx: CatalogueCallContext, item: CatalogueItemRef): Promise<OutboundResult>;
|
|
134
|
+
}
|
|
135
|
+
/** One published item, as a pull marketplace's menu document lists it. */
|
|
136
|
+
type CatalogueMenuEntry = CatalogueItemOut;
|
|
137
|
+
/** What the host states about the menu a pull marketplace reads: its words and money, never the engine's. */
|
|
138
|
+
interface CatalogueMenuOptions {
|
|
139
|
+
/** The menu's display name, in the store's language. */
|
|
140
|
+
menuName: string;
|
|
141
|
+
/** ISO 4217 code of the prices. */
|
|
142
|
+
currency: string;
|
|
143
|
+
}
|
|
144
|
+
/** A marketplace that reads the menu from the store's software. */
|
|
145
|
+
interface PullCatalogue {
|
|
146
|
+
readonly mode: "pull";
|
|
147
|
+
/**
|
|
148
|
+
* The menu part of the document the marketplace pulls, built from every item
|
|
149
|
+
* published to this connection. Pure and offline: the host serves it, merged
|
|
150
|
+
* into whatever else that document carries (the store's own details).
|
|
151
|
+
*/
|
|
152
|
+
menuDocument(input: {
|
|
153
|
+
externalMerchantId: string;
|
|
154
|
+
entries: readonly CatalogueMenuEntry[];
|
|
155
|
+
options: CatalogueMenuOptions;
|
|
156
|
+
}): unknown;
|
|
157
|
+
/** Tell the marketplace the menu changed, so it pulls it again. */
|
|
158
|
+
notifyMenuChanged(ctx: CatalogueCallContext): Promise<OutboundResult>;
|
|
159
|
+
}
|
|
160
|
+
/** The catalogue capability an adapter states, or leaves out. */
|
|
161
|
+
type MarketplaceCatalogue = PushCatalogue | PullCatalogue;
|
|
162
|
+
|
|
1
163
|
/**
|
|
2
164
|
* The canonical shape every marketplace adapter normalizes INTO.
|
|
3
165
|
*
|
|
@@ -173,7 +335,8 @@ interface MarketplaceCredentials {
|
|
|
173
335
|
}
|
|
174
336
|
/** What the host's HTTP client takes. */
|
|
175
337
|
interface MarketplaceHttpRequest {
|
|
176
|
-
|
|
338
|
+
/** `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it. */
|
|
339
|
+
method: "GET" | "POST" | "PUT" | "PATCH";
|
|
177
340
|
url: string;
|
|
178
341
|
headers: Record<string, string>;
|
|
179
342
|
body?: string;
|
|
@@ -303,6 +466,13 @@ interface MarketplaceAdapter {
|
|
|
303
466
|
fetchOrder?(ctx: AdapterCallContext, order: {
|
|
304
467
|
externalOrderId: string;
|
|
305
468
|
}): Promise<FetchOrderResult>;
|
|
469
|
+
/**
|
|
470
|
+
* OPTIONAL. Publishing the store's products to this marketplace's catalogue
|
|
471
|
+
* (FUT-4768): `push` (the adapter writes each item) or `pull` (the
|
|
472
|
+
* marketplace reads a menu document the host serves). Absent: the
|
|
473
|
+
* marketplace cannot be published to, and the host says so.
|
|
474
|
+
*/
|
|
475
|
+
readonly catalogue?: MarketplaceCatalogue;
|
|
306
476
|
/** Where "open it on the marketplace" goes: the order when `perOrderAppLink`, else the portal. Always https. */
|
|
307
477
|
appLink(order: Pick<OutboundOrderRef, "externalOrderId" | "externalDisplayId">): string;
|
|
308
478
|
}
|
|
@@ -316,4 +486,4 @@ declare function outboundResultOf(response: MarketplaceHttpResponse): OutboundRe
|
|
|
316
486
|
/** A call that never got an answer is a retry, with the reason a log can read. */
|
|
317
487
|
declare function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult>;
|
|
318
488
|
|
|
319
|
-
export { type AdapterCallContext as A, type
|
|
489
|
+
export { type AdapterCallContext as A, type NormalizedBuyer as B, type CatalogueMenuEntry as C, type NormalizedOrderLine as D, type OutboundResult as E, type FetchOrderResult as F, PROVIDER_ID_PATTERN as G, answered as H, outboundResultOf as I, type MarketplaceAdapter as M, type NormalizedEvent as N, type OutboundOrderRef as O, type PullCatalogue as P, type NormalizedMarketplaceOrder as a, type CatalogueMenuOptions as b, type PushCatalogue as c, type CatalogueItemOut as d, type MarketplaceProvider as e, type CancellationReason as f, type AdapterTokenCache as g, type CancellationOutcome as h, type CancellationRequestInput as i, type CatalogueCallContext as j, type CatalogueFailure as k, type CatalogueImage as l, type CatalogueItem as m, type CatalogueItemRef as n, type CataloguePublishResult as o, type CatalogueStoredImage as p, type CatalogueWarningCode as q, type MarketplaceCapabilities as r, type MarketplaceCatalogue as s, type MarketplaceCredentials as t, type MarketplaceDeliveredBy as u, type MarketplaceHttp as v, type MarketplaceHttpRequest as w, type MarketplaceHttpResponse as x, type MarketplaceOrderType as y, type NormalizedAddress as z };
|
|
@@ -9,9 +9,10 @@ import {
|
|
|
9
9
|
upsertMarketplaceMenuLinksBody
|
|
10
10
|
} from "./chunk-UYFYGGCS.js";
|
|
11
11
|
import {
|
|
12
|
+
CatalogueRetryError,
|
|
12
13
|
FetchOrderRetryError,
|
|
13
14
|
OutboundRetryError
|
|
14
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-XUAFXNOH.js";
|
|
15
16
|
import {
|
|
16
17
|
__name
|
|
17
18
|
} from "./chunk-7QVYU63E.js";
|
|
@@ -366,6 +367,27 @@ var fetchOrder = {
|
|
|
366
367
|
}
|
|
367
368
|
}, "handle")
|
|
368
369
|
};
|
|
370
|
+
var MARKETPLACE_CATALOGUE_ATTEMPTS = 3;
|
|
371
|
+
var catalogue = {
|
|
372
|
+
name: "catalogue",
|
|
373
|
+
attempts: MARKETPLACE_CATALOGUE_ATTEMPTS,
|
|
374
|
+
// Short: a person is watching the switch say "sending".
|
|
375
|
+
backoff: { type: "exponential", delayMs: 1e4 },
|
|
376
|
+
handle: /* @__PURE__ */ __name(async (payload, deps, context) => {
|
|
377
|
+
try {
|
|
378
|
+
const outcome = await deps.engine.runCatalogue(payload, {
|
|
379
|
+
attempt: context.attempt,
|
|
380
|
+
maxAttempts: context.maxAttempts
|
|
381
|
+
});
|
|
382
|
+
if (outcome.kind === "skipped") {
|
|
383
|
+
context.logger.info(`marketplace.catalogue: ${payload.action} ${payload.publicationId} skipped: ${outcome.reason}`);
|
|
384
|
+
}
|
|
385
|
+
} catch (error) {
|
|
386
|
+
if (error instanceof CatalogueRetryError) context.logger.warn(`marketplace.catalogue: ${error.message}`);
|
|
387
|
+
throw error;
|
|
388
|
+
}
|
|
389
|
+
}, "handle")
|
|
390
|
+
};
|
|
369
391
|
var outboundSweep = {
|
|
370
392
|
name: "outbound-sweep",
|
|
371
393
|
queue: MARKETPLACE_SWEEP_QUEUE,
|
|
@@ -375,9 +397,10 @@ var outboundSweep = {
|
|
|
375
397
|
lease: { ttlMs: SWEEP_LEASE_MS },
|
|
376
398
|
handle: /* @__PURE__ */ __name(async (_payload, deps, context) => {
|
|
377
399
|
const result = await deps.engine.sweepOutbound();
|
|
378
|
-
|
|
400
|
+
const idle = result.requeued + result.givenUp + result.timedOut + result.catalogueRequeued === 0;
|
|
401
|
+
if (idle) return;
|
|
379
402
|
context.logger.info(
|
|
380
|
-
`marketplace.outbound-sweep: re-queued ${result.requeued} call(s), timed out ${result.timedOut} cancellation request(s), gave up on ${result.givenUp}.`
|
|
403
|
+
`marketplace.outbound-sweep: re-queued ${result.requeued} call(s) and ${result.catalogueRequeued} catalogue call(s), timed out ${result.timedOut} cancellation request(s), gave up on ${result.givenUp}.`
|
|
381
404
|
);
|
|
382
405
|
}, "handle")
|
|
383
406
|
};
|
|
@@ -388,6 +411,7 @@ var MARKETPLACE_JOBS = {
|
|
|
388
411
|
"reconcile-inbox": reconcileInbox,
|
|
389
412
|
outbound,
|
|
390
413
|
"fetch-order": fetchOrder,
|
|
414
|
+
catalogue,
|
|
391
415
|
"outbound-sweep": outboundSweep
|
|
392
416
|
}
|
|
393
417
|
};
|
|
@@ -409,4 +433,4 @@ export {
|
|
|
409
433
|
MARKETPLACE_JOBS,
|
|
410
434
|
createApiMarketplace
|
|
411
435
|
};
|
|
412
|
-
//# sourceMappingURL=chunk-
|
|
436
|
+
//# sourceMappingURL=chunk-AYYBRQJV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/http.ts","../src/server/webhook.ts","../src/server/routes.ts","../src/server/jobs.ts","../src/server/index.ts"],"sourcesContent":["import type { z } from \"zod\";\n\nimport type { WireResponse } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceLogger } from \"../core/ports\";\nimport type { MarketplaceServerCopy } from \"./copy\";\n\n/**\n * What the route descriptors share: the config, the actor, and the two answer\n * shapes every handler uses.\n */\n\n/** Whoever the host resolved: the tenant this request may act inside. */\nexport interface MarketplaceActor {\n /** The tenant's id — every engine call is scoped to it. */\n clientId: string;\n /** The person, for the audit line an archive writes. Null for a system caller. */\n userId?: string | null;\n}\n\nexport interface MarketplaceApiConfig {\n /** The mounted engine (`createMarketplaceEngine`). */\n engine: MarketplaceEngine;\n /** Every sentence the routes answer a person with. Required, no defaults. */\n copy: MarketplaceServerCopy;\n /**\n * Which tenant a webhook's URL slug names, or null for none. The webhook is\n * unauthenticated by design (a marketplace cannot sign in), so the tenant\n * comes from the URL and is then proved by that tenant's signature secret.\n */\n tenantBySlug: (slug: string) => Promise<string | null>;\n /** Where the routes say what they refused. The manifest's `marketplace` namespace. */\n logger: MarketplaceLogger;\n}\n\n/** A 200 in the `{ data }` envelope. */\nexport function ok(data: unknown): WireResponse {\n return { status: 200, body: { data } };\n}\n\n/** A refusal in the `{ error }` envelope, with any extra fields beside it. */\nexport function refuse(status: number, error: string, extra: Record<string, unknown> = {}): WireResponse {\n return { status, body: { error, ...extra } };\n}\n\n/** The parsed value, or the 422 that names every problem and its path. */\nexport function parse<T>(\n schema: z.ZodType<T>,\n value: unknown,\n copy: MarketplaceServerCopy,\n): { ok: true; value: T } | { ok: false; response: WireResponse } {\n const parsed = schema.safeParse(value ?? {});\n if (parsed.success) return { ok: true, value: parsed.data };\n const problems = parsed.error.issues.map((issue) => ({\n path: issue.path.map((segment) => (typeof segment === \"number\" ? segment : String(segment))),\n code: \"INVALID_INPUT\",\n message: issue.message,\n }));\n return { ok: false, response: refuse(422, copy.invalidInput, { problems }) };\n}\n\n/** An ISO string, or null. */\nexport function iso(value: Date | null | undefined): string | null {\n return value ? value.toISOString() : null;\n}\n","import type { WireRequest, WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { IngestionTarget } from \"../core/integration\";\nimport type { MarketplaceApiConfig } from \"./http\";\n\n/**\n * `POST /webhooks/marketplace/:tenantSlug/:provider` — inbound deliveries for\n * ONE store, from any registered marketplace.\n *\n * PUBLIC by design (`kind: \"webhook\"`): a marketplace cannot authenticate as a\n * user. The store is attributed from the URL slug, then the delivery is\n * verified against THAT store's secret, through the provider's own adapter\n * (which header carries the signature, and how it is computed) — the route\n * itself knows no marketplace.\n *\n * It answers 2xx for almost everything, deliberately. A marketplace\n * redelivers on any non-2xx, so the only failures worth signalling are the\n * ones a redelivery could fix: a genuine processing failure answers 500, and\n * the inbox row it left is retried by the sweep regardless. Refusals (unknown\n * slug, no connection, bad signature) answer 401, indistinguishably, so a\n * prober cannot learn which stores exist. The bodies are machine codes: the\n * reader is a server, not a person.\n */\n\nconst UNAUTHORIZED: WireResponse = { status: 401, body: { error: \"unauthorized\" } };\n\n/**\n * The tenant the slug names and its connection to this marketplace, or the\n * 401 that ends the request. A blob that will not open is a 401 too, logged:\n * a key problem must never read as \"no secret configured\".\n */\nasync function connectionOf(\n config: MarketplaceApiConfig,\n tenantSlug: string,\n provider: string,\n): Promise<{ clientId: string; target: IngestionTarget } | WireResponse> {\n const clientId = await config.tenantBySlug(tenantSlug);\n if (!clientId) {\n config.logger.warn(`marketplace.webhook: unknown tenant slug \"${tenantSlug}\" (${provider})`);\n return UNAUTHORIZED;\n }\n try {\n const target = await config.engine.target(clientId, provider);\n // No connection at all: refused rather than stored — without one there is\n // no secret to verify against.\n return target ? { clientId, target } : UNAUTHORIZED;\n } catch (error) {\n config.logger.error(\n `marketplace.webhook: ${tenantSlug} ${provider} credentials do not open: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n return UNAUTHORIZED;\n }\n}\n\n/** The verified, parsed delivery, or the answer that ends the request. */\nasync function admit(\n config: MarketplaceApiConfig,\n request: WireRequest<unknown>,\n): Promise<{ clientId: string; provider: string; payload: unknown; target: IngestionTarget } | WireResponse> {\n const { tenantSlug = \"\", provider = \"\" } = request.params;\n const { engine } = config;\n if (!engine.knows(provider)) return { status: 404, body: { error: \"unknown_provider\" } };\n const raw = request.request;\n if (!raw) return { status: 400, body: { error: \"raw_request_required\" } };\n\n const connection = await connectionOf(config, tenantSlug, provider);\n if (\"status\" in connection) return connection;\n const rawBody = await raw.text();\n const signature = engine.readSignature(provider, (name) => raw.headers.get(name));\n if (!engine.verifySignature(provider, rawBody, signature, connection.target.webhookSecret)) {\n config.logger.warn(`marketplace.webhook: ${tenantSlug} ${provider} signature rejected`);\n return UNAUTHORIZED;\n }\n try {\n return { ...connection, provider, payload: JSON.parse(rawBody) as unknown };\n } catch {\n return { status: 400, body: { error: \"invalid_json\" } };\n }\n}\n\n/** Record and act on one verified delivery. */\nasync function handleWebhook(config: MarketplaceApiConfig, request: WireRequest<unknown>): Promise<WireResponse> {\n const admitted = await admit(config, request);\n if (\"status\" in admitted) return admitted;\n const { clientId, provider, payload, target } = admitted;\n const { engine } = config;\n\n const event = engine.normalize(provider, payload);\n if (!event) {\n // Nothing the adapter can key on. 200: redelivering an unreadable payload\n // produces an identical unreadable payload.\n config.logger.warn(`marketplace.webhook: ${provider} payload did not normalize`);\n return { status: 200, body: { received: true, ignored: \"unrecognized_payload\" } };\n }\n const outcome = await engine.deliver({\n clientId,\n event,\n payload,\n // A DISABLED connection still stores its deliveries and ingests nothing;\n // the retry sweep ingests them if the store turns it back on.\n settings: target.enabled ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds } : null,\n });\n if (outcome.kind === \"failed\") {\n return { status: 500, body: { received: true, error: outcome.reason } };\n }\n return { status: 200, body: { received: true, outcome: outcome.kind } };\n}\n\n/** The webhook descriptor. Raw body required: signatures are computed over bytes. */\nexport function webhookRoute(config: MarketplaceApiConfig): WireRoute<unknown> {\n return {\n method: \"POST\",\n path: \"/webhooks/marketplace/:tenantSlug/:provider\",\n kind: \"webhook\",\n handle: (request) => handleWebhook(config, request),\n };\n}\n","import type { WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { BulkProblem } from \"../core/bulk\";\nimport type { DecisionProblem } from \"../core/cancellation\";\nimport type { MarketplaceIntegrationView } from \"../core/integration\";\nimport type { MarketplaceMenuLinkView } from \"../core/menu-links\";\nimport { MARKETPLACE_DECIDE, MARKETPLACE_MANAGE } from \"./contribution\";\nimport type { MarketplaceServerCopy } from \"./copy\";\nimport { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from \"./http\";\nimport {\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nimport { webhookRoute } from \"./webhook\";\n\n/**\n * The marketplace HTTP surface as framework-neutral wiring descriptors: the\n * webhook every marketplace posts to, and, per entity, one read and one bulk\n * write — connections, SKU links, decisions — for a store's staff and its MCP\n * tools alike.\n *\n * There is no authentication, tenant resolution or RBAC in here: each\n * descriptor DECLARES the permission it needs and the host's guard answers it;\n * the actor arrives already resolved. Paths are relative to the host's mount.\n */\n\nexport type MarketplaceRoute = WireRoute<MarketplaceActor> | WireRoute<unknown>;\n\nconst BASE = \"/admin/:tenantSlug/marketplace\";\n\n/** The 409 code of a decision on an order that is no longer on the clock. */\nexport const ORDER_NOT_PENDING_CODE = \"MARKETPLACE_ORDER_NOT_PENDING\";\n\nconst NOT_PENDING = new Set([\"NOT_FOUND\", \"ALREADY_DECIDED\", \"EXPIRED\", \"CONFLICT\"]);\n\n/** A connection as the read returns it: dates as ISO, the adapter's half beside it. */\nfunction integrationOut(config: MarketplaceApiConfig, row: MarketplaceIntegrationView) {\n const adapter = config.engine.adapter(row.provider);\n return {\n ...row,\n lastEventAt: iso(row.lastEventAt),\n lastVerifiedAt: iso(row.lastVerifiedAt),\n archivedAt: iso(row.archivedAt),\n capabilities: adapter ? adapter.capabilities : null,\n reasons: adapter ? [...adapter.cancellationReasons()] : [],\n };\n}\n\nfunction linkOut(link: MarketplaceMenuLinkView) {\n return { ...link, lastSeenAt: link.lastSeenAt.toISOString() };\n}\n\n/** Each problem with its sentence; a host refusal keeps the host's own words. */\nfunction problemsOut(copy: MarketplaceServerCopy, problems: readonly (BulkProblem | DecisionProblem)[]) {\n return problems.map((problem) => {\n const host = \"host\" in problem ? problem.host : undefined;\n return {\n ...problem,\n message: host?.message ?? copy.problems[problem.code],\n ...(host ? { hostCode: host.code, details: host.details } : {}),\n };\n });\n}\n\n/** A refused bulk write: 422, nothing saved, every problem with its path. */\nfunction refusedBulk(copy: MarketplaceServerCopy, problems: readonly BulkProblem[]): WireResponse {\n return refuse(422, copy.nothingSaved, { problems: problemsOut(copy, problems) });\n}\n\n/**\n * A refused decision call. The host's own refusal is a 409 carrying ITS code\n * (`MARKETPLACE_STOCK_ASK` and the short lines in `details`); an order no\n * longer on the clock a 409; anything else (a reason, an item) a 422.\n */\nfunction refusedDecisions(copy: MarketplaceServerCopy, problems: readonly DecisionProblem[]): WireResponse {\n const out = problemsOut(copy, problems);\n const host = problems.find((problem) => problem.code === \"HOST_REFUSED\")?.host;\n if (host) return refuse(409, host.message, { code: host.code, details: host.details, problems: out });\n if (problems.some((problem) => NOT_PENDING.has(problem.code))) {\n return refuse(409, copy.orderNoLongerPending, { code: ORDER_NOT_PENDING_CODE, problems: out });\n }\n return refuse(422, copy.nothingSaved, { problems: out });\n}\n\nfunction integrationRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceIntegrationsQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const rows = await engine.integrations(actor.clientId, {\n providers: parsed.value.ids,\n includeArchived: parsed.value.includeArchived === \"true\",\n });\n return ok(rows.map((row) => integrationOut(config, row)));\n },\n },\n {\n method: \"PUT\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceIntegrationsBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertIntegrations({\n clientId: actor.clientId,\n actorId: actor.userId ?? null,\n validateOnly: parsed.value.validateOnly,\n rows: parsed.value.integrations.map((row) =>\n \"credentials\" in row && row.credentials\n ? { ...row, credentials: { ...row.credentials, webhookSecret: row.credentials.webhookSecret ?? null } }\n : row,\n ) as Parameters<typeof engine.upsertIntegrations>[0][\"rows\"],\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, integrations: result.rows.map((row) => integrationOut(config, row)) });\n },\n },\n ];\n}\n\nfunction menuLinkRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceMenuLinksQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const links = await engine.menuLinks({\n clientId: actor.clientId,\n provider: parsed.value.provider,\n unmappedOnly: parsed.value.unmapped === \"true\",\n ids: parsed.value.ids,\n });\n return ok(links.map(linkOut));\n },\n },\n {\n method: \"PUT\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceMenuLinksBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertMenuLinks({\n clientId: actor.clientId,\n rows: parsed.value.links,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, links: result.rows.map(linkOut) });\n },\n },\n ];\n}\n\nfunction acceptanceRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceAcceptancesQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const pending = await engine.pending(actor.clientId, parsed.value.ids);\n return ok(\n pending.map((order) => ({\n ...order,\n acknowledgeBy: iso(order.acknowledgeBy),\n externalDueAt: iso(order.externalDueAt),\n })),\n );\n },\n },\n {\n method: \"POST\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, body }) => {\n const parsed = parse(decideMarketplaceOrdersBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.decideMany({\n clientId: actor.clientId,\n decisions: parsed.value.decisions,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedDecisions(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, decisions: result.rows });\n },\n },\n ];\n}\n\n/** The whole surface, in mount order. */\nexport function marketplaceRoutes(config: MarketplaceApiConfig): MarketplaceRoute[] {\n return [\n webhookRoute(config),\n ...integrationRoutes(config),\n ...menuLinkRoutes(config),\n ...acceptanceRoutes(config),\n ];\n}\n","import type { JobsContribution, WireJobBlueprint } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport { CatalogueRetryError, type CatalogueJobPayload } from \"../core/catalogue-job\";\nimport { FetchOrderRetryError, type FetchOrderJobPayload } from \"../core/fetch-order\";\nimport { OutboundRetryError } from \"../core/outbound\";\nimport type { OutboundJobPayload } from \"../core/outbound-queue\";\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,GA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EACpD,UAAU;AAAA,EACV,OAAO,EAAE,OAAO,eAAe;AAAA,EAC/B,QAAQ,8BAAO,UAAU,MAAM,YAAY;AACzC,UAAM,SAAS,MAAM,KAAK,OAAO,cAAc;AAC/C,UAAM,OAAO,OAAO,WAAW,OAAO,UAAU,OAAO,WAAW,OAAO,sBAAsB;AAC/F,QAAI,KAAM;AACV,YAAQ,OAAO;AAAA,MACb,yCAAyC,OAAO,QAAQ,gBAAgB,OAAO,iBAAiB,iCACxE,OAAO,QAAQ,wCAAwC,OAAO,OAAO;AAAA,IAC/F;AAAA,EACF,GARQ;AASV;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,EACpB;AACF;;;AC5KO,SAAS,qBAAqB,QAA8C;AACjF,MAAI,CAAC,OAAO,QAAQ;AAClB,UAAM,IAAI,MAAM,kFAAkF;AAAA,EACpG;AACA,SAAO,EAAE,QAAQ,kBAAkB,MAAM,GAAG,QAAQ,OAAO,OAAO;AACpE;AALgB;","names":[]}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__name
|
|
3
|
+
} from "./chunk-7QVYU63E.js";
|
|
4
|
+
|
|
5
|
+
// src/core/catalogue-ids.ts
|
|
6
|
+
import { createHash } from "crypto";
|
|
7
|
+
function stableUuid(seed) {
|
|
8
|
+
const hex = createHash("sha256").update(seed, "utf8").digest("hex");
|
|
9
|
+
const variant = (Number.parseInt(hex.slice(16, 17), 16) & 3 | 8).toString(16);
|
|
10
|
+
return [
|
|
11
|
+
hex.slice(0, 8),
|
|
12
|
+
hex.slice(8, 12),
|
|
13
|
+
`4${hex.slice(13, 16)}`,
|
|
14
|
+
`${variant}${hex.slice(17, 20)}`,
|
|
15
|
+
hex.slice(20, 32)
|
|
16
|
+
].join("-");
|
|
17
|
+
}
|
|
18
|
+
__name(stableUuid, "stableUuid");
|
|
19
|
+
|
|
20
|
+
export {
|
|
21
|
+
stableUuid
|
|
22
|
+
};
|
|
23
|
+
//# sourceMappingURL=chunk-M2V4RFMA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/catalogue-ids.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\n/**\n * A UUID v4-shaped id derived from a seed, the same for the same seed (FUT-4768).\n *\n * Some marketplaces make the store's software invent the id of a catalogue\n * entity (iFood's Catalog API v2.0 and Open Delivery both want a UUID the\n * software generates). Deriving it from the engine's stable publication\n * reference, instead of drawing a random one, makes a retried publish whose\n * first answer was lost name the SAME item rather than a second one, and needs\n * no write before the call.\n */\nexport function stableUuid(seed: string): string {\n const hex = createHash(\"sha256\").update(seed, \"utf8\").digest(\"hex\");\n const variant = ((Number.parseInt(hex.slice(16, 17), 16) & 0x3) | 0x8).toString(16);\n return [\n hex.slice(0, 8),\n hex.slice(8, 12),\n `4${hex.slice(13, 16)}`,\n `${variant}${hex.slice(17, 20)}`,\n hex.slice(20, 32),\n ].join(\"-\");\n}\n"],"mappings":";;;;;AAAA,SAAS,kBAAkB;AAYpB,SAAS,WAAW,MAAsB;AAC/C,QAAM,MAAM,WAAW,QAAQ,EAAE,OAAO,MAAM,MAAM,EAAE,OAAO,KAAK;AAClE,QAAM,WAAY,OAAO,SAAS,IAAI,MAAM,IAAI,EAAE,GAAG,EAAE,IAAI,IAAO,GAAK,SAAS,EAAE;AAClF,SAAO;AAAA,IACL,IAAI,MAAM,GAAG,CAAC;AAAA,IACd,IAAI,MAAM,GAAG,EAAE;AAAA,IACf,IAAI,IAAI,MAAM,IAAI,EAAE,CAAC;AAAA,IACrB,GAAG,OAAO,GAAG,IAAI,MAAM,IAAI,EAAE,CAAC;AAAA,IAC9B,IAAI,MAAM,IAAI,EAAE;AAAA,EAClB,EAAE,KAAK,GAAG;AACZ;AAVgB;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { MarketplaceCatalogue } from \"./catalogue-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 /** `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it. */\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\";\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 /** A final 4xx (not 408/425/429): never retried. */\n | { kind: \"refused\"; status: number; message: string }\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 /** 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/** 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":";;;;;AA+LA,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;AAShB,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":[]}
|