@12-apps/marketplace 1.16.0 → 1.18.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 (79) hide show
  1. package/ADOPTING.md +185 -0
  2. package/dist/99food/index.d.ts +2 -2
  3. package/dist/99food/index.js +2 -2
  4. package/dist/{adapter-CjVdMhZ2.d.ts → adapter-ZpAWKoCk.d.ts} +300 -3
  5. package/dist/{chunk-TRUK5ZBE.js → chunk-3B5EULS6.js} +2 -2
  6. package/dist/{chunk-DJIMUEHT.js → chunk-BLHZ3MRB.js} +79 -7
  7. package/dist/chunk-BLHZ3MRB.js.map +1 -0
  8. package/dist/{chunk-SGOTN5PX.js → chunk-LO7OKO6V.js} +45 -4
  9. package/dist/chunk-LO7OKO6V.js.map +1 -0
  10. package/dist/{chunk-TICWLBSA.js → chunk-MDEIRGNL.js} +1372 -823
  11. package/dist/chunk-MDEIRGNL.js.map +1 -0
  12. package/dist/{chunk-H2VQRD3B.js → chunk-Q5RMVNU5.js} +1 -1
  13. package/dist/chunk-Q5RMVNU5.js.map +1 -0
  14. package/dist/{chunk-BTKVZAJI.js → chunk-ZT6TZTLD.js} +1 -1
  15. package/dist/chunk-ZT6TZTLD.js.map +1 -0
  16. package/dist/{client-DgzCkl8u.d.ts → client-DpEq0yXb.d.ts} +1 -1
  17. package/dist/{engine-DSRj7qnC.d.ts → engine-DRRhAjZK.d.ts} +566 -293
  18. package/dist/hono/index.d.ts +2 -2
  19. package/dist/hono/index.js +4 -4
  20. package/dist/ifood/index.d.ts +14 -2
  21. package/dist/ifood/index.js +406 -120
  22. package/dist/ifood/index.js.map +1 -1
  23. package/dist/index.d.ts +21 -4
  24. package/dist/index.js +453 -43
  25. package/dist/index.js.map +1 -1
  26. package/dist/keeta/index.d.ts +2 -2
  27. package/dist/keeta/index.js +2 -2
  28. package/dist/manifest/index.d.ts +78 -0
  29. package/dist/manifest/index.js +1 -1
  30. package/dist/manifest/server.d.ts +6 -2
  31. package/dist/manifest/server.js +4 -4
  32. package/dist/rappi/index.d.ts +1 -1
  33. package/dist/rappi/index.js +1 -1
  34. package/dist/server/index.d.ts +93 -7
  35. package/dist/server/index.js +4 -4
  36. package/package.json +1 -1
  37. package/prisma/marketplace.prisma +70 -2
  38. package/prisma/migrations/20261203180000_marketplace_app_link_check/migration.sql +14 -0
  39. package/prisma/migrations/20261203190000_marketplace_disputes/migration.sql +96 -0
  40. package/prisma/migrations/20261203200000_marketplace_status_logistics_steps/migration.sql +12 -0
  41. package/src/core/adapter.ts +14 -2
  42. package/src/core/app-linking.ts +396 -0
  43. package/src/core/delivery-code.ts +119 -0
  44. package/src/core/dispute-engine.ts +32 -0
  45. package/src/core/dispute-job.ts +142 -0
  46. package/src/core/dispute-port.ts +133 -0
  47. package/src/core/dispute-store.ts +203 -0
  48. package/src/core/disputes.ts +263 -0
  49. package/src/core/engine.ts +12 -55
  50. package/src/core/integration.ts +3 -1
  51. package/src/core/link-engine.ts +176 -0
  52. package/src/core/link-store.ts +15 -0
  53. package/src/core/linking-port.ts +35 -1
  54. package/src/core/linking.ts +8 -0
  55. package/src/core/logistics.ts +388 -0
  56. package/src/core/outbound-queue.ts +6 -1
  57. package/src/core/outbound-sweep.ts +19 -6
  58. package/src/core/outbound.ts +4 -5
  59. package/src/core/pipeline.ts +14 -4
  60. package/src/core/ports.ts +20 -2
  61. package/src/core/status-job.ts +3 -0
  62. package/src/core/status-store.ts +2 -1
  63. package/src/core/types.ts +10 -0
  64. package/src/ifood/app-linking.ts +119 -0
  65. package/src/ifood/disputes.ts +209 -0
  66. package/src/ifood/index.ts +15 -1
  67. package/src/ifood/logistics.ts +38 -0
  68. package/src/ifood/normalize.ts +14 -1
  69. package/src/index.ts +44 -0
  70. package/src/server/jobs.ts +51 -3
  71. package/src/server/link-routes.ts +56 -4
  72. package/src/server/mcp-link.ts +44 -2
  73. package/src/server/mcp.ts +2 -1
  74. package/dist/chunk-BTKVZAJI.js.map +0 -1
  75. package/dist/chunk-DJIMUEHT.js.map +0 -1
  76. package/dist/chunk-H2VQRD3B.js.map +0 -1
  77. package/dist/chunk-SGOTN5PX.js.map +0 -1
  78. package/dist/chunk-TICWLBSA.js.map +0 -1
  79. /package/dist/{chunk-TRUK5ZBE.js.map → chunk-3B5EULS6.js.map} +0 -0
@@ -1,200 +1,799 @@
1
1
  import {
2
2
  PROVIDER_ID_PATTERN
3
- } from "./chunk-H2VQRD3B.js";
3
+ } from "./chunk-Q5RMVNU5.js";
4
4
  import {
5
5
  __name
6
6
  } from "./chunk-7QVYU63E.js";
7
7
 
8
- // src/core/registry.ts
9
- var MarketplaceAdapterRegistrationError = class extends Error {
8
+ // src/core/merchant-claim.ts
9
+ var MarketplaceMerchantTakenError = class extends Error {
10
10
  static {
11
- __name(this, "MarketplaceAdapterRegistrationError");
11
+ __name(this, "MarketplaceMerchantTakenError");
12
12
  }
13
- constructor(message) {
14
- super(`@12-apps/marketplace: ${message}`);
15
- this.name = "MarketplaceAdapterRegistrationError";
13
+ code = "MERCHANT_TAKEN";
14
+ /** The field the refusal is about, as a problem path. */
15
+ path = ["externalMerchantId"];
16
+ constructor(provider, merchantId) {
17
+ super(`The ${provider} merchant ${merchantId} is already held by another store's live connection.`);
18
+ this.name = "MarketplaceMerchantTakenError";
16
19
  }
17
20
  };
18
- function assertReasons(adapter) {
19
- const codes = /* @__PURE__ */ new Set();
20
- for (const reason of adapter.cancellationReasons()) {
21
- if (reason.code.trim() === "") {
22
- throw new MarketplaceAdapterRegistrationError(`${adapter.provider} declares a reason with a blank code.`);
23
- }
24
- if (codes.has(reason.code)) {
25
- throw new MarketplaceAdapterRegistrationError(
26
- `${adapter.provider} declares the reason code "${reason.code}" twice.`
27
- );
28
- }
29
- codes.add(reason.code);
30
- }
31
- if (adapter.capabilities.apiCancel && codes.size === 0) {
32
- throw new MarketplaceAdapterRegistrationError(
33
- `${adapter.provider} can cancel through its API but declares no reason to cancel with.`
34
- );
35
- }
36
- }
37
- __name(assertReasons, "assertReasons");
38
- function createAdapterRegistry(adapters) {
39
- if (adapters.length === 0) {
40
- throw new MarketplaceAdapterRegistrationError("an engine needs at least one adapter.");
41
- }
42
- const byProvider = /* @__PURE__ */ new Map();
43
- for (const adapter of adapters) {
44
- if (!PROVIDER_ID_PATTERN.test(adapter.provider)) {
45
- throw new MarketplaceAdapterRegistrationError(
46
- `provider id "${adapter.provider}" must be uppercase letters, digits and underscores.`
47
- );
48
- }
49
- if (byProvider.has(adapter.provider)) {
50
- throw new MarketplaceAdapterRegistrationError(`two adapters claim "${adapter.provider}".`);
51
- }
52
- assertReasons(adapter);
53
- byProvider.set(adapter.provider, adapter);
54
- }
55
- const providers = [...byProvider.keys()];
56
- return {
57
- get: /* @__PURE__ */ __name((provider) => byProvider.get(provider) ?? null, "get"),
58
- has: /* @__PURE__ */ __name((provider) => byProvider.has(provider), "has"),
59
- providers: /* @__PURE__ */ __name(() => providers, "providers")
60
- };
21
+ function isUniqueViolation(error) {
22
+ const code = error?.code;
23
+ return code === "P2002" || code === "23505";
61
24
  }
62
- __name(createAdapterRegistry, "createAdapterRegistry");
63
- function storedReasons(value) {
64
- if (!Array.isArray(value) || value.length === 0) return null;
65
- return value.flatMap((entry) => {
66
- const { code, description } = entry ?? {};
67
- return typeof code === "string" ? [{ code, description: typeof description === "string" ? description : code }] : [];
25
+ __name(isUniqueViolation, "isUniqueViolation");
26
+ async function merchantHeldElsewhere(db, clientId, provider, merchantId) {
27
+ const rows = await db.marketplaceIntegration.findMany({
28
+ where: { provider, externalMerchantId: merchantId, archivedAt: null },
29
+ select: { clientId: true }
68
30
  });
31
+ return rows.some((row) => row.clientId !== clientId);
69
32
  }
70
- __name(storedReasons, "storedReasons");
71
- function reasonsForOrder(adapter, stored) {
72
- const own = storedReasons(stored);
73
- if (own === null) return adapter.cancellationReasons();
74
- const known = new Map(adapter.cancellationReasons().map((reason) => [reason.code, reason]));
75
- return own.map(
76
- (reason) => known.get(reason.code) ?? { code: reason.code, label: reason.description, itemUnavailable: false, needsItems: false }
77
- );
78
- }
79
- __name(reasonsForOrder, "reasonsForOrder");
80
- function resolveReason(adapter, code, stored) {
81
- const reasons = reasonsForOrder(adapter, stored);
82
- if (code === null || code === void 0) return reasons[0] ?? null;
83
- return reasons.find((reason) => reason.code === code) ?? null;
84
- }
85
- __name(resolveReason, "resolveReason");
86
- function suggestReason(adapter, input) {
87
- const reasons = adapter.cancellationReasons();
88
- if (input.itemUnavailable) {
89
- const unavailable = reasons.find((reason) => reason.itemUnavailable);
90
- if (unavailable) return unavailable;
33
+ __name(merchantHeldElsewhere, "merchantHeldElsewhere");
34
+ async function assertMerchantFree(db, clientId, provider, merchantId) {
35
+ if (merchantId && await merchantHeldElsewhere(db, clientId, provider, merchantId)) {
36
+ throw new MarketplaceMerchantTakenError(provider, merchantId);
91
37
  }
92
- return reasons[0] ?? null;
93
38
  }
94
- __name(suggestReason, "suggestReason");
95
-
96
- // src/core/cancellation-outcome.ts
97
- async function tell(ctx, what, orderId, call2) {
39
+ __name(assertMerchantFree, "assertMerchantFree");
40
+ async function guardMerchantClaim(ctx, claim3, write2) {
98
41
  try {
99
- await call2();
42
+ return await write2();
100
43
  } catch (error) {
101
- ctx.ports.logger.error(
102
- `marketplace.cancellation: order ${orderId} ${what} but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
103
- );
44
+ const { merchantId } = claim3;
45
+ if (!isUniqueViolation(error) || !merchantId) throw error;
46
+ if (!await merchantHeldElsewhere(await ctx.ports.db(), claim3.clientId, claim3.provider, merchantId)) throw error;
47
+ throw new MarketplaceMerchantTakenError(claim3.provider, merchantId);
104
48
  }
105
49
  }
106
- __name(tell, "tell");
107
- function requestsFirst(ctx) {
108
- return ctx.ports.order.onCancellationConfirmed !== void 0;
109
- }
110
- __name(requestsFirst, "requestsFirst");
111
- async function rejectConfirmed(db, orderId, now) {
112
- await db.marketplaceAcceptance.updateMany({
113
- where: { orderId, status: "AWAITING" },
114
- data: { status: "REJECTED", acknowledgedAt: now }
115
- });
116
- await db.marketplaceAcceptance.updateMany({
117
- where: { orderId, status: { in: ["ACCEPTED", "EXPIRED"] } },
118
- data: { status: "REJECTED" }
50
+ __name(guardMerchantClaim, "guardMerchantClaim");
51
+ async function resolveTenantByMerchant(ctx, provider, externalMerchantId) {
52
+ const db = await ctx.ports.db();
53
+ const rows = await db.marketplaceIntegration.findMany({
54
+ where: { provider, externalMerchantId, archivedAt: null },
55
+ select: { clientId: true },
56
+ take: 2
119
57
  });
58
+ if (rows.length > 1) {
59
+ ctx.ports.logger.warn(`marketplace: ${provider} merchant ${externalMerchantId} is held by several live connections`);
60
+ return null;
61
+ }
62
+ return rows[0]?.clientId ?? null;
120
63
  }
121
- __name(rejectConfirmed, "rejectConfirmed");
122
- async function confirmedToHost(ctx, clientId, orderId) {
123
- if (await tellCancellationConfirmed(ctx, clientId, orderId)) return;
124
- await ctx.ports.order.onRefused(clientId, orderId, "CANCELLED");
125
- }
126
- __name(confirmedToHost, "confirmedToHost");
127
- async function tellCancellationConfirmed(ctx, clientId, orderId) {
128
- const hook = ctx.ports.order.onCancellationConfirmed;
129
- if (!hook) return false;
130
- await tell(ctx, "was cancelled on the store's request", orderId, () => hook.call(ctx.ports.order, clientId, orderId));
131
- return true;
64
+ __name(resolveTenantByMerchant, "resolveTenantByMerchant");
65
+
66
+ // src/core/outbound-queue.ts
67
+ var MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
68
+ function outboundDedupeKey(payload) {
69
+ return `${MARKETPLACE_OUTBOUND_JOB}:${payload.action}:${payload.step ? `${payload.step}:` : ""}${payload.orderId}`;
132
70
  }
133
- __name(tellCancellationConfirmed, "tellCancellationConfirmed");
134
- async function tellCancellationFailed(ctx, clientId, orderId, reason) {
135
- const hook = ctx.ports.order.onCancellationFailed;
136
- if (!hook) return;
137
- await tell(
138
- ctx,
139
- `had its cancellation request fail (${reason})`,
140
- orderId,
141
- () => hook.call(ctx.ports.order, clientId, orderId, reason)
142
- );
71
+ __name(outboundDedupeKey, "outboundDedupeKey");
72
+ function statusDedupeKey(step, orderId, at) {
73
+ return `${MARKETPLACE_OUTBOUND_JOB}:status:${step}:${orderId}:${at.getTime()}`;
143
74
  }
144
- __name(tellCancellationFailed, "tellCancellationFailed");
145
- function cancellationWindowMs(ctx, adapter) {
146
- return ctx.ports.cancellationWindowMs ?? adapter.capabilities.cancellationAnswerWindowMs ?? null;
75
+ __name(statusDedupeKey, "statusDedupeKey");
76
+ function ableTo(adapter, payload) {
77
+ switch (payload.action) {
78
+ case "status":
79
+ return Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step));
80
+ case "logistics":
81
+ return Boolean(adapter.logistics);
82
+ case "confirm":
83
+ return adapter.capabilities.apiConfirm;
84
+ default:
85
+ return adapter.capabilities.apiCancel;
86
+ }
147
87
  }
148
- __name(cancellationWindowMs, "cancellationWindowMs");
149
- function failedRequestData(reason) {
150
- return { cancellationStatus: "FAILED", cancellationFailureReason: reason };
88
+ __name(ableTo, "ableTo");
89
+ async function enqueueOutbound(ctx, payload, provider, dedupeKey = outboundDedupeKey(payload)) {
90
+ const adapter = ctx.registry.get(provider);
91
+ if (!adapter) return false;
92
+ if (!ableTo(adapter, payload)) return false;
93
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
94
+ if (!outcome.enqueued) {
95
+ ctx.ports.logger.warn(
96
+ `${MARKETPLACE_OUTBOUND_JOB}: ${payload.action} for order ${payload.orderId} was not queued; the outbound sweep will re-queue it` + (outcome.reason ? ` (${outcome.reason})` : "")
97
+ );
98
+ }
99
+ return outcome.enqueued;
151
100
  }
152
- __name(failedRequestData, "failedRequestData");
101
+ __name(enqueueOutbound, "enqueueOutbound");
153
102
 
154
- // src/core/cancellation.ts
155
- function noStandingRequest(cancellationStatus) {
156
- return cancellationStatus === null || cancellationStatus === "FAILED";
103
+ // src/core/link-store.ts
104
+ function sealLink(ctx, refreshToken) {
105
+ return ctx.ports.secrets.seal(JSON.stringify({ clientId: "", clientSecret: "", webhookSecret: null, refreshToken }));
157
106
  }
158
- __name(noStandingRequest, "noStandingRequest");
159
- var NO_STANDING_REQUEST = { OR: [{ cancellationStatus: null }, { cancellationStatus: "FAILED" }] };
160
- var CLAIM_SELECT = {
161
- orderId: true,
162
- provider: true,
163
- status: true,
164
- cancellationStatus: true,
165
- lineSkus: true,
166
- cancellationReasons: true
167
- };
168
- function notPendingProblem(row, path, allowed = ["AWAITING"]) {
169
- if (!row) return { path: [...path, "orderId"], code: "NOT_FOUND" };
170
- if (allowed.includes(row.status) && noStandingRequest(row.cancellationStatus)) return null;
171
- const status = row.status;
172
- return { path: [...path, "orderId"], code: status === "EXPIRED" ? "EXPIRED" : "ALREADY_DECIDED", status };
107
+ __name(sealLink, "sealLink");
108
+ function openLinkRefreshToken(ctx, sealed) {
109
+ const parsed = JSON.parse(ctx.ports.secrets.open(sealed));
110
+ const token = typeof parsed === "object" && parsed !== null ? parsed.refreshToken : null;
111
+ if (typeof token !== "string" || token === "") throw new Error("The linked connection holds no refresh token.");
112
+ return token;
173
113
  }
174
- __name(notPendingProblem, "notPendingProblem");
175
- function lineSkusOf(row) {
176
- return Array.isArray(row.lineSkus) ? new Set(row.lineSkus.map(String)) : null;
114
+ __name(openLinkRefreshToken, "openLinkRefreshToken");
115
+ function sealAppLink(ctx) {
116
+ return ctx.ports.secrets.seal(JSON.stringify({ clientId: "", clientSecret: "", webhookSecret: null, app: true }));
177
117
  }
178
- __name(lineSkusOf, "lineSkusOf");
179
- function skuProblems(reason, skus, row, path) {
180
- if (reason?.needsItems && skus.length === 0) return [{ path: [...path, "offendingSkus"], code: "ITEMS_REQUIRED" }];
181
- const known = lineSkusOf(row);
182
- if (!known) return [];
183
- return skus.flatMap(
184
- (sku, index) => known.has(sku) ? [] : [{ path: [...path, "offendingSkus", index], code: "UNKNOWN_ITEM" }]
185
- );
118
+ __name(sealAppLink, "sealAppLink");
119
+ function isAppLinkBlob(ctx, sealed) {
120
+ try {
121
+ const parsed = JSON.parse(ctx.ports.secrets.open(sealed));
122
+ return typeof parsed === "object" && parsed !== null && parsed.app === true;
123
+ } catch {
124
+ return false;
125
+ }
186
126
  }
187
- __name(skuProblems, "skuProblems");
188
- function invalidReasonProblem(adapter, reason, input, path) {
189
- if (input.code === null || input.code === void 0 || reason) return null;
190
- const validCodes = reasonsForOrder(adapter, input.stored).map((candidate) => candidate.code);
191
- return { path: [...path, "reasonCode"], code: "INVALID_REASON", validCodes };
127
+ __name(isAppLinkBlob, "isAppLinkBlob");
128
+ async function appCredentialsOf(ctx, provider, environment) {
129
+ const port = ctx.ports.appCredentials;
130
+ if (!port) return null;
131
+ const credentials = await port(provider, environment);
132
+ return credentials && credentials.clientId !== "" && credentials.clientSecret !== "" ? credentials : null;
192
133
  }
193
- __name(invalidReasonProblem, "invalidReasonProblem");
194
- function planCancellation(adapter, input, row, path) {
195
- if (!adapter) return { status: null, reason: null, skus: [] };
196
- const reason = resolveReason(adapter, input.reasonCode, row.cancellationReasons);
197
- const invalid = invalidReasonProblem(adapter, reason, { code: input.reasonCode, stored: row.cancellationReasons }, path);
134
+ __name(appCredentialsOf, "appCredentialsOf");
135
+ var linkTokenKey = /* @__PURE__ */ __name((provider, environment, clientId) => `LINK:${provider}:${environment}:${clientId}`, "linkTokenKey");
136
+ async function cacheLinkToken(ctx, link, key, grant) {
137
+ const db = await ctx.ports.db();
138
+ const row = await db.marketplaceIntegration.findUnique({
139
+ where: { clientId_provider: { clientId: link.clientId, provider: link.provider } },
140
+ select: { credentials: true }
141
+ });
142
+ if (row?.credentials !== link.sealed) return false;
143
+ setToken(ctx, key, grant);
144
+ return true;
145
+ }
146
+ __name(cacheLinkToken, "cacheLinkToken");
147
+ function setToken(ctx, key, grant) {
148
+ const expiresAt = ctx.ports.clock.now().getTime() + Math.max(grant.expiresInSeconds, 1) * 1e3;
149
+ ctx.tokens.set(key, { token: grant.accessToken, expiresAt });
150
+ }
151
+ __name(setToken, "setToken");
152
+ var inflight = /* @__PURE__ */ new WeakMap();
153
+ async function storeRotated(ctx, link, refreshToken) {
154
+ const db = await ctx.ports.db();
155
+ const { count } = await db.marketplaceIntegration.updateMany({
156
+ where: { clientId: link.clientId, provider: link.provider, authMode: "LINKED", archivedAt: null, credentials: link.sealed },
157
+ data: { credentials: sealLink(ctx, refreshToken) }
158
+ });
159
+ return count > 0;
160
+ }
161
+ __name(storeRotated, "storeRotated");
162
+ async function markLinkFailed(ctx, link) {
163
+ const db = await ctx.ports.db();
164
+ const { count } = await db.marketplaceIntegration.updateMany({
165
+ where: { clientId: link.clientId, provider: link.provider, authMode: "LINKED", credentials: link.sealed },
166
+ data: { status: "FAILED" }
167
+ });
168
+ if (count > 0) ctx.ports.publishChanged(link.clientId);
169
+ return count > 0;
170
+ }
171
+ __name(markLinkFailed, "markLinkFailed");
172
+ var RELINKED = { kind: "retry", reason: "the connection was linked again during the refresh" };
173
+ async function refreshOnce(ctx, link, key) {
174
+ const linking = ctx.registry.get(link.provider)?.linking;
175
+ if (!linking) return { kind: "refused", status: 0, message: "this marketplace links no store", own: true };
176
+ const answer = await linking.refresh(
177
+ { http: ctx.ports.http, credentials: link.app, environment: link.environment, now: ctx.ports.clock.now() },
178
+ { refreshToken: link.refreshToken }
179
+ );
180
+ if (answer.kind === "retry") return answer;
181
+ if (answer.kind === "refused") return await markLinkFailed(ctx, link) ? { ...answer, own: true } : RELINKED;
182
+ const rotated = answer.value.refreshToken;
183
+ if (rotated === null || rotated === link.refreshToken) {
184
+ return await cacheLinkToken(ctx, link, key, answer.value) ? { token: answer.value.accessToken } : RELINKED;
185
+ }
186
+ const stored = await storeRotated(ctx, link, rotated).catch((error) => {
187
+ ctx.ports.logger.error(
188
+ `marketplace.link: ${link.provider} rotated refresh token of ${link.clientId} not stored: ` + (error instanceof Error ? error.message : String(error))
189
+ );
190
+ return null;
191
+ });
192
+ if (stored === false) return RELINKED;
193
+ setToken(ctx, key, answer.value);
194
+ return { token: answer.value.accessToken };
195
+ }
196
+ __name(refreshOnce, "refreshOnce");
197
+ function linkGrant(ctx, link) {
198
+ const key = linkTokenKey(link.provider, link.environment, link.clientId);
199
+ return {
200
+ key,
201
+ accessToken: /* @__PURE__ */ __name(async () => {
202
+ const cached = ctx.tokens.get(key);
203
+ if (cached && cached.expiresAt > ctx.ports.clock.now().getTime()) return { token: cached.token };
204
+ let running = inflight.get(ctx.tokens);
205
+ if (!running) {
206
+ running = /* @__PURE__ */ new Map();
207
+ inflight.set(ctx.tokens, running);
208
+ }
209
+ const pending = running.get(key);
210
+ if (pending) return pending;
211
+ const call2 = refreshOnce(ctx, link, key).catch((error) => ({
212
+ kind: "retry",
213
+ reason: error instanceof Error ? error.message : String(error)
214
+ })).finally(() => running.delete(key));
215
+ running.set(key, call2);
216
+ return call2;
217
+ }, "accessToken")
218
+ };
219
+ }
220
+ __name(linkGrant, "linkGrant");
221
+
222
+ // src/core/integration.ts
223
+ var VIEW_SELECT = {
224
+ provider: true,
225
+ enabled: true,
226
+ environment: true,
227
+ status: true,
228
+ externalMerchantId: true,
229
+ autoAccept: true,
230
+ followStatus: true,
231
+ ackSlaSeconds: true,
232
+ credentials: true,
233
+ lastEventAt: true,
234
+ lastVerifiedAt: true,
235
+ archivedAt: true,
236
+ authMode: true
237
+ };
238
+ function toView(row) {
239
+ return {
240
+ provider: row.provider,
241
+ enabled: row.enabled,
242
+ environment: row.environment,
243
+ status: row.status,
244
+ externalMerchantId: row.externalMerchantId,
245
+ autoAccept: row.autoAccept,
246
+ followStatus: row.followStatus ?? true,
247
+ ackSlaSeconds: row.ackSlaSeconds,
248
+ connected: row.credentials !== "",
249
+ lastEventAt: row.lastEventAt,
250
+ lastVerifiedAt: row.lastVerifiedAt,
251
+ archivedAt: row.archivedAt ?? null,
252
+ authMode: row.authMode === "LINKED" ? "LINKED" : "CREDENTIALS"
253
+ };
254
+ }
255
+ __name(toView, "toView");
256
+ async function listMarketplaceIntegrations(ctx, clientId, options = {}) {
257
+ const db = await ctx.ports.db();
258
+ const rows = await db.marketplaceIntegration.findMany({
259
+ where: {
260
+ clientId,
261
+ ...options.providers ? { provider: { in: [...options.providers] } } : {},
262
+ ...options.includeArchived ? {} : { archivedAt: null }
263
+ },
264
+ select: VIEW_SELECT,
265
+ orderBy: { provider: "asc" }
266
+ });
267
+ return rows.map(toView);
268
+ }
269
+ __name(listMarketplaceIntegrations, "listMarketplaceIntegrations");
270
+ async function saveMarketplaceIntegration(ctx, input, db) {
271
+ await assertMerchantFree(db, input.clientId, input.provider, input.externalMerchantId);
272
+ const sealed = input.credentials ? ctx.ports.secrets.seal(JSON.stringify(input.credentials)) : void 0;
273
+ const mutable = {
274
+ ...input.enabled === void 0 ? {} : { enabled: input.enabled },
275
+ ...input.environment === void 0 ? {} : { environment: input.environment },
276
+ ...input.externalMerchantId === void 0 ? {} : { externalMerchantId: input.externalMerchantId },
277
+ ...input.autoAccept === void 0 ? {} : { autoAccept: input.autoAccept },
278
+ ...input.followStatus === void 0 ? {} : { followStatus: input.followStatus },
279
+ ...input.ackSlaSeconds === void 0 ? {} : { ackSlaSeconds: input.ackSlaSeconds },
280
+ // Typed credentials make the connection the store's own app again.
281
+ ...sealed === void 0 ? {} : { credentials: sealed, status: "UNVERIFIED", authMode: "CREDENTIALS" }
282
+ };
283
+ const row = await db.marketplaceIntegration.upsert({
284
+ where: { clientId_provider: { clientId: input.clientId, provider: input.provider } },
285
+ create: {
286
+ clientId: input.clientId,
287
+ provider: input.provider,
288
+ credentials: sealed ?? "",
289
+ ackSlaSeconds: ctx.ports.defaultAckSlaSeconds,
290
+ ...mutable
291
+ },
292
+ update: mutable,
293
+ select: VIEW_SELECT
294
+ });
295
+ return toView(row);
296
+ }
297
+ __name(saveMarketplaceIntegration, "saveMarketplaceIntegration");
298
+ async function connectionMerchantId(ctx, clientId, provider) {
299
+ const db = await ctx.ports.db();
300
+ const row = await db.marketplaceIntegration.findUnique({
301
+ where: { clientId_provider: { clientId, provider } },
302
+ select: { externalMerchantId: true, archivedAt: true }
303
+ });
304
+ return row && !row.archivedAt ? row.externalMerchantId ?? null : null;
305
+ }
306
+ __name(connectionMerchantId, "connectionMerchantId");
307
+ async function resolveIngestionTarget(ctx, clientId, provider) {
308
+ const db = await ctx.ports.db();
309
+ const row = await db.marketplaceIntegration.findUnique({
310
+ where: { clientId_provider: { clientId, provider } },
311
+ select: {
312
+ enabled: true,
313
+ autoAccept: true,
314
+ followStatus: true,
315
+ ackSlaSeconds: true,
316
+ credentials: true,
317
+ archivedAt: true,
318
+ externalMerchantId: true,
319
+ authMode: true,
320
+ environment: true
321
+ }
322
+ });
323
+ if (!row || row.archivedAt) return null;
324
+ return {
325
+ enabled: row.enabled,
326
+ autoAccept: row.autoAccept,
327
+ followStatus: row.followStatus ?? true,
328
+ ackSlaSeconds: row.ackSlaSeconds,
329
+ externalMerchantId: row.externalMerchantId ?? null,
330
+ // An unopenable blob must not read as "no secret configured" — that would
331
+ // turn a key-rotation problem into an endpoint that accepts unsigned
332
+ // deliveries. The secrets port throws instead, and the caller answers 401.
333
+ webhookSecret: await webhookSecretOf(ctx, provider, row)
334
+ };
335
+ }
336
+ __name(resolveIngestionTarget, "resolveIngestionTarget");
337
+ async function webhookSecretOf(ctx, provider, row) {
338
+ if (row.authMode !== "LINKED") {
339
+ return row.credentials === "" ? null : openCredentials(ctx, row.credentials).webhookSecret;
340
+ }
341
+ const app = await appCredentialsOf(ctx, provider, environmentOf(row.environment));
342
+ if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
343
+ const secret = app.webhookSecret || app.clientSecret;
344
+ if (!secret) throw new Error(`No webhook key is configured for ${provider}.`);
345
+ return secret;
346
+ }
347
+ __name(webhookSecretOf, "webhookSecretOf");
348
+ var environmentOf = /* @__PURE__ */ __name((value) => value === "PRODUCTION" ? "PRODUCTION" : "SANDBOX", "environmentOf");
349
+ function openCredentials(ctx, sealed) {
350
+ const parsed = JSON.parse(ctx.ports.secrets.open(sealed));
351
+ if (typeof parsed !== "object" || parsed === null) {
352
+ throw new Error("Stored marketplace credentials are not an object.");
353
+ }
354
+ const record = parsed;
355
+ return {
356
+ clientId: String(record.clientId ?? ""),
357
+ clientSecret: String(record.clientSecret ?? ""),
358
+ webhookSecret: record.webhookSecret ? String(record.webhookSecret) : null
359
+ };
360
+ }
361
+ __name(openCredentials, "openCredentials");
362
+ async function markMarketplaceEventSeen(db, clientId, provider, at) {
363
+ await db.marketplaceIntegration.updateMany({
364
+ where: { clientId, provider },
365
+ data: { lastEventAt: at }
366
+ });
367
+ }
368
+ __name(markMarketplaceEventSeen, "markMarketplaceEventSeen");
369
+ async function readOutboundConnection(ctx, clientId, provider) {
370
+ return (await readSealedOutboundConnection(ctx, clientId, provider))?.connection ?? null;
371
+ }
372
+ __name(readOutboundConnection, "readOutboundConnection");
373
+ async function readSealedOutboundConnection(ctx, clientId, provider) {
374
+ const db = await ctx.ports.db();
375
+ const row = await db.marketplaceIntegration.findUnique({
376
+ where: { clientId_provider: { clientId, provider } },
377
+ select: { environment: true, credentials: true, authMode: true }
378
+ });
379
+ if (!row || row.credentials === "") return null;
380
+ const sealed = row.credentials;
381
+ const environment = environmentOf(row.environment);
382
+ if (row.authMode !== "LINKED") return { connection: { environment, credentials: openCredentials(ctx, sealed) }, sealed };
383
+ const app = await appCredentialsOf(ctx, provider, environment);
384
+ if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
385
+ if (isAppLinkBlob(ctx, sealed)) return { connection: { environment, credentials: app }, sealed };
386
+ const refreshToken = openLinkRefreshToken(ctx, sealed);
387
+ const link = { clientId, provider, environment, refreshToken, app, sealed };
388
+ return { connection: { environment, credentials: app, grant: linkGrant(ctx, link) }, sealed };
389
+ }
390
+ __name(readSealedOutboundConnection, "readSealedOutboundConnection");
391
+
392
+ // src/core/status-store.ts
393
+ function statusTable(db) {
394
+ return db.marketplaceStatusUpdate ?? null;
395
+ }
396
+ __name(statusTable, "statusTable");
397
+ async function readStatusRows(table, orderId, steps2) {
398
+ return await table.findMany({
399
+ where: { orderId, step: { in: [...steps2] } },
400
+ select: { orderId: true, step: true, source: true, state: true, claimKey: true }
401
+ });
402
+ }
403
+ __name(readStatusRows, "readStatusRows");
404
+ async function insertStatusRow(table, row) {
405
+ try {
406
+ await table.create({ data: row });
407
+ return true;
408
+ } catch (error) {
409
+ if (error.code === "P2002") return false;
410
+ throw error;
411
+ }
412
+ }
413
+ __name(insertStatusRow, "insertStatusRow");
414
+ async function noteMarketplaceStep(ctx, row) {
415
+ const table = statusTable(await ctx.ports.db());
416
+ if (table) await insertStatusRow(table, { ...row, source: "MARKETPLACE", state: "NOTED", claimKey: "" });
417
+ }
418
+ __name(noteMarketplaceStep, "noteMarketplaceStep");
419
+ async function settleStatusRow(table, where, state) {
420
+ return (await table.updateMany({ where: { ...where, state: "SENDING" }, data: { state } })).count;
421
+ }
422
+ __name(settleStatusRow, "settleStatusRow");
423
+
424
+ // src/core/logistics.ts
425
+ var LOGISTICS_STEPS = ["ASSIGNED", "GOING_TO_ORIGIN", "ARRIVED_AT_ORIGIN", "DISPATCHED", "ARRIVED_AT_DESTINATION"];
426
+ var LOGISTICS_ROW_PREFIX = "LOGISTICS_";
427
+ var rowStep = /* @__PURE__ */ __name((step) => `${LOGISTICS_ROW_PREFIX}${step}`, "rowStep");
428
+ function logisticsDedupeKey(step, orderId, at) {
429
+ return `${MARKETPLACE_OUTBOUND_JOB}:logistics:${step}:${orderId}:${at.getTime()}`;
430
+ }
431
+ __name(logisticsDedupeKey, "logisticsDedupeKey");
432
+ async function informLogistics(ctx, input) {
433
+ const payload = {
434
+ clientId: input.clientId,
435
+ orderId: input.orderId,
436
+ action: "logistics",
437
+ logisticsStep: input.step,
438
+ // The step is in the key: two moves at one instant never share a claim.
439
+ claimKey: `${input.step}:${input.at.getTime()}`
440
+ };
441
+ try {
442
+ const options = {
443
+ dedupeKey: logisticsDedupeKey(input.step, input.orderId, input.at),
444
+ ...input.delayMs === void 0 ? {} : { delayMs: input.delayMs }
445
+ };
446
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, options);
447
+ if (!outcome.enqueued) ctx.ports.logger.warn(`${MARKETPLACE_OUTBOUND_JOB}: logistics ${input.step} for order ${input.orderId} was not queued`);
448
+ return outcome.enqueued;
449
+ } catch (error) {
450
+ ctx.ports.logger.warn(
451
+ `${MARKETPLACE_OUTBOUND_JOB}: logistics ${input.step} for order ${input.orderId} was not queued: ` + (error instanceof Error ? error.message : String(error))
452
+ );
453
+ return false;
454
+ }
455
+ }
456
+ __name(informLogistics, "informLogistics");
457
+ function logisticsEngine(ctx) {
458
+ return { informLogistics: /* @__PURE__ */ __name((input) => informLogistics(ctx, input), "informLogistics") };
459
+ }
460
+ __name(logisticsEngine, "logisticsEngine");
461
+ var skipped = /* @__PURE__ */ __name((reason) => ({ kind: "skipped", reason }), "skipped");
462
+ function orderSkip(row, adapter) {
463
+ if (!adapter.logistics) return "the marketplace has no Logistics half";
464
+ if (row.deliveredBy !== "MERCHANT") return "the store does not carry this order";
465
+ if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
466
+ const standing = row.cancellationStatus !== null && row.cancellationStatus !== "FAILED";
467
+ return standing ? `a cancellation request is ${row.cancellationStatus}` : null;
468
+ }
469
+ __name(orderSkip, "orderSkip");
470
+ function confirmSkip(row, adapter, deps) {
471
+ if (!adapter.capabilities.statusAfterConfirm || row.confirmedAt) return null;
472
+ if (row.confirmFailedAt) return "the marketplace never took the store's confirm";
473
+ if (deps.attempt.attempt < deps.attempt.maxAttempts) throw deps.retryError(`logistics for order ${row.orderId}: the store's confirm has not reached the marketplace yet`);
474
+ return "the store's confirm has not reached the marketplace";
475
+ }
476
+ __name(confirmSkip, "confirmSkip");
477
+ async function logisticsAppOf(ctx, provider, environment) {
478
+ const port = ctx.ports.logisticsCredentials;
479
+ if (!port) return null;
480
+ const credentials = await port(provider, environment);
481
+ return credentials && credentials.clientId !== "" && credentials.clientSecret !== "" ? credentials : null;
482
+ }
483
+ __name(logisticsAppOf, "logisticsAppOf");
484
+ async function environmentOf2(ctx, clientId, provider) {
485
+ try {
486
+ const connection = await readOutboundConnection(ctx, clientId, provider);
487
+ return connection ? { environment: connection.environment } : { missing: "no credentials on file" };
488
+ } catch (error) {
489
+ return { missing: `credentials do not open: ${error instanceof Error ? error.message : String(error)}` };
490
+ }
491
+ }
492
+ __name(environmentOf2, "environmentOf");
493
+ function chainTo(target) {
494
+ return LOGISTICS_STEPS.slice(0, LOGISTICS_STEPS.indexOf(target) + 1);
495
+ }
496
+ __name(chainTo, "chainTo");
497
+ async function waitOrSkip(run, target, reason) {
498
+ if (run.deps.attempt.attempt < run.deps.attempt.maxAttempts) throw run.deps.retryError(`logistics for order ${run.row.orderId}: ${reason}`);
499
+ await claimStep(run, target, void 0);
500
+ return skipped(reason);
501
+ }
502
+ __name(waitOrSkip, "waitOrSkip");
503
+ async function send(run, step) {
504
+ if (step !== "ASSIGNED") return run.logistics.step(run.call, run.deps.ref, step);
505
+ if (!run.driver) return { kind: "invalid", reason: "the host names no courier for this order" };
506
+ return run.logistics.assignDriver(run.call, run.deps.ref, run.driver);
507
+ }
508
+ __name(send, "send");
509
+ async function settle(run, step, result) {
510
+ const where = { orderId: run.row.orderId, step: rowStep(step), claimKey: run.key };
511
+ if (result.kind === "accepted") {
512
+ await settleStatusRow(run.table, where, "SENT");
513
+ return null;
514
+ }
515
+ const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
516
+ if (result.kind === "retry" && run.deps.attempt.attempt < run.deps.attempt.maxAttempts) {
517
+ throw run.deps.retryError(`logistics ${step} for order ${run.row.orderId}: ${reason}`);
518
+ }
519
+ await settleStatusRow(run.table, where, "FAILED");
520
+ run.ctx.ports.logger.error(`${MARKETPLACE_OUTBOUND_JOB}: logistics ${step} for order ${run.row.orderId} failed: ${reason}`);
521
+ return reason;
522
+ }
523
+ __name(settle, "settle");
524
+ async function claimStep(run, step, found) {
525
+ if (found?.state === "SENT") return "sent";
526
+ if (found?.state === "FAILED") return { stop: `${step} failed earlier` };
527
+ if (found?.state === "SENDING") return found.claimKey === run.key ? "mine" : { wait: `${step} is being sent by another run` };
528
+ const claimed = await insertStatusRow(run.table, {
529
+ clientId: run.payload.clientId,
530
+ orderId: run.row.orderId,
531
+ provider: run.row.provider,
532
+ step: rowStep(step),
533
+ source: "STORE",
534
+ state: "SENDING",
535
+ claimKey: run.key
536
+ });
537
+ return claimed ? "mine" : { wait: `another run holds the claim on ${step}` };
538
+ }
539
+ __name(claimStep, "claimStep");
540
+ async function logisticsCallContext(ctx, clientId, provider) {
541
+ const connection = await environmentOf2(ctx, clientId, provider);
542
+ if ("missing" in connection) return connection.missing;
543
+ const app = await logisticsAppOf(ctx, provider, connection.environment);
544
+ if (!app) return "no Logistics app credentials are configured";
545
+ return { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), environment: connection.environment, credentials: app };
546
+ }
547
+ __name(logisticsCallContext, "logisticsCallContext");
548
+ async function stopChain(run, chain, reason) {
549
+ for (const step of chain) await settleStatusRow(run.table, { orderId: run.row.orderId, step: rowStep(step), claimKey: run.key }, "FAILED");
550
+ return { kind: "failed", action: "logistics", reason };
551
+ }
552
+ __name(stopChain, "stopChain");
553
+ async function courierWhileOwed(ctx, table, payload, orderId) {
554
+ const [assigned] = await readStatusRows(table, orderId, [rowStep("ASSIGNED")]);
555
+ if (assigned?.state === "SENT") return null;
556
+ return await ctx.ports.order.logisticsDriver?.call(ctx.ports.order, payload.clientId, orderId) ?? "none";
557
+ }
558
+ __name(courierWhileOwed, "courierWhileOwed");
559
+ async function releaseHeld(ctx, table, orderId, chain, key) {
560
+ await table.deleteMany?.({ where: { orderId, step: { in: chain.map(rowStep) }, state: "SENDING", claimKey: key } });
561
+ ctx.ports.logger.info(`${MARKETPLACE_OUTBOUND_JOB}: logistics for order ${orderId} not sent: the host names no courier for it now`);
562
+ return skipped("the host names no courier for this order");
563
+ }
564
+ __name(releaseHeld, "releaseHeld");
565
+ async function runChain(run, chain) {
566
+ const rows = await readStatusRows(run.table, run.row.orderId, chain.map(rowStep));
567
+ for (const step of chain) {
568
+ const claim3 = await claimStep(run, step, rows.find((found) => found.step === rowStep(step)));
569
+ if (claim3 === "sent") continue;
570
+ if (typeof claim3 === "object") return "wait" in claim3 ? waitOrSkip(run, chain.at(-1), claim3.wait) : stopChain(run, chain, claim3.stop);
571
+ const failed = await settle(run, step, await send(run, step));
572
+ if (failed) return stopChain(run, chain, failed);
573
+ }
574
+ return { kind: "done", action: "logistics" };
575
+ }
576
+ __name(runChain, "runChain");
577
+ async function runLogistics(ctx, payload, row, adapter, deps) {
578
+ const target = payload.logisticsStep;
579
+ if (!target || !LOGISTICS_STEPS.includes(target)) return skipped("a logistics call names no step");
580
+ const stopped = orderSkip(row, adapter) ?? confirmSkip(row, adapter, deps);
581
+ if (stopped) return skipped(stopped);
582
+ const table = statusTable(await ctx.ports.db());
583
+ if (!table) return skipped("the host has not composed the status model");
584
+ const call2 = await logisticsCallContext(ctx, payload.clientId, row.provider);
585
+ if (typeof call2 === "string") {
586
+ ctx.ports.logger.info(`${MARKETPLACE_OUTBOUND_JOB}: logistics ${target} for order ${row.orderId} not sent: ${call2}`);
587
+ return skipped(call2);
588
+ }
589
+ const chain = chainTo(target);
590
+ const key = payload.claimKey ?? "";
591
+ const driver = await courierWhileOwed(ctx, table, payload, row.orderId);
592
+ if (driver === "none") return releaseHeld(ctx, table, row.orderId, chain, key);
593
+ return runChain({ ctx, table, payload, row, call: call2, logistics: adapter.logistics, driver, key, deps }, chain);
594
+ }
595
+ __name(runLogistics, "runLogistics");
596
+ async function failLogisticsJob(ctx, payload, error) {
597
+ const reason = error instanceof Error ? error.message : String(error);
598
+ const table = statusTable(await ctx.ports.db());
599
+ for (const step of table && payload.logisticsStep ? chainTo(payload.logisticsStep) : []) {
600
+ await settleStatusRow(table, { orderId: payload.orderId, step: rowStep(step), claimKey: payload.claimKey ?? "" }, "FAILED");
601
+ }
602
+ ctx.ports.logger.error(`${MARKETPLACE_OUTBOUND_JOB}: logistics ${payload.logisticsStep ?? ""} for order ${payload.orderId} failed: ${reason}`);
603
+ return { kind: "failed", action: "logistics", reason };
604
+ }
605
+ __name(failLogisticsJob, "failLogisticsJob");
606
+
607
+ // src/core/registry.ts
608
+ var MarketplaceAdapterRegistrationError = class extends Error {
609
+ static {
610
+ __name(this, "MarketplaceAdapterRegistrationError");
611
+ }
612
+ constructor(message) {
613
+ super(`@12-apps/marketplace: ${message}`);
614
+ this.name = "MarketplaceAdapterRegistrationError";
615
+ }
616
+ };
617
+ function assertReasons(adapter) {
618
+ const codes = /* @__PURE__ */ new Set();
619
+ for (const reason of adapter.cancellationReasons()) {
620
+ if (reason.code.trim() === "") {
621
+ throw new MarketplaceAdapterRegistrationError(`${adapter.provider} declares a reason with a blank code.`);
622
+ }
623
+ if (codes.has(reason.code)) {
624
+ throw new MarketplaceAdapterRegistrationError(
625
+ `${adapter.provider} declares the reason code "${reason.code}" twice.`
626
+ );
627
+ }
628
+ codes.add(reason.code);
629
+ }
630
+ if (adapter.capabilities.apiCancel && codes.size === 0) {
631
+ throw new MarketplaceAdapterRegistrationError(
632
+ `${adapter.provider} can cancel through its API but declares no reason to cancel with.`
633
+ );
634
+ }
635
+ }
636
+ __name(assertReasons, "assertReasons");
637
+ function createAdapterRegistry(adapters) {
638
+ if (adapters.length === 0) {
639
+ throw new MarketplaceAdapterRegistrationError("an engine needs at least one adapter.");
640
+ }
641
+ const byProvider = /* @__PURE__ */ new Map();
642
+ for (const adapter of adapters) {
643
+ if (!PROVIDER_ID_PATTERN.test(adapter.provider)) {
644
+ throw new MarketplaceAdapterRegistrationError(
645
+ `provider id "${adapter.provider}" must be uppercase letters, digits and underscores.`
646
+ );
647
+ }
648
+ if (byProvider.has(adapter.provider)) {
649
+ throw new MarketplaceAdapterRegistrationError(`two adapters claim "${adapter.provider}".`);
650
+ }
651
+ assertReasons(adapter);
652
+ byProvider.set(adapter.provider, adapter);
653
+ }
654
+ const providers = [...byProvider.keys()];
655
+ return {
656
+ get: /* @__PURE__ */ __name((provider) => byProvider.get(provider) ?? null, "get"),
657
+ has: /* @__PURE__ */ __name((provider) => byProvider.has(provider), "has"),
658
+ providers: /* @__PURE__ */ __name(() => providers, "providers")
659
+ };
660
+ }
661
+ __name(createAdapterRegistry, "createAdapterRegistry");
662
+ function storedReasons(value) {
663
+ if (!Array.isArray(value) || value.length === 0) return null;
664
+ return value.flatMap((entry) => {
665
+ const { code, description } = entry ?? {};
666
+ return typeof code === "string" ? [{ code, description: typeof description === "string" ? description : code }] : [];
667
+ });
668
+ }
669
+ __name(storedReasons, "storedReasons");
670
+ function reasonsForOrder(adapter, stored) {
671
+ const own = storedReasons(stored);
672
+ if (own === null) return adapter.cancellationReasons();
673
+ const known = new Map(adapter.cancellationReasons().map((reason) => [reason.code, reason]));
674
+ return own.map(
675
+ (reason) => known.get(reason.code) ?? { code: reason.code, label: reason.description, itemUnavailable: false, needsItems: false }
676
+ );
677
+ }
678
+ __name(reasonsForOrder, "reasonsForOrder");
679
+ function resolveReason(adapter, code, stored) {
680
+ const reasons = reasonsForOrder(adapter, stored);
681
+ if (code === null || code === void 0) return reasons[0] ?? null;
682
+ return reasons.find((reason) => reason.code === code) ?? null;
683
+ }
684
+ __name(resolveReason, "resolveReason");
685
+ function suggestReason(adapter, input) {
686
+ const reasons = adapter.cancellationReasons();
687
+ if (input.itemUnavailable) {
688
+ const unavailable = reasons.find((reason) => reason.itemUnavailable);
689
+ if (unavailable) return unavailable;
690
+ }
691
+ return reasons[0] ?? null;
692
+ }
693
+ __name(suggestReason, "suggestReason");
694
+
695
+ // src/core/cancellation-outcome.ts
696
+ async function tell(ctx, what, orderId, call2) {
697
+ try {
698
+ await call2();
699
+ } catch (error) {
700
+ ctx.ports.logger.error(
701
+ `marketplace.cancellation: order ${orderId} ${what} but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
702
+ );
703
+ }
704
+ }
705
+ __name(tell, "tell");
706
+ function requestsFirst(ctx) {
707
+ return ctx.ports.order.onCancellationConfirmed !== void 0;
708
+ }
709
+ __name(requestsFirst, "requestsFirst");
710
+ async function rejectConfirmed(db, orderId, now) {
711
+ await db.marketplaceAcceptance.updateMany({
712
+ where: { orderId, status: "AWAITING" },
713
+ data: { status: "REJECTED", acknowledgedAt: now }
714
+ });
715
+ await db.marketplaceAcceptance.updateMany({
716
+ where: { orderId, status: { in: ["ACCEPTED", "EXPIRED"] } },
717
+ data: { status: "REJECTED" }
718
+ });
719
+ }
720
+ __name(rejectConfirmed, "rejectConfirmed");
721
+ async function confirmedToHost(ctx, clientId, orderId) {
722
+ if (await tellCancellationConfirmed(ctx, clientId, orderId)) return;
723
+ await ctx.ports.order.onRefused(clientId, orderId, "CANCELLED");
724
+ }
725
+ __name(confirmedToHost, "confirmedToHost");
726
+ async function tellCancellationConfirmed(ctx, clientId, orderId) {
727
+ const hook = ctx.ports.order.onCancellationConfirmed;
728
+ if (!hook) return false;
729
+ await tell(ctx, "was cancelled on the store's request", orderId, () => hook.call(ctx.ports.order, clientId, orderId));
730
+ return true;
731
+ }
732
+ __name(tellCancellationConfirmed, "tellCancellationConfirmed");
733
+ async function tellCancellationFailed(ctx, clientId, orderId, reason) {
734
+ const hook = ctx.ports.order.onCancellationFailed;
735
+ if (!hook) return;
736
+ await tell(
737
+ ctx,
738
+ `had its cancellation request fail (${reason})`,
739
+ orderId,
740
+ () => hook.call(ctx.ports.order, clientId, orderId, reason)
741
+ );
742
+ }
743
+ __name(tellCancellationFailed, "tellCancellationFailed");
744
+ function cancellationWindowMs(ctx, adapter) {
745
+ return ctx.ports.cancellationWindowMs ?? adapter.capabilities.cancellationAnswerWindowMs ?? null;
746
+ }
747
+ __name(cancellationWindowMs, "cancellationWindowMs");
748
+ function failedRequestData(reason) {
749
+ return { cancellationStatus: "FAILED", cancellationFailureReason: reason };
750
+ }
751
+ __name(failedRequestData, "failedRequestData");
752
+
753
+ // src/core/cancellation.ts
754
+ function noStandingRequest(cancellationStatus) {
755
+ return cancellationStatus === null || cancellationStatus === "FAILED";
756
+ }
757
+ __name(noStandingRequest, "noStandingRequest");
758
+ var NO_STANDING_REQUEST = { OR: [{ cancellationStatus: null }, { cancellationStatus: "FAILED" }] };
759
+ var CLAIM_SELECT = {
760
+ orderId: true,
761
+ provider: true,
762
+ status: true,
763
+ cancellationStatus: true,
764
+ lineSkus: true,
765
+ cancellationReasons: true
766
+ };
767
+ function notPendingProblem(row, path, allowed = ["AWAITING"]) {
768
+ if (!row) return { path: [...path, "orderId"], code: "NOT_FOUND" };
769
+ if (allowed.includes(row.status) && noStandingRequest(row.cancellationStatus)) return null;
770
+ const status = row.status;
771
+ return { path: [...path, "orderId"], code: status === "EXPIRED" ? "EXPIRED" : "ALREADY_DECIDED", status };
772
+ }
773
+ __name(notPendingProblem, "notPendingProblem");
774
+ function lineSkusOf(row) {
775
+ return Array.isArray(row.lineSkus) ? new Set(row.lineSkus.map(String)) : null;
776
+ }
777
+ __name(lineSkusOf, "lineSkusOf");
778
+ function skuProblems(reason, skus, row, path) {
779
+ if (reason?.needsItems && skus.length === 0) return [{ path: [...path, "offendingSkus"], code: "ITEMS_REQUIRED" }];
780
+ const known = lineSkusOf(row);
781
+ if (!known) return [];
782
+ return skus.flatMap(
783
+ (sku, index) => known.has(sku) ? [] : [{ path: [...path, "offendingSkus", index], code: "UNKNOWN_ITEM" }]
784
+ );
785
+ }
786
+ __name(skuProblems, "skuProblems");
787
+ function invalidReasonProblem(adapter, reason, input, path) {
788
+ if (input.code === null || input.code === void 0 || reason) return null;
789
+ const validCodes = reasonsForOrder(adapter, input.stored).map((candidate) => candidate.code);
790
+ return { path: [...path, "reasonCode"], code: "INVALID_REASON", validCodes };
791
+ }
792
+ __name(invalidReasonProblem, "invalidReasonProblem");
793
+ function planCancellation(adapter, input, row, path) {
794
+ if (!adapter) return { status: null, reason: null, skus: [] };
795
+ const reason = resolveReason(adapter, input.reasonCode, row.cancellationReasons);
796
+ const invalid = invalidReasonProblem(adapter, reason, { code: input.reasonCode, stored: row.cancellationReasons }, path);
198
797
  if (invalid) return [invalid];
199
798
  const skus = [...new Set(input.offendingSkus ?? [])];
200
799
  const problems = skuProblems(reason, skus, row, path);
@@ -297,612 +896,244 @@ async function settleInboxEvent(ctx, id, outcome, error) {
297
896
  });
298
897
  }
299
898
  __name(settleInboxEvent, "settleInboxEvent");
300
- async function deferInboxEvent(ctx, id, reason) {
301
- if (!id) return;
302
- const db = await ctx.ports.db();
303
- await db.marketplaceInboxEvent.update({
304
- where: { id },
305
- data: { error: reason.slice(0, 500), attempts: { increment: 1 } }
306
- });
307
- }
308
- __name(deferInboxEvent, "deferInboxEvent");
309
- async function listRetryableInboxEvents(ctx) {
310
- const db = await ctx.ports.db();
311
- const rows = await db.marketplaceInboxEvent.findMany({
312
- where: {
313
- status: { in: ["PENDING", "FAILED"] },
314
- clientId: { not: null },
315
- attempts: { lt: ctx.ports.maxInboxAttempts }
316
- },
317
- orderBy: { receivedAt: "asc" },
318
- take: ctx.ports.reconcileBatchSize,
319
- select: { id: true, clientId: true, provider: true, payload: true, receivedAt: true }
320
- });
321
- return rows.map((row) => ({
322
- id: row.id,
323
- clientId: row.clientId,
324
- provider: row.provider,
325
- payload: row.payload,
326
- receivedAt: row.receivedAt
327
- }));
328
- }
329
- __name(listRetryableInboxEvents, "listRetryableInboxEvents");
330
-
331
- // src/core/marketplace-confirmed.ts
332
- var CONFIRMED_BEFORE_ORDER = "confirmed before its order";
333
- var NotClaimed = class extends Error {
334
- constructor(refusal) {
335
- super("not claimed");
336
- this.refusal = refusal;
337
- }
338
- refusal;
339
- static {
340
- __name(this, "NotClaimed");
341
- }
342
- };
343
- var CLEARED_FAILED_REQUEST = {
344
- cancellationStatus: null,
345
- cancellationReasonCode: null,
346
- cancellationOffendingSkus: null,
347
- cancellationFailureReason: null
348
- };
349
- async function claimConfirmed(ctx, clientId, held, now) {
350
- if (held.cancellationStatus === "PENDING" || held.cancellationStatus === "REQUESTED") return { accepted: false };
351
- try {
352
- await ctx.ports.transaction(async (tx) => {
353
- const answer = await ctx.ports.order.admit({
354
- clientId,
355
- orderId: held.orderId,
356
- decision: "ACCEPT",
357
- admission: {},
358
- db: tx
359
- });
360
- if (!answer.admitted) throw new NotClaimed({ code: answer.code, message: answer.message });
361
- const claimed = await tx.marketplaceAcceptance.updateMany({
362
- where: { orderId: held.orderId, clientId, status: "AWAITING", ...NO_STANDING_REQUEST },
363
- data: {
364
- status: "ACCEPTED",
365
- acknowledgedAt: now,
366
- confirmedAt: now,
367
- ...held.cancellationStatus === "FAILED" ? CLEARED_FAILED_REQUEST : {}
368
- }
369
- });
370
- if (claimed.count === 0) throw new NotClaimed(null);
371
- });
372
- return { accepted: true };
373
- } catch (error) {
374
- if (!(error instanceof NotClaimed)) throw error;
375
- return error.refusal ? { accepted: false, refusal: error.refusal } : { accepted: false };
376
- }
377
- }
378
- __name(claimConfirmed, "claimConfirmed");
379
- async function tellAccepted(ctx, clientId, orderId) {
380
- try {
381
- await ctx.ports.order.onAccepted(clientId, orderId);
382
- } catch (error) {
383
- ctx.ports.logger.error(
384
- `marketplace.confirmed: order ${orderId} is ACCEPTED but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
385
- );
386
- }
387
- }
388
- __name(tellAccepted, "tellAccepted");
389
- async function confirmHeld(ctx, inboxId, clientId, held) {
390
- const now = ctx.ports.clock.now();
391
- const db = await ctx.ports.db();
392
- await db.marketplaceAcceptance.updateMany({
393
- where: { orderId: held.orderId, clientId, status: "AWAITING", confirmedAt: null },
394
- data: { confirmedAt: now }
395
- });
396
- const claim3 = await claimConfirmed(ctx, clientId, held, now);
397
- const note = claim3.accepted ? void 0 : `accepted on the marketplace; waits for a person${claim3.refusal ? ` (${claim3.refusal.code})` : ""}`;
398
- await settleInboxEvent(ctx, inboxId, "PROCESSED", note);
399
- if (claim3.accepted) await tellAccepted(ctx, clientId, held.orderId);
400
- ctx.ports.publishChanged(clientId);
401
- return { kind: "confirmedByMarketplace", orderId: held.orderId, ...claim3 };
402
- }
403
- __name(confirmHeld, "confirmHeld");
404
- async function applyMarketplaceConfirmation(ctx, inboxId, clientId, event) {
405
- if (!event.marketplaceConfirmed || !event.externalOrderId) return null;
406
- const db = await ctx.ports.db();
407
- const held = await db.marketplaceAcceptance.findFirst({
408
- where: { clientId, provider: event.provider, externalOrderId: event.externalOrderId },
409
- select: { orderId: true, status: true, cancellationStatus: true }
410
- });
411
- if (!held) {
412
- await deferInboxEvent(ctx, inboxId, CONFIRMED_BEFORE_ORDER);
413
- return { kind: "ignored", reason: CONFIRMED_BEFORE_ORDER };
414
- }
415
- if (held.status === "ACCEPTED") return confirmAccepted(ctx, inboxId, clientId, held.orderId);
416
- if (held.status !== "AWAITING") {
417
- const reason = `the order is ${held.status}, not AWAITING`;
418
- await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
419
- return { kind: "ignored", reason };
420
- }
421
- return confirmHeld(ctx, inboxId, clientId, held);
422
- }
423
- __name(applyMarketplaceConfirmation, "applyMarketplaceConfirmation");
424
- async function confirmAccepted(ctx, inboxId, clientId, orderId) {
425
- const db = await ctx.ports.db();
426
- const stamped = await db.marketplaceAcceptance.updateMany({
427
- where: { orderId, clientId, status: "ACCEPTED", confirmedAt: null },
428
- data: { confirmedAt: ctx.ports.clock.now(), confirmFailedAt: null }
429
- });
430
- if (stamped.count === 0) {
431
- const reason = "the order is ACCEPTED and its confirm already stamped";
432
- await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
433
- return { kind: "ignored", reason };
434
- }
435
- await settleInboxEvent(ctx, inboxId, "PROCESSED", "accepted here first; the marketplace took the acceptance");
436
- ctx.ports.publishChanged(clientId);
437
- return { kind: "confirmedByMarketplace", orderId, accepted: true };
438
- }
439
- __name(confirmAccepted, "confirmAccepted");
440
- async function applyRows(ctx, rows) {
441
- const applied = /* @__PURE__ */ new Set();
442
- for (const row of rows) {
443
- const event = ctx.registry.get(row.provider)?.normalize(row.payload) ?? null;
444
- if (!event?.marketplaceConfirmed) continue;
445
- const outcome = await applyMarketplaceConfirmation(ctx, row.id, row.clientId, event);
446
- if (outcome?.kind === "confirmedByMarketplace") applied.add(outcome.orderId);
447
- }
448
- return applied;
449
- }
450
- __name(applyRows, "applyRows");
451
- var DEFERRED_SELECT = { id: true, clientId: true, provider: true, externalOrderId: true, payload: true };
452
- async function applyDeferredConfirmations(ctx, input) {
453
- if (!ctx.registry.get(input.provider)?.capabilities.marketplaceConfirms) return;
899
+ async function deferInboxEvent(ctx, id, reason) {
900
+ if (!id) return;
454
901
  const db = await ctx.ports.db();
455
- const rows = await db.marketplaceInboxEvent.findMany({
456
- where: { ...input, status: "PENDING", error: CONFIRMED_BEFORE_ORDER },
457
- select: DEFERRED_SELECT
902
+ await db.marketplaceInboxEvent.update({
903
+ where: { id },
904
+ data: { error: reason.slice(0, 500), attempts: { increment: 1 } }
458
905
  });
459
- await applyRows(ctx, rows);
460
906
  }
461
- __name(applyDeferredConfirmations, "applyDeferredConfirmations");
462
- async function applyOwedConfirmations(ctx, lapsed) {
463
- if (lapsed.length === 0) return /* @__PURE__ */ new Set();
907
+ __name(deferInboxEvent, "deferInboxEvent");
908
+ async function listRetryableInboxEvents(ctx) {
464
909
  const db = await ctx.ports.db();
465
910
  const rows = await db.marketplaceInboxEvent.findMany({
466
911
  where: {
467
- status: "PENDING",
468
- error: CONFIRMED_BEFORE_ORDER,
912
+ status: { in: ["PENDING", "FAILED"] },
469
913
  clientId: { not: null },
470
- externalOrderId: { in: [...new Set(lapsed.map((row) => row.externalOrderId))] }
914
+ attempts: { lt: ctx.ports.maxInboxAttempts }
471
915
  },
472
- select: DEFERRED_SELECT
916
+ orderBy: { receivedAt: "asc" },
917
+ take: ctx.ports.reconcileBatchSize,
918
+ select: { id: true, clientId: true, provider: true, payload: true, receivedAt: true }
473
919
  });
474
- const named = new Set(lapsed.map((row) => `${row.provider}:${row.externalOrderId}`));
475
- return applyRows(ctx, rows.filter((row) => named.has(`${row.provider}:${row.externalOrderId ?? ""}`)));
920
+ return rows.map((row) => ({
921
+ id: row.id,
922
+ clientId: row.clientId,
923
+ provider: row.provider,
924
+ payload: row.payload,
925
+ receivedAt: row.receivedAt
926
+ }));
476
927
  }
477
- __name(applyOwedConfirmations, "applyOwedConfirmations");
928
+ __name(listRetryableInboxEvents, "listRetryableInboxEvents");
478
929
 
479
- // src/core/merchant-claim.ts
480
- var MarketplaceMerchantTakenError = class extends Error {
481
- static {
482
- __name(this, "MarketplaceMerchantTakenError");
930
+ // src/core/marketplace-confirmed.ts
931
+ var CONFIRMED_BEFORE_ORDER = "confirmed before its order";
932
+ var NotClaimed = class extends Error {
933
+ constructor(refusal) {
934
+ super("not claimed");
935
+ this.refusal = refusal;
483
936
  }
484
- code = "MERCHANT_TAKEN";
485
- /** The field the refusal is about, as a problem path. */
486
- path = ["externalMerchantId"];
487
- constructor(provider, merchantId) {
488
- super(`The ${provider} merchant ${merchantId} is already held by another store's live connection.`);
489
- this.name = "MarketplaceMerchantTakenError";
937
+ refusal;
938
+ static {
939
+ __name(this, "NotClaimed");
490
940
  }
491
941
  };
492
- function isUniqueViolation(error) {
493
- const code = error?.code;
494
- return code === "P2002" || code === "23505";
495
- }
496
- __name(isUniqueViolation, "isUniqueViolation");
497
- async function merchantHeldElsewhere(db, clientId, provider, merchantId) {
498
- const rows = await db.marketplaceIntegration.findMany({
499
- where: { provider, externalMerchantId: merchantId, archivedAt: null },
500
- select: { clientId: true }
501
- });
502
- return rows.some((row) => row.clientId !== clientId);
503
- }
504
- __name(merchantHeldElsewhere, "merchantHeldElsewhere");
505
- async function assertMerchantFree(db, clientId, provider, merchantId) {
506
- if (merchantId && await merchantHeldElsewhere(db, clientId, provider, merchantId)) {
507
- throw new MarketplaceMerchantTakenError(provider, merchantId);
508
- }
509
- }
510
- __name(assertMerchantFree, "assertMerchantFree");
511
- async function guardMerchantClaim(ctx, claim3, write2) {
942
+ var CLEARED_FAILED_REQUEST = {
943
+ cancellationStatus: null,
944
+ cancellationReasonCode: null,
945
+ cancellationOffendingSkus: null,
946
+ cancellationFailureReason: null
947
+ };
948
+ async function claimConfirmed(ctx, clientId, held, now) {
949
+ if (held.cancellationStatus === "PENDING" || held.cancellationStatus === "REQUESTED") return { accepted: false };
512
950
  try {
513
- return await write2();
951
+ await ctx.ports.transaction(async (tx) => {
952
+ const answer = await ctx.ports.order.admit({
953
+ clientId,
954
+ orderId: held.orderId,
955
+ decision: "ACCEPT",
956
+ admission: {},
957
+ db: tx
958
+ });
959
+ if (!answer.admitted) throw new NotClaimed({ code: answer.code, message: answer.message });
960
+ const claimed = await tx.marketplaceAcceptance.updateMany({
961
+ where: { orderId: held.orderId, clientId, status: "AWAITING", ...NO_STANDING_REQUEST },
962
+ data: {
963
+ status: "ACCEPTED",
964
+ acknowledgedAt: now,
965
+ confirmedAt: now,
966
+ ...held.cancellationStatus === "FAILED" ? CLEARED_FAILED_REQUEST : {}
967
+ }
968
+ });
969
+ if (claimed.count === 0) throw new NotClaimed(null);
970
+ });
971
+ return { accepted: true };
514
972
  } catch (error) {
515
- const { merchantId } = claim3;
516
- if (!isUniqueViolation(error) || !merchantId) throw error;
517
- if (!await merchantHeldElsewhere(await ctx.ports.db(), claim3.clientId, claim3.provider, merchantId)) throw error;
518
- throw new MarketplaceMerchantTakenError(claim3.provider, merchantId);
519
- }
520
- }
521
- __name(guardMerchantClaim, "guardMerchantClaim");
522
- async function resolveTenantByMerchant(ctx, provider, externalMerchantId) {
523
- const db = await ctx.ports.db();
524
- const rows = await db.marketplaceIntegration.findMany({
525
- where: { provider, externalMerchantId, archivedAt: null },
526
- select: { clientId: true },
527
- take: 2
528
- });
529
- if (rows.length > 1) {
530
- ctx.ports.logger.warn(`marketplace: ${provider} merchant ${externalMerchantId} is held by several live connections`);
531
- return null;
532
- }
533
- return rows[0]?.clientId ?? null;
534
- }
535
- __name(resolveTenantByMerchant, "resolveTenantByMerchant");
536
-
537
- // src/core/outbound-queue.ts
538
- var MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
539
- function outboundDedupeKey(payload) {
540
- return `${MARKETPLACE_OUTBOUND_JOB}:${payload.action}:${payload.step ? `${payload.step}:` : ""}${payload.orderId}`;
541
- }
542
- __name(outboundDedupeKey, "outboundDedupeKey");
543
- function statusDedupeKey(step, orderId, at) {
544
- return `${MARKETPLACE_OUTBOUND_JOB}:status:${step}:${orderId}:${at.getTime()}`;
545
- }
546
- __name(statusDedupeKey, "statusDedupeKey");
547
- function ableTo(adapter, payload) {
548
- switch (payload.action) {
549
- case "status":
550
- return Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step));
551
- case "confirm":
552
- return adapter.capabilities.apiConfirm;
553
- default:
554
- return adapter.capabilities.apiCancel;
555
- }
556
- }
557
- __name(ableTo, "ableTo");
558
- async function enqueueOutbound(ctx, payload, provider, dedupeKey = outboundDedupeKey(payload)) {
559
- const adapter = ctx.registry.get(provider);
560
- if (!adapter) return false;
561
- if (!ableTo(adapter, payload)) return false;
562
- const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
563
- if (!outcome.enqueued) {
564
- ctx.ports.logger.warn(
565
- `${MARKETPLACE_OUTBOUND_JOB}: ${payload.action} for order ${payload.orderId} was not queued; the outbound sweep will re-queue it` + (outcome.reason ? ` (${outcome.reason})` : "")
566
- );
567
- }
568
- return outcome.enqueued;
569
- }
570
- __name(enqueueOutbound, "enqueueOutbound");
571
-
572
- // src/core/catalogue-category.ts
573
- var CLAIM_STALE_MS = 3 * 6e4;
574
- async function claim(table, key, row, now) {
575
- if (!row) {
576
- try {
577
- await table.create({ data: { ...key, claimedAt: now } });
578
- return true;
579
- } catch (error) {
580
- if (error.code === "P2002") return false;
581
- throw error;
582
- }
583
- }
584
- const stale = new Date(now.getTime() - CLAIM_STALE_MS);
585
- const moved = await table.updateMany({
586
- where: { ...key, externalId: null, OR: [{ claimedAt: null }, { claimedAt: { lt: stale } }] },
587
- data: { claimedAt: now }
588
- });
589
- return moved.count > 0;
590
- }
591
- __name(claim, "claim");
592
- async function release(table, key, claimedAt, id) {
593
- if (id !== null) {
594
- await table.updateMany({ where: { ...key, externalId: null }, data: { externalId: id, claimedAt: null } });
595
- return;
973
+ if (!(error instanceof NotClaimed)) throw error;
974
+ return error.refusal ? { accepted: false, refusal: error.refusal } : { accepted: false };
596
975
  }
597
- await table.updateMany({ where: { ...key, externalId: null, claimedAt }, data: { claimedAt: null } });
598
976
  }
599
- __name(release, "release");
600
- async function resolveCategory(ctx, connection, name, resolve, state = { waited: false }) {
601
- const table = (await ctx.ports.db()).marketplaceCatalogueCategory;
602
- if (!table) return resolve();
603
- const key = { clientId: connection.clientId, provider: connection.provider, name: name.trim() };
604
- const row = await table.findFirst({ where: key, select: { externalId: true } });
605
- if (row?.externalId) return { id: row.externalId };
606
- const now = ctx.ports.clock.now();
607
- if (!await claim(table, key, row, now)) {
608
- state.waited = true;
609
- return { kind: "retry", reason: `another publish is creating the category "${key.name}"` };
610
- }
611
- let result = { kind: "retry", reason: "the category was not resolved" };
977
+ __name(claimConfirmed, "claimConfirmed");
978
+ async function tellAccepted(ctx, clientId, orderId) {
612
979
  try {
613
- result = await resolve();
614
- } catch (error) {
615
- result = { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
616
- } finally {
617
- await release(table, key, now, "id" in result ? result.id : null);
618
- }
619
- return result;
620
- }
621
- __name(resolveCategory, "resolveCategory");
622
- async function forgetCategory(ctx, connection, name) {
623
- const table = (await ctx.ports.db()).marketplaceCatalogueCategory;
624
- if (!table) return;
625
- await table.updateMany({
626
- where: { clientId: connection.clientId, provider: connection.provider, name: name.trim() },
627
- data: { externalId: null, claimedAt: null }
628
- });
629
- }
630
- __name(forgetCategory, "forgetCategory");
631
-
632
- // src/core/link-store.ts
633
- function sealLink(ctx, refreshToken) {
634
- return ctx.ports.secrets.seal(JSON.stringify({ clientId: "", clientSecret: "", webhookSecret: null, refreshToken }));
635
- }
636
- __name(sealLink, "sealLink");
637
- function openLinkRefreshToken(ctx, sealed) {
638
- const parsed = JSON.parse(ctx.ports.secrets.open(sealed));
639
- const token = typeof parsed === "object" && parsed !== null ? parsed.refreshToken : null;
640
- if (typeof token !== "string" || token === "") throw new Error("The linked connection holds no refresh token.");
641
- return token;
642
- }
643
- __name(openLinkRefreshToken, "openLinkRefreshToken");
644
- async function appCredentialsOf(ctx, provider, environment) {
645
- const port = ctx.ports.appCredentials;
646
- if (!port) return null;
647
- const credentials = await port(provider, environment);
648
- return credentials && credentials.clientId !== "" && credentials.clientSecret !== "" ? credentials : null;
649
- }
650
- __name(appCredentialsOf, "appCredentialsOf");
651
- var linkTokenKey = /* @__PURE__ */ __name((provider, environment, clientId) => `LINK:${provider}:${environment}:${clientId}`, "linkTokenKey");
652
- async function cacheLinkToken(ctx, link, key, grant) {
653
- const db = await ctx.ports.db();
654
- const row = await db.marketplaceIntegration.findUnique({
655
- where: { clientId_provider: { clientId: link.clientId, provider: link.provider } },
656
- select: { credentials: true }
657
- });
658
- if (row?.credentials !== link.sealed) return false;
659
- setToken(ctx, key, grant);
660
- return true;
661
- }
662
- __name(cacheLinkToken, "cacheLinkToken");
663
- function setToken(ctx, key, grant) {
664
- const expiresAt = ctx.ports.clock.now().getTime() + Math.max(grant.expiresInSeconds, 1) * 1e3;
665
- ctx.tokens.set(key, { token: grant.accessToken, expiresAt });
980
+ await ctx.ports.order.onAccepted(clientId, orderId);
981
+ } catch (error) {
982
+ ctx.ports.logger.error(
983
+ `marketplace.confirmed: order ${orderId} is ACCEPTED but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
984
+ );
985
+ }
666
986
  }
667
- __name(setToken, "setToken");
668
- var inflight = /* @__PURE__ */ new WeakMap();
669
- async function storeRotated(ctx, link, refreshToken) {
987
+ __name(tellAccepted, "tellAccepted");
988
+ async function confirmHeld(ctx, inboxId, clientId, held) {
989
+ const now = ctx.ports.clock.now();
670
990
  const db = await ctx.ports.db();
671
- const { count } = await db.marketplaceIntegration.updateMany({
672
- where: { clientId: link.clientId, provider: link.provider, authMode: "LINKED", archivedAt: null, credentials: link.sealed },
673
- data: { credentials: sealLink(ctx, refreshToken) }
991
+ await db.marketplaceAcceptance.updateMany({
992
+ where: { orderId: held.orderId, clientId, status: "AWAITING", confirmedAt: null },
993
+ data: { confirmedAt: now }
674
994
  });
675
- return count > 0;
995
+ const claim3 = await claimConfirmed(ctx, clientId, held, now);
996
+ const note = claim3.accepted ? void 0 : `accepted on the marketplace; waits for a person${claim3.refusal ? ` (${claim3.refusal.code})` : ""}`;
997
+ await settleInboxEvent(ctx, inboxId, "PROCESSED", note);
998
+ if (claim3.accepted) await tellAccepted(ctx, clientId, held.orderId);
999
+ ctx.ports.publishChanged(clientId);
1000
+ return { kind: "confirmedByMarketplace", orderId: held.orderId, ...claim3 };
676
1001
  }
677
- __name(storeRotated, "storeRotated");
678
- async function markLinkFailed(ctx, link) {
1002
+ __name(confirmHeld, "confirmHeld");
1003
+ async function applyMarketplaceConfirmation(ctx, inboxId, clientId, event) {
1004
+ if (!event.marketplaceConfirmed || !event.externalOrderId) return null;
679
1005
  const db = await ctx.ports.db();
680
- const { count } = await db.marketplaceIntegration.updateMany({
681
- where: { clientId: link.clientId, provider: link.provider, authMode: "LINKED", credentials: link.sealed },
682
- data: { status: "FAILED" }
1006
+ const held = await db.marketplaceAcceptance.findFirst({
1007
+ where: { clientId, provider: event.provider, externalOrderId: event.externalOrderId },
1008
+ select: { orderId: true, status: true, cancellationStatus: true }
683
1009
  });
684
- if (count > 0) ctx.ports.publishChanged(link.clientId);
685
- return count > 0;
686
- }
687
- __name(markLinkFailed, "markLinkFailed");
688
- var RELINKED = { kind: "retry", reason: "the connection was linked again during the refresh" };
689
- async function refreshOnce(ctx, link, key) {
690
- const linking = ctx.registry.get(link.provider)?.linking;
691
- if (!linking) return { kind: "refused", status: 0, message: "this marketplace links no store", own: true };
692
- const answer = await linking.refresh(
693
- { http: ctx.ports.http, credentials: link.app, environment: link.environment, now: ctx.ports.clock.now() },
694
- { refreshToken: link.refreshToken }
695
- );
696
- if (answer.kind === "retry") return answer;
697
- if (answer.kind === "refused") return await markLinkFailed(ctx, link) ? { ...answer, own: true } : RELINKED;
698
- const rotated = answer.value.refreshToken;
699
- if (rotated === null || rotated === link.refreshToken) {
700
- return await cacheLinkToken(ctx, link, key, answer.value) ? { token: answer.value.accessToken } : RELINKED;
1010
+ if (!held) {
1011
+ await deferInboxEvent(ctx, inboxId, CONFIRMED_BEFORE_ORDER);
1012
+ return { kind: "ignored", reason: CONFIRMED_BEFORE_ORDER };
701
1013
  }
702
- const stored = await storeRotated(ctx, link, rotated).catch((error) => {
703
- ctx.ports.logger.error(
704
- `marketplace.link: ${link.provider} rotated refresh token of ${link.clientId} not stored: ` + (error instanceof Error ? error.message : String(error))
705
- );
706
- return null;
707
- });
708
- if (stored === false) return RELINKED;
709
- setToken(ctx, key, answer.value);
710
- return { token: answer.value.accessToken };
711
- }
712
- __name(refreshOnce, "refreshOnce");
713
- function linkGrant(ctx, link) {
714
- const key = linkTokenKey(link.provider, link.environment, link.clientId);
715
- return {
716
- key,
717
- accessToken: /* @__PURE__ */ __name(async () => {
718
- const cached = ctx.tokens.get(key);
719
- if (cached && cached.expiresAt > ctx.ports.clock.now().getTime()) return { token: cached.token };
720
- let running = inflight.get(ctx.tokens);
721
- if (!running) {
722
- running = /* @__PURE__ */ new Map();
723
- inflight.set(ctx.tokens, running);
724
- }
725
- const pending = running.get(key);
726
- if (pending) return pending;
727
- const call2 = refreshOnce(ctx, link, key).catch((error) => ({
728
- kind: "retry",
729
- reason: error instanceof Error ? error.message : String(error)
730
- })).finally(() => running.delete(key));
731
- running.set(key, call2);
732
- return call2;
733
- }, "accessToken")
734
- };
735
- }
736
- __name(linkGrant, "linkGrant");
737
-
738
- // src/core/integration.ts
739
- var VIEW_SELECT = {
740
- provider: true,
741
- enabled: true,
742
- environment: true,
743
- status: true,
744
- externalMerchantId: true,
745
- autoAccept: true,
746
- followStatus: true,
747
- ackSlaSeconds: true,
748
- credentials: true,
749
- lastEventAt: true,
750
- lastVerifiedAt: true,
751
- archivedAt: true,
752
- authMode: true
753
- };
754
- function toView(row) {
755
- return {
756
- provider: row.provider,
757
- enabled: row.enabled,
758
- environment: row.environment,
759
- status: row.status,
760
- externalMerchantId: row.externalMerchantId,
761
- autoAccept: row.autoAccept,
762
- followStatus: row.followStatus ?? true,
763
- ackSlaSeconds: row.ackSlaSeconds,
764
- connected: row.credentials !== "",
765
- lastEventAt: row.lastEventAt,
766
- lastVerifiedAt: row.lastVerifiedAt,
767
- archivedAt: row.archivedAt ?? null,
768
- authMode: row.authMode === "LINKED" ? "LINKED" : "CREDENTIALS"
769
- };
1014
+ if (held.status === "ACCEPTED") return confirmAccepted(ctx, inboxId, clientId, held.orderId);
1015
+ if (held.status !== "AWAITING") {
1016
+ const reason = `the order is ${held.status}, not AWAITING`;
1017
+ await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
1018
+ return { kind: "ignored", reason };
1019
+ }
1020
+ return confirmHeld(ctx, inboxId, clientId, held);
770
1021
  }
771
- __name(toView, "toView");
772
- async function listMarketplaceIntegrations(ctx, clientId, options = {}) {
1022
+ __name(applyMarketplaceConfirmation, "applyMarketplaceConfirmation");
1023
+ async function confirmAccepted(ctx, inboxId, clientId, orderId) {
773
1024
  const db = await ctx.ports.db();
774
- const rows = await db.marketplaceIntegration.findMany({
775
- where: {
776
- clientId,
777
- ...options.providers ? { provider: { in: [...options.providers] } } : {},
778
- ...options.includeArchived ? {} : { archivedAt: null }
779
- },
780
- select: VIEW_SELECT,
781
- orderBy: { provider: "asc" }
1025
+ const stamped = await db.marketplaceAcceptance.updateMany({
1026
+ where: { orderId, clientId, status: "ACCEPTED", confirmedAt: null },
1027
+ data: { confirmedAt: ctx.ports.clock.now(), confirmFailedAt: null }
782
1028
  });
783
- return rows.map(toView);
1029
+ if (stamped.count === 0) {
1030
+ const reason = "the order is ACCEPTED and its confirm already stamped";
1031
+ await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
1032
+ return { kind: "ignored", reason };
1033
+ }
1034
+ await settleInboxEvent(ctx, inboxId, "PROCESSED", "accepted here first; the marketplace took the acceptance");
1035
+ ctx.ports.publishChanged(clientId);
1036
+ return { kind: "confirmedByMarketplace", orderId, accepted: true };
784
1037
  }
785
- __name(listMarketplaceIntegrations, "listMarketplaceIntegrations");
786
- async function saveMarketplaceIntegration(ctx, input, db) {
787
- await assertMerchantFree(db, input.clientId, input.provider, input.externalMerchantId);
788
- const sealed = input.credentials ? ctx.ports.secrets.seal(JSON.stringify(input.credentials)) : void 0;
789
- const mutable = {
790
- ...input.enabled === void 0 ? {} : { enabled: input.enabled },
791
- ...input.environment === void 0 ? {} : { environment: input.environment },
792
- ...input.externalMerchantId === void 0 ? {} : { externalMerchantId: input.externalMerchantId },
793
- ...input.autoAccept === void 0 ? {} : { autoAccept: input.autoAccept },
794
- ...input.followStatus === void 0 ? {} : { followStatus: input.followStatus },
795
- ...input.ackSlaSeconds === void 0 ? {} : { ackSlaSeconds: input.ackSlaSeconds },
796
- // Typed credentials make the connection the store's own app again.
797
- ...sealed === void 0 ? {} : { credentials: sealed, status: "UNVERIFIED", authMode: "CREDENTIALS" }
798
- };
799
- const row = await db.marketplaceIntegration.upsert({
800
- where: { clientId_provider: { clientId: input.clientId, provider: input.provider } },
801
- create: {
802
- clientId: input.clientId,
803
- provider: input.provider,
804
- credentials: sealed ?? "",
805
- ackSlaSeconds: ctx.ports.defaultAckSlaSeconds,
806
- ...mutable
807
- },
808
- update: mutable,
809
- select: VIEW_SELECT
810
- });
811
- return toView(row);
1038
+ __name(confirmAccepted, "confirmAccepted");
1039
+ async function applyRows(ctx, rows) {
1040
+ const applied = /* @__PURE__ */ new Set();
1041
+ for (const row of rows) {
1042
+ const event = ctx.registry.get(row.provider)?.normalize(row.payload) ?? null;
1043
+ if (!event?.marketplaceConfirmed) continue;
1044
+ const outcome = await applyMarketplaceConfirmation(ctx, row.id, row.clientId, event);
1045
+ if (outcome?.kind === "confirmedByMarketplace") applied.add(outcome.orderId);
1046
+ }
1047
+ return applied;
812
1048
  }
813
- __name(saveMarketplaceIntegration, "saveMarketplaceIntegration");
814
- async function connectionMerchantId(ctx, clientId, provider) {
1049
+ __name(applyRows, "applyRows");
1050
+ var DEFERRED_SELECT = { id: true, clientId: true, provider: true, externalOrderId: true, payload: true };
1051
+ async function applyDeferredConfirmations(ctx, input) {
1052
+ if (!ctx.registry.get(input.provider)?.capabilities.marketplaceConfirms) return;
815
1053
  const db = await ctx.ports.db();
816
- const row = await db.marketplaceIntegration.findUnique({
817
- where: { clientId_provider: { clientId, provider } },
818
- select: { externalMerchantId: true, archivedAt: true }
1054
+ const rows = await db.marketplaceInboxEvent.findMany({
1055
+ where: { ...input, status: "PENDING", error: CONFIRMED_BEFORE_ORDER },
1056
+ select: DEFERRED_SELECT
819
1057
  });
820
- return row && !row.archivedAt ? row.externalMerchantId ?? null : null;
1058
+ await applyRows(ctx, rows);
821
1059
  }
822
- __name(connectionMerchantId, "connectionMerchantId");
823
- async function resolveIngestionTarget(ctx, clientId, provider) {
1060
+ __name(applyDeferredConfirmations, "applyDeferredConfirmations");
1061
+ async function applyOwedConfirmations(ctx, lapsed) {
1062
+ if (lapsed.length === 0) return /* @__PURE__ */ new Set();
824
1063
  const db = await ctx.ports.db();
825
- const row = await db.marketplaceIntegration.findUnique({
826
- where: { clientId_provider: { clientId, provider } },
827
- select: {
828
- enabled: true,
829
- autoAccept: true,
830
- followStatus: true,
831
- ackSlaSeconds: true,
832
- credentials: true,
833
- archivedAt: true,
834
- externalMerchantId: true,
835
- authMode: true,
836
- environment: true
837
- }
1064
+ const rows = await db.marketplaceInboxEvent.findMany({
1065
+ where: {
1066
+ status: "PENDING",
1067
+ error: CONFIRMED_BEFORE_ORDER,
1068
+ clientId: { not: null },
1069
+ externalOrderId: { in: [...new Set(lapsed.map((row) => row.externalOrderId))] }
1070
+ },
1071
+ select: DEFERRED_SELECT
838
1072
  });
839
- if (!row || row.archivedAt) return null;
840
- return {
841
- enabled: row.enabled,
842
- autoAccept: row.autoAccept,
843
- followStatus: row.followStatus ?? true,
844
- ackSlaSeconds: row.ackSlaSeconds,
845
- externalMerchantId: row.externalMerchantId ?? null,
846
- // An unopenable blob must not read as "no secret configured" — that would
847
- // turn a key-rotation problem into an endpoint that accepts unsigned
848
- // deliveries. The secrets port throws instead, and the caller answers 401.
849
- webhookSecret: await webhookSecretOf(ctx, provider, row)
850
- };
851
- }
852
- __name(resolveIngestionTarget, "resolveIngestionTarget");
853
- async function webhookSecretOf(ctx, provider, row) {
854
- if (row.authMode !== "LINKED") {
855
- return row.credentials === "" ? null : openCredentials(ctx, row.credentials).webhookSecret;
856
- }
857
- const app = await appCredentialsOf(ctx, provider, environmentOf(row.environment));
858
- if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
859
- const secret = app.webhookSecret || app.clientSecret;
860
- if (!secret) throw new Error(`No webhook key is configured for ${provider}.`);
861
- return secret;
1073
+ const named = new Set(lapsed.map((row) => `${row.provider}:${row.externalOrderId}`));
1074
+ return applyRows(ctx, rows.filter((row) => named.has(`${row.provider}:${row.externalOrderId ?? ""}`)));
862
1075
  }
863
- __name(webhookSecretOf, "webhookSecretOf");
864
- var environmentOf = /* @__PURE__ */ __name((value) => value === "PRODUCTION" ? "PRODUCTION" : "SANDBOX", "environmentOf");
865
- function openCredentials(ctx, sealed) {
866
- const parsed = JSON.parse(ctx.ports.secrets.open(sealed));
867
- if (typeof parsed !== "object" || parsed === null) {
868
- throw new Error("Stored marketplace credentials are not an object.");
1076
+ __name(applyOwedConfirmations, "applyOwedConfirmations");
1077
+
1078
+ // src/core/catalogue-category.ts
1079
+ var CLAIM_STALE_MS = 3 * 6e4;
1080
+ async function claim(table, key, row, now) {
1081
+ if (!row) {
1082
+ try {
1083
+ await table.create({ data: { ...key, claimedAt: now } });
1084
+ return true;
1085
+ } catch (error) {
1086
+ if (error.code === "P2002") return false;
1087
+ throw error;
1088
+ }
869
1089
  }
870
- const record = parsed;
871
- return {
872
- clientId: String(record.clientId ?? ""),
873
- clientSecret: String(record.clientSecret ?? ""),
874
- webhookSecret: record.webhookSecret ? String(record.webhookSecret) : null
875
- };
876
- }
877
- __name(openCredentials, "openCredentials");
878
- async function markMarketplaceEventSeen(db, clientId, provider, at) {
879
- await db.marketplaceIntegration.updateMany({
880
- where: { clientId, provider },
881
- data: { lastEventAt: at }
1090
+ const stale = new Date(now.getTime() - CLAIM_STALE_MS);
1091
+ const moved = await table.updateMany({
1092
+ where: { ...key, externalId: null, OR: [{ claimedAt: null }, { claimedAt: { lt: stale } }] },
1093
+ data: { claimedAt: now }
882
1094
  });
1095
+ return moved.count > 0;
883
1096
  }
884
- __name(markMarketplaceEventSeen, "markMarketplaceEventSeen");
885
- async function readOutboundConnection(ctx, clientId, provider) {
886
- return (await readSealedOutboundConnection(ctx, clientId, provider))?.connection ?? null;
1097
+ __name(claim, "claim");
1098
+ async function release(table, key, claimedAt, id) {
1099
+ if (id !== null) {
1100
+ await table.updateMany({ where: { ...key, externalId: null }, data: { externalId: id, claimedAt: null } });
1101
+ return;
1102
+ }
1103
+ await table.updateMany({ where: { ...key, externalId: null, claimedAt }, data: { claimedAt: null } });
887
1104
  }
888
- __name(readOutboundConnection, "readOutboundConnection");
889
- async function readSealedOutboundConnection(ctx, clientId, provider) {
890
- const db = await ctx.ports.db();
891
- const row = await db.marketplaceIntegration.findUnique({
892
- where: { clientId_provider: { clientId, provider } },
893
- select: { environment: true, credentials: true, authMode: true }
1105
+ __name(release, "release");
1106
+ async function resolveCategory(ctx, connection, name, resolve, state = { waited: false }) {
1107
+ const table = (await ctx.ports.db()).marketplaceCatalogueCategory;
1108
+ if (!table) return resolve();
1109
+ const key = { clientId: connection.clientId, provider: connection.provider, name: name.trim() };
1110
+ const row = await table.findFirst({ where: key, select: { externalId: true } });
1111
+ if (row?.externalId) return { id: row.externalId };
1112
+ const now = ctx.ports.clock.now();
1113
+ if (!await claim(table, key, row, now)) {
1114
+ state.waited = true;
1115
+ return { kind: "retry", reason: `another publish is creating the category "${key.name}"` };
1116
+ }
1117
+ let result = { kind: "retry", reason: "the category was not resolved" };
1118
+ try {
1119
+ result = await resolve();
1120
+ } catch (error) {
1121
+ result = { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
1122
+ } finally {
1123
+ await release(table, key, now, "id" in result ? result.id : null);
1124
+ }
1125
+ return result;
1126
+ }
1127
+ __name(resolveCategory, "resolveCategory");
1128
+ async function forgetCategory(ctx, connection, name) {
1129
+ const table = (await ctx.ports.db()).marketplaceCatalogueCategory;
1130
+ if (!table) return;
1131
+ await table.updateMany({
1132
+ where: { clientId: connection.clientId, provider: connection.provider, name: name.trim() },
1133
+ data: { externalId: null, claimedAt: null }
894
1134
  });
895
- if (!row || row.credentials === "") return null;
896
- const sealed = row.credentials;
897
- const environment = environmentOf(row.environment);
898
- if (row.authMode !== "LINKED") return { connection: { environment, credentials: openCredentials(ctx, sealed) }, sealed };
899
- const app = await appCredentialsOf(ctx, provider, environment);
900
- if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
901
- const refreshToken = openLinkRefreshToken(ctx, sealed);
902
- const link = { clientId, provider, environment, refreshToken, app, sealed };
903
- return { connection: { environment, credentials: app, grant: linkGrant(ctx, link) }, sealed };
904
1135
  }
905
- __name(readSealedOutboundConnection, "readSealedOutboundConnection");
1136
+ __name(forgetCategory, "forgetCategory");
906
1137
 
907
1138
  // src/core/catalogue-store.ts
908
1139
  var CATALOGUE_ROW_SELECT = {
@@ -1126,10 +1357,10 @@ async function runOnce(ctx, table, payload, attempt) {
1126
1357
  if (row.status !== WANTED[action]) return { kind: "skipped", reason: `the publication is ${row.status}, not ${WANTED[action]}` };
1127
1358
  const run = await runFor(ctx, row, action);
1128
1359
  if ("code" in run) return fail(ctx, table, row, action, { code: run.code, reason: null }, run.code);
1129
- return settle(ctx, table, row, action, run, attempt);
1360
+ return settle2(ctx, table, row, action, run, attempt);
1130
1361
  }
1131
1362
  __name(runOnce, "runOnce");
1132
- async function settle(ctx, table, row, action, run, attempt) {
1363
+ async function settle2(ctx, table, row, action, run, attempt) {
1133
1364
  const { result } = run;
1134
1365
  if (result.kind === "accepted" || result.kind === "published") {
1135
1366
  await stampSuccess(ctx, table, row, action, result, run.sentPriceCents);
@@ -1144,7 +1375,7 @@ async function settle(ctx, table, row, action, run, attempt) {
1144
1375
  if (result.kind === "retry" && run.waited) return waitedOut(ctx, row, action, detail);
1145
1376
  return fail(ctx, table, row, action, failureOf(result), detail);
1146
1377
  }
1147
- __name(settle, "settle");
1378
+ __name(settle2, "settle");
1148
1379
  function readRow(table, payload) {
1149
1380
  return table.findFirst({
1150
1381
  where: { id: payload.publicationId, clientId: payload.clientId },
@@ -1224,7 +1455,7 @@ async function runAcknowledge(ctx, payload, attempt) {
1224
1455
  { http: ctx.ports.http, tokens: ctx.tokens, now, ...connection },
1225
1456
  [...new Set(owed.map((row) => row.eventId))]
1226
1457
  );
1227
- return settle2(ctx, payload, owed, result, attempt);
1458
+ return settle3(ctx, payload, owed, result, attempt);
1228
1459
  }
1229
1460
  __name(runAcknowledge, "runAcknowledge");
1230
1461
  async function stampSettled(ctx, owed) {
@@ -1235,7 +1466,7 @@ async function stampSettled(ctx, owed) {
1235
1466
  });
1236
1467
  }
1237
1468
  __name(stampSettled, "stampSettled");
1238
- async function settle2(ctx, payload, owed, result, attempt) {
1469
+ async function settle3(ctx, payload, owed, result, attempt) {
1239
1470
  if (result.kind === "accepted") {
1240
1471
  await stampSettled(ctx, owed);
1241
1472
  return { kind: "done", acknowledged: owed.length };
@@ -1252,7 +1483,7 @@ async function settle2(ctx, payload, owed, result, attempt) {
1252
1483
  ctx.ports.logger.error(`${MARKETPLACE_ACKNOWLEDGE_JOB}: ${payload.provider} events of ${payload.clientId} not acknowledged: ${reason}`);
1253
1484
  return { kind: "failed", reason };
1254
1485
  }
1255
- __name(settle2, "settle");
1486
+ __name(settle3, "settle");
1256
1487
  async function sweepAcknowledgements(ctx) {
1257
1488
  const db = await ctx.ports.db();
1258
1489
  let requeued = 0;
@@ -1297,12 +1528,12 @@ var CancellationReasonsRetryError = class extends Error {
1297
1528
  };
1298
1529
  async function enqueueOrderReasons(ctx, input) {
1299
1530
  const adapter = ctx.registry.get(input.provider);
1300
- const deferred = input.deferredConfirmations === true && adapter?.capabilities.marketplaceConfirms === true;
1301
- if (!adapter?.orderCancellationReasons && !deferred) return;
1531
+ const deferred2 = input.deferredConfirmations === true && adapter?.capabilities.marketplaceConfirms === true;
1532
+ if (!adapter?.orderCancellationReasons && !deferred2) return;
1302
1533
  const payload = {
1303
1534
  clientId: input.clientId,
1304
1535
  orderId: input.orderId,
1305
- ...deferred ? { deferredConfirmations: true } : {}
1536
+ ...deferred2 ? { deferredConfirmations: true } : {}
1306
1537
  };
1307
1538
  const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_CANCELLATION_REASONS_JOB, payload, {
1308
1539
  dedupeKey: `${MARKETPLACE_CANCELLATION_REASONS_JOB}:${input.orderId}`
@@ -1371,6 +1602,337 @@ async function readOrderReasons(ctx, clientId, orderId) {
1371
1602
  }
1372
1603
  __name(readOrderReasons, "readOrderReasons");
1373
1604
 
1605
+ // src/core/dispute-store.ts
1606
+ var MARKETPLACE_DISPUTE_ANSWER_JOB = "marketplace.dispute-answer";
1607
+ async function disputeTable(ctx) {
1608
+ return (await ctx.ports.db()).marketplaceDispute ?? null;
1609
+ }
1610
+ __name(disputeTable, "disputeTable");
1611
+ function arrayOf(value, keep2) {
1612
+ return Array.isArray(value) ? value.filter(keep2) : [];
1613
+ }
1614
+ __name(arrayOf, "arrayOf");
1615
+ var isString = /* @__PURE__ */ __name((entry) => typeof entry === "string", "isString");
1616
+ var isReason = /* @__PURE__ */ __name((entry) => typeof entry?.code === "string" && typeof entry.description === "string", "isReason");
1617
+ var isItem = /* @__PURE__ */ __name((entry) => typeof entry?.name === "string", "isItem");
1618
+ var ALTERNATIVE_TYPES = /* @__PURE__ */ new Set(["REFUND", "BENEFIT", "ADDITIONAL_TIME"]);
1619
+ var isAlternative = /* @__PURE__ */ __name((entry) => typeof entry?.id === "string" && ALTERNATIVE_TYPES.has(entry.type), "isAlternative");
1620
+ function reasonsOf(value) {
1621
+ return arrayOf(value, isReason);
1622
+ }
1623
+ __name(reasonsOf, "reasonsOf");
1624
+ function alternativesOf(value) {
1625
+ return arrayOf(value, isAlternative);
1626
+ }
1627
+ __name(alternativesOf, "alternativesOf");
1628
+ function answerOf(row) {
1629
+ if (row.answer === null || row.answeredAt === null) return null;
1630
+ return {
1631
+ kind: row.answer,
1632
+ reasonCode: row.answerReasonCode,
1633
+ alternativeId: row.answerAlternativeId,
1634
+ amountCents: row.answerAmountCents,
1635
+ minutes: row.answerMinutes,
1636
+ at: row.answeredAt
1637
+ };
1638
+ }
1639
+ __name(answerOf, "answerOf");
1640
+ function settlementOf(row) {
1641
+ if (row.settlement === null || row.settledAt === null) return null;
1642
+ return { outcome: row.settlement, at: row.settledAt, amountCents: row.settledAmountCents };
1643
+ }
1644
+ __name(settlementOf, "settlementOf");
1645
+ function disputeView(row) {
1646
+ return {
1647
+ disputeId: row.disputeId,
1648
+ orderId: row.orderId,
1649
+ provider: row.provider,
1650
+ externalOrderId: row.externalOrderId,
1651
+ status: row.status,
1652
+ action: row.action,
1653
+ handshakeType: row.handshakeType,
1654
+ reason: row.reason,
1655
+ message: row.message,
1656
+ evidenceUrls: arrayOf(row.evidences, isString),
1657
+ items: arrayOf(row.items, isItem),
1658
+ requestedAmountCents: row.requestedAmountCents,
1659
+ expiresAt: row.expiresAt,
1660
+ openedAt: row.openedAt,
1661
+ timeoutAction: row.timeoutAction,
1662
+ alternatives: alternativesOf(row.alternatives),
1663
+ rejectReasons: reasonsOf(row.rejectReasons),
1664
+ answer: answerOf(row),
1665
+ failure: row.answerFailure,
1666
+ settlement: settlementOf(row)
1667
+ };
1668
+ }
1669
+ __name(disputeView, "disputeView");
1670
+ var LIVE = ["OPEN", "SENDING", "ANSWERED"];
1671
+ async function readDisputes(ctx, input) {
1672
+ const table = await disputeTable(ctx);
1673
+ if (!table) return [];
1674
+ const live = input.settledSince ? { OR: [{ status: { in: [...LIVE] } }, { settledAt: { gte: input.settledSince } }] } : {};
1675
+ const rows = await table.findMany({
1676
+ where: { clientId: input.clientId, ...input.orderIds ? { orderId: { in: [...input.orderIds] } } : {}, ...live },
1677
+ orderBy: { openedAt: "asc" }
1678
+ });
1679
+ return rows.map(disputeView);
1680
+ }
1681
+ __name(readDisputes, "readDisputes");
1682
+ async function findDispute(table, clientId, disputeId, orderId) {
1683
+ return await table.findFirst({ where: { clientId, disputeId, ...orderId === void 0 ? {} : { orderId } } });
1684
+ }
1685
+ __name(findDispute, "findDispute");
1686
+
1687
+ // src/core/disputes.ts
1688
+ async function heldOrder(ctx, clientId, event) {
1689
+ const db = await ctx.ports.db();
1690
+ return await db.marketplaceAcceptance.findFirst({
1691
+ where: { clientId, provider: event.provider, externalOrderId: event.externalOrderId },
1692
+ select: { orderId: true }
1693
+ });
1694
+ }
1695
+ __name(heldOrder, "heldOrder");
1696
+ async function tellHost(ctx, clientId, orderId, change) {
1697
+ ctx.ports.publishChanged(clientId);
1698
+ const hook = ctx.ports.order.onDispute;
1699
+ if (!hook) return;
1700
+ try {
1701
+ await hook.call(ctx.ports.order, clientId, orderId, change);
1702
+ } catch (error) {
1703
+ ctx.ports.logger.error(`marketplace.dispute: the host's onDispute failed for order ${orderId}`, error);
1704
+ }
1705
+ }
1706
+ __name(tellHost, "tellHost");
1707
+ function openedData(clientId, orderId, event, dispute, now) {
1708
+ return {
1709
+ clientId,
1710
+ orderId,
1711
+ provider: event.provider,
1712
+ externalOrderId: event.externalOrderId,
1713
+ disputeId: dispute.disputeId,
1714
+ status: "OPEN",
1715
+ action: dispute.action,
1716
+ handshakeType: dispute.handshakeType,
1717
+ reason: dispute.reason,
1718
+ message: dispute.message,
1719
+ evidences: dispute.evidenceUrls,
1720
+ items: dispute.items,
1721
+ requestedAmountCents: dispute.requestedAmountCents,
1722
+ expiresAt: dispute.expiresAt,
1723
+ openedAt: dispute.openedAt ?? now,
1724
+ timeoutAction: dispute.timeoutAction,
1725
+ alternatives: dispute.alternatives,
1726
+ rejectReasons: dispute.rejectReasons,
1727
+ acceptReasons: dispute.acceptReasons
1728
+ };
1729
+ }
1730
+ __name(openedData, "openedData");
1731
+ async function keepOpened(ctx, clientId, order, event, dispute) {
1732
+ const table = await disputeTable(ctx);
1733
+ if (!table) throw new Error("marketplace disputes need migration 20261203190000_marketplace_disputes");
1734
+ const existing = await table.findFirst({ where: { provider: event.provider, disputeId: dispute.disputeId } });
1735
+ if (existing) return "unchanged";
1736
+ await table.create({ data: openedData(clientId, order.orderId, event, dispute, ctx.ports.clock.now()) });
1737
+ return "opened";
1738
+ }
1739
+ __name(keepOpened, "keepOpened");
1740
+ async function keepSettled(ctx, clientId, event, settlement) {
1741
+ const table = await disputeTable(ctx);
1742
+ const row = table ? await findDispute(table, clientId, settlement.disputeId) : null;
1743
+ if (!table || !row || row.provider !== event.provider) return null;
1744
+ if (row.status === "SETTLED") return { orderId: row.orderId, changed: false };
1745
+ await table.updateMany({
1746
+ where: { id: row.id },
1747
+ data: {
1748
+ status: "SETTLED",
1749
+ settlement: settlement.outcome,
1750
+ settledAt: settlement.at ?? ctx.ports.clock.now(),
1751
+ settledAmountCents: settlement.amountCents
1752
+ }
1753
+ });
1754
+ return { orderId: row.orderId, changed: true };
1755
+ }
1756
+ __name(keepSettled, "keepSettled");
1757
+ async function deferred(ctx, inboxId, reason) {
1758
+ await deferInboxEvent(ctx, inboxId, reason);
1759
+ return { kind: "ignored", reason };
1760
+ }
1761
+ __name(deferred, "deferred");
1762
+ async function applyDisputeEvent(ctx, inboxId, clientId, event) {
1763
+ const dispute = event.dispute;
1764
+ if (!dispute || !event.externalOrderId) return null;
1765
+ if (dispute.kind === "settled") {
1766
+ const settled = await keepSettled(ctx, clientId, event, dispute.settlement);
1767
+ if (!settled) return deferred(ctx, inboxId, "settlement before its dispute");
1768
+ await settleInboxEvent(ctx, inboxId, "PROCESSED");
1769
+ const disputeId2 = dispute.settlement.disputeId;
1770
+ if (settled.changed) await tellHost(ctx, clientId, settled.orderId, { kind: "settled", disputeId: disputeId2 });
1771
+ return { kind: "dispute", orderId: settled.orderId, disputeId: disputeId2, change: settled.changed ? "settled" : "unchanged" };
1772
+ }
1773
+ const order = await heldOrder(ctx, clientId, event);
1774
+ if (!order) return deferred(ctx, inboxId, "dispute before its order");
1775
+ const change = await keepOpened(ctx, clientId, order, event, dispute.dispute);
1776
+ await settleInboxEvent(ctx, inboxId, "PROCESSED");
1777
+ const disputeId = dispute.dispute.disputeId;
1778
+ if (change === "opened") await tellHost(ctx, clientId, order.orderId, { kind: "opened", disputeId });
1779
+ return { kind: "dispute", orderId: order.orderId, disputeId, change };
1780
+ }
1781
+ __name(applyDisputeEvent, "applyDisputeEvent");
1782
+ var NONE = { answerReasonCode: null, answerAlternativeId: null, answerAmountCents: null, answerMinutes: null };
1783
+ function isPositiveInteger(value) {
1784
+ return typeof value === "number" && Number.isInteger(value) && value > 0;
1785
+ }
1786
+ __name(isPositiveInteger, "isPositiveInteger");
1787
+ function judgeAlternative(alternative, input) {
1788
+ const base = { ...NONE, answer: "ALTERNATIVE", answerAlternativeId: alternative.id };
1789
+ if (alternative.type === "ADDITIONAL_TIME") {
1790
+ const minutes = input.minutes;
1791
+ if (!isPositiveInteger(minutes)) return "INVALID_MINUTES";
1792
+ if (alternative.allowedMinutes.length > 0 && !alternative.allowedMinutes.includes(minutes)) return "INVALID_MINUTES";
1793
+ return { ...base, answerMinutes: minutes };
1794
+ }
1795
+ const amount = input.amountCents;
1796
+ if (!isPositiveInteger(amount)) return "INVALID_AMOUNT";
1797
+ if (alternative.maxAmountCents !== null && amount > alternative.maxAmountCents) return "INVALID_AMOUNT";
1798
+ return { ...base, answerAmountCents: amount };
1799
+ }
1800
+ __name(judgeAlternative, "judgeAlternative");
1801
+ function judgeAnswer(row, input) {
1802
+ if (input.kind === "ACCEPT") {
1803
+ return { ...NONE, answer: "ACCEPT", answerReasonCode: reasonsOf(row.acceptReasons)[0]?.code ?? null };
1804
+ }
1805
+ if (input.kind === "REJECT") {
1806
+ const known = reasonsOf(row.rejectReasons).some((reason) => reason.code === input.reasonCode);
1807
+ return known ? { ...NONE, answer: "REJECT", answerReasonCode: input.reasonCode } : "INVALID_REASON";
1808
+ }
1809
+ const alternative = alternativesOf(row.alternatives).find((entry) => entry.id === input.alternativeId);
1810
+ return alternative ? judgeAlternative(alternative, input) : "INVALID_ALTERNATIVE";
1811
+ }
1812
+ __name(judgeAnswer, "judgeAnswer");
1813
+ function closedFor(ctx, row, now) {
1814
+ if (row.status !== "OPEN") return "ALREADY_ANSWERED";
1815
+ if (row.expiresAt !== null && now.getTime() >= row.expiresAt.getTime()) return "EXPIRED";
1816
+ return ctx.registry.get(row.provider)?.disputes ? null : "UNSUPPORTED";
1817
+ }
1818
+ __name(closedFor, "closedFor");
1819
+ async function enqueueDisputeAnswer(ctx, row, key) {
1820
+ const outcome = await ctx.ports.enqueue.enqueue(
1821
+ MARKETPLACE_DISPUTE_ANSWER_JOB,
1822
+ { clientId: row.clientId, disputeId: row.disputeId },
1823
+ { dedupeKey: `${MARKETPLACE_DISPUTE_ANSWER_JOB}:${row.disputeId}:${key}` }
1824
+ );
1825
+ if (!outcome.enqueued) {
1826
+ ctx.ports.logger.warn(`${MARKETPLACE_DISPUTE_ANSWER_JOB}: dispute ${row.disputeId} not queued; the sweep re-queues it` + (outcome.reason ? ` (${outcome.reason})` : ""));
1827
+ }
1828
+ return outcome.enqueued;
1829
+ }
1830
+ __name(enqueueDisputeAnswer, "enqueueDisputeAnswer");
1831
+ async function answerDispute(ctx, input) {
1832
+ const now = input.now ?? ctx.ports.clock.now();
1833
+ const table = await disputeTable(ctx);
1834
+ const row = table ? await findDispute(table, input.clientId, input.disputeId, input.orderId) : null;
1835
+ if (!table || !row) return { kind: "refused", code: "NOT_FOUND" };
1836
+ const closed = closedFor(ctx, row, now);
1837
+ if (closed) return { kind: "refused", code: closed };
1838
+ const judged = judgeAnswer(row, input.answer);
1839
+ if (typeof judged === "string") return { kind: "refused", code: judged };
1840
+ const data = { ...judged, status: "SENDING", answeredAt: now, answerFailure: null };
1841
+ const claimed = await table.updateMany({ where: { id: row.id, status: "OPEN" }, data });
1842
+ if (claimed.count === 0) return { kind: "refused", code: "ALREADY_ANSWERED" };
1843
+ await enqueueDisputeAnswer(ctx, row, String(now.getTime()));
1844
+ ctx.ports.publishChanged(input.clientId);
1845
+ return { kind: "queued", dispute: disputeView({ ...row, ...data }) };
1846
+ }
1847
+ __name(answerDispute, "answerDispute");
1848
+
1849
+ // src/core/dispute-job.ts
1850
+ var DisputeAnswerRetryError = class extends Error {
1851
+ static {
1852
+ __name(this, "DisputeAnswerRetryError");
1853
+ }
1854
+ constructor(message) {
1855
+ super(message);
1856
+ this.name = "DisputeAnswerRetryError";
1857
+ }
1858
+ };
1859
+ function answerToSend(row) {
1860
+ if (row.answer === "ACCEPT") return { kind: "ACCEPT", reasonCode: row.answerReasonCode };
1861
+ if (row.answer === "REJECT") return row.answerReasonCode ? { kind: "REJECT", reasonCode: row.answerReasonCode } : null;
1862
+ const alternative = alternativesOf(row.alternatives).find((entry) => entry.id === row.answerAlternativeId);
1863
+ if (row.answer !== "ALTERNATIVE" || !alternative) return null;
1864
+ return { kind: "ALTERNATIVE", alternative, amountCents: row.answerAmountCents, minutes: row.answerMinutes };
1865
+ }
1866
+ __name(answerToSend, "answerToSend");
1867
+ async function giveBack(ctx, table, row, code) {
1868
+ await table.updateMany({
1869
+ where: { id: row.id, status: "SENDING" },
1870
+ data: {
1871
+ status: "OPEN",
1872
+ answerFailure: code,
1873
+ answer: null,
1874
+ answerReasonCode: null,
1875
+ answerAlternativeId: null,
1876
+ answerAmountCents: null,
1877
+ answerMinutes: null,
1878
+ answeredAt: null
1879
+ }
1880
+ });
1881
+ ctx.ports.logger.warn(`${MARKETPLACE_DISPUTE_ANSWER_JOB}: dispute ${row.disputeId} not answered: ${code}`);
1882
+ ctx.ports.publishChanged(row.clientId);
1883
+ return { kind: "failed", code };
1884
+ }
1885
+ __name(giveBack, "giveBack");
1886
+ async function stampAnswered(ctx, table, row, failure) {
1887
+ await table.updateMany({ where: { id: row.id, status: "SENDING" }, data: { status: "ANSWERED", answerFailure: failure } });
1888
+ ctx.ports.publishChanged(row.clientId);
1889
+ return { kind: "answered" };
1890
+ }
1891
+ __name(stampAnswered, "stampAnswered");
1892
+ async function settleSend(ctx, table, row, result, attempt) {
1893
+ if (result.kind === "accepted") return stampAnswered(ctx, table, row, null);
1894
+ if (result.kind === "refused") {
1895
+ return result.code === "ALREADY_ANSWERED" ? stampAnswered(ctx, table, row, "ALREADY_ANSWERED") : giveBack(ctx, table, row, result.code);
1896
+ }
1897
+ if (attempt.attempt < attempt.maxAttempts) throw new DisputeAnswerRetryError(`dispute ${row.disputeId}: ${result.reason}`);
1898
+ return giveBack(ctx, table, row, "UNREACHABLE");
1899
+ }
1900
+ __name(settleSend, "settleSend");
1901
+ async function runDisputeAnswer(ctx, payload, attempt) {
1902
+ const table = await disputeTable(ctx);
1903
+ const row = table ? await findDispute(table, payload.clientId, payload.disputeId) : null;
1904
+ if (!table || !row || row.status !== "SENDING") return { kind: "skipped", reason: "no answer to send" };
1905
+ const api = ctx.registry.get(row.provider)?.disputes;
1906
+ const answer = answerToSend(row);
1907
+ if (!api || !answer) return giveBack(ctx, table, row, "UNSUPPORTED");
1908
+ const connection = await readOutboundConnection(ctx, row.clientId, row.provider).catch(() => null);
1909
+ if (!connection) return giveBack(ctx, table, row, "NOT_CONNECTED");
1910
+ const call2 = { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection };
1911
+ const result = await api.answer(call2, { externalOrderId: row.externalOrderId, disputeId: row.disputeId }, answer);
1912
+ return settleSend(ctx, table, row, result, attempt);
1913
+ }
1914
+ __name(runDisputeAnswer, "runDisputeAnswer");
1915
+ var SWEEP_BATCH = 100;
1916
+ var DISPUTE_STALE_MS = 10 * 6e4;
1917
+ var DISPUTE_GIVE_UP_MS = 24 * 60 * 6e4;
1918
+ async function sweepDisputes(ctx, now) {
1919
+ const table = await disputeTable(ctx);
1920
+ if (!table) return { requeued: 0, givenUp: 0 };
1921
+ const stale = new Date(now.getTime() - DISPUTE_STALE_MS);
1922
+ const giveUp = new Date(now.getTime() - DISPUTE_GIVE_UP_MS);
1923
+ const rows = await table.findMany({ where: { status: "SENDING", answeredAt: { lt: stale } }, orderBy: { answeredAt: "asc" }, take: SWEEP_BATCH });
1924
+ let requeued = 0;
1925
+ let givenUp = 0;
1926
+ for (const row of rows) {
1927
+ if (row.answeredAt !== null && row.answeredAt.getTime() < giveUp.getTime()) {
1928
+ await giveBack(ctx, table, row, "UNREACHABLE");
1929
+ givenUp += 1;
1930
+ } else if (await enqueueDisputeAnswer(ctx, row, `sweep:${now.getTime()}`)) requeued += 1;
1931
+ }
1932
+ return { requeued, givenUp };
1933
+ }
1934
+ __name(sweepDisputes, "sweepDisputes");
1935
+
1374
1936
  // src/core/menu-links.ts
1375
1937
  var LINK_SELECT = {
1376
1938
  id: true,
@@ -1880,38 +2442,6 @@ async function sweepCatalogue(ctx, now) {
1880
2442
  }
1881
2443
  __name(sweepCatalogue, "sweepCatalogue");
1882
2444
 
1883
- // src/core/status-store.ts
1884
- function statusTable(db) {
1885
- return db.marketplaceStatusUpdate ?? null;
1886
- }
1887
- __name(statusTable, "statusTable");
1888
- async function readStatusRows(table, orderId, steps2) {
1889
- return await table.findMany({
1890
- where: { orderId, step: { in: [...steps2] } },
1891
- select: { orderId: true, step: true, source: true, state: true, claimKey: true }
1892
- });
1893
- }
1894
- __name(readStatusRows, "readStatusRows");
1895
- async function insertStatusRow(table, row) {
1896
- try {
1897
- await table.create({ data: row });
1898
- return true;
1899
- } catch (error) {
1900
- if (error.code === "P2002") return false;
1901
- throw error;
1902
- }
1903
- }
1904
- __name(insertStatusRow, "insertStatusRow");
1905
- async function noteMarketplaceStep(ctx, row) {
1906
- const table = statusTable(await ctx.ports.db());
1907
- if (table) await insertStatusRow(table, { ...row, source: "MARKETPLACE", state: "NOTED", claimKey: "" });
1908
- }
1909
- __name(noteMarketplaceStep, "noteMarketplaceStep");
1910
- async function settleStatusRow(table, where, state) {
1911
- return (await table.updateMany({ where: { ...where, state: "SENDING" }, data: { state } })).count;
1912
- }
1913
- __name(settleStatusRow, "settleStatusRow");
1914
-
1915
2445
  // src/core/outbound-sweep.ts
1916
2446
  var OUTBOUND_STALE_MS = 10 * 6e4;
1917
2447
  var OUTBOUND_GIVE_UP_MS = 24 * 60 * 6e4;
@@ -1924,14 +2454,15 @@ __name(sweepDedupeKey, "sweepDedupeKey");
1924
2454
  async function requeue(ctx, rows, action, now) {
1925
2455
  let queued = 0;
1926
2456
  for (const row of rows) {
2457
+ const logistics = row.step?.startsWith(LOGISTICS_ROW_PREFIX) === true;
1927
2458
  const payload = {
1928
2459
  clientId: row.clientId,
1929
2460
  orderId: row.orderId,
1930
- action,
1931
- ...row.step ? { step: row.step } : {},
2461
+ action: logistics ? "logistics" : action,
2462
+ ...logistics ? { logisticsStep: row.step.slice(LOGISTICS_ROW_PREFIX.length) } : row.step ? { step: row.step } : {},
1932
2463
  ...row.claimKey === void 0 ? {} : { claimKey: row.claimKey }
1933
2464
  };
1934
- if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now, row.step))) queued += 1;
2465
+ if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(payload.action, row.orderId, now, row.step))) queued += 1;
1935
2466
  }
1936
2467
  return queued;
1937
2468
  }
@@ -1986,7 +2517,7 @@ async function sweepStatus(ctx, now) {
1986
2517
  });
1987
2518
  const claimed = [];
1988
2519
  for (const row of owed) {
1989
- const fresh = `sweep:${now.getTime()}`;
2520
+ const fresh = `sweep:${now.getTime()}:${row.step}`;
1990
2521
  const taken = await table.updateMany({
1991
2522
  where: { orderId: row.orderId, step: row.step, state: "SENDING", claimKey: row.claimKey, updatedAt: { lt: stale } },
1992
2523
  data: { claimKey: fresh }
@@ -2021,7 +2552,13 @@ async function sweepOutbound(ctx, now) {
2021
2552
  if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} cancellation request(s).`);
2022
2553
  const catalogueRequeued = await sweepCatalogue(ctx, now);
2023
2554
  const status = await sweepStatus(ctx, now);
2024
- return { requeued: requeued + status.requeued, givenUp: givenUp + status.givenUp, timedOut, catalogueRequeued };
2555
+ const disputes = await sweepDisputes(ctx, now);
2556
+ return {
2557
+ requeued: requeued + status.requeued + disputes.requeued,
2558
+ givenUp: givenUp + status.givenUp + disputes.givenUp,
2559
+ timedOut,
2560
+ catalogueRequeued
2561
+ };
2025
2562
  }
2026
2563
  __name(sweepOutbound, "sweepOutbound");
2027
2564
 
@@ -2108,14 +2645,14 @@ function deliveredByOf(row) {
2108
2645
  return row.deliveredBy === "MERCHANT" || row.deliveredBy === "MARKETPLACE" ? row.deliveredBy : null;
2109
2646
  }
2110
2647
  __name(deliveredByOf, "deliveredByOf");
2111
- var skipped = /* @__PURE__ */ __name((reason) => ({ kind: "skipped", reason }), "skipped");
2648
+ var skipped2 = /* @__PURE__ */ __name((reason) => ({ kind: "skipped", reason }), "skipped");
2112
2649
  function acceptanceSkip(row) {
2113
2650
  if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
2114
2651
  const standing = row.cancellationStatus !== null && row.cancellationStatus !== "FAILED";
2115
2652
  return standing ? `a cancellation request is ${row.cancellationStatus}` : null;
2116
2653
  }
2117
2654
  __name(acceptanceSkip, "acceptanceSkip");
2118
- function confirmSkip(row, adapter, deps) {
2655
+ function confirmSkip2(row, adapter, deps) {
2119
2656
  if (!adapter.capabilities.statusAfterConfirm || row.confirmedAt) return null;
2120
2657
  if (row.confirmFailedAt) return "the marketplace never took the store's confirm";
2121
2658
  if (deps.attempt.attempt < deps.attempt.maxAttempts) {
@@ -2123,7 +2660,7 @@ function confirmSkip(row, adapter, deps) {
2123
2660
  }
2124
2661
  return "the store's confirm has not reached the marketplace";
2125
2662
  }
2126
- __name(confirmSkip, "confirmSkip");
2663
+ __name(confirmSkip2, "confirmSkip");
2127
2664
  async function adapterAndHostSkip(ctx, payload, step, row, adapter) {
2128
2665
  const takes = adapter.informStatus !== void 0 && adapter.capabilities.statusSteps?.includes(step) === true && adapter.statusSupported?.({ step, deliveredBy: deliveredByOf(row) }) !== false;
2129
2666
  if (!takes) return `the marketplace does not take ${step} for this order`;
@@ -2148,7 +2685,7 @@ function callAdapter(ctx, connection, adapter, row, step, ref) {
2148
2685
  });
2149
2686
  }
2150
2687
  __name(callAdapter, "callAdapter");
2151
- async function settle3(ctx, db, where, result, deps) {
2688
+ async function settle4(ctx, db, where, result, deps) {
2152
2689
  const table = statusTable(db);
2153
2690
  if (result.kind === "accepted") {
2154
2691
  await settleStatusRow(table, where, "SENT");
@@ -2162,7 +2699,7 @@ async function settle3(ctx, db, where, result, deps) {
2162
2699
  ctx.ports.logger.error(`${MARKETPLACE_OUTBOUND_JOB}: status ${where.step} for order ${where.orderId} failed: ${reason}`);
2163
2700
  return { kind: "failed", action: "status", reason };
2164
2701
  }
2165
- __name(settle3, "settle");
2702
+ __name(settle4, "settle");
2166
2703
  function ownsClaim(found, key) {
2167
2704
  return found.source === "STORE" && found.state === "SENDING" && found.claimKey === key;
2168
2705
  }
@@ -2188,24 +2725,24 @@ async function claim2(table, payload, row, step, key) {
2188
2725
  __name(claim2, "claim");
2189
2726
  async function runStatus(ctx, payload, row, adapter, deps) {
2190
2727
  const step = payload.step;
2191
- if (!step) return skipped("a status call names no step");
2192
- const stopped = acceptanceSkip(row) ?? confirmSkip(row, adapter, deps) ?? await adapterAndHostSkip(ctx, payload, step, row, adapter);
2193
- if (stopped) return skipped(stopped);
2728
+ if (!step) return skipped2("a status call names no step");
2729
+ const stopped = acceptanceSkip(row) ?? confirmSkip2(row, adapter, deps) ?? await adapterAndHostSkip(ctx, payload, step, row, adapter);
2730
+ if (stopped) return skipped2(stopped);
2194
2731
  const db = await ctx.ports.db();
2195
2732
  const table = statusTable(db);
2196
- if (!table) return skipped("the host has not composed the status model");
2733
+ if (!table) return skipped2("the host has not composed the status model");
2197
2734
  const connection = await connectionOf(ctx, payload.clientId, row.provider);
2198
2735
  if (typeof connection === "string") {
2199
2736
  ctx.ports.logger.info(`${MARKETPLACE_OUTBOUND_JOB}: status ${step} for order ${row.orderId} not sent: ${connection}`);
2200
- return skipped(connection);
2737
+ return skipped2(connection);
2201
2738
  }
2202
2739
  const key = payload.claimKey ?? "";
2203
2740
  const unclaimed = await claim2(table, payload, row, step, key);
2204
- if (unclaimed) return skipped(unclaimed);
2741
+ if (unclaimed) return skipped2(unclaimed);
2205
2742
  const before = await sendPrerequisite(ctx, { table, payload, row, step, key, connection, adapter }, deps);
2206
2743
  if (before) return before;
2207
2744
  const result = await callAdapter(ctx, connection, adapter, row, step, deps.ref);
2208
- return settle3(ctx, db, { orderId: row.orderId, step, claimKey: key }, result, deps);
2745
+ return settle4(ctx, db, { orderId: row.orderId, step, claimKey: key }, result, deps);
2209
2746
  }
2210
2747
  __name(runStatus, "runStatus");
2211
2748
  function prerequisiteState(found, key, run, first, deps) {
@@ -2214,7 +2751,7 @@ function prerequisiteState(found, key, run, first, deps) {
2214
2751
  if (deps.attempt.attempt < deps.attempt.maxAttempts) {
2215
2752
  throw deps.retryError(`status ${run.step} for order ${run.row.orderId}: waiting for ${first}, held by another run`);
2216
2753
  }
2217
- return skipped(`${first} is still being sent by another run`);
2754
+ return skipped2(`${first} is still being sent by another run`);
2218
2755
  }
2219
2756
  __name(prerequisiteState, "prerequisiteState");
2220
2757
  async function sendPrerequisite(ctx, run, deps) {
@@ -2231,7 +2768,7 @@ async function sendPrerequisite(ctx, run, deps) {
2231
2768
  if (!claimed) return sendPrerequisite(ctx, run, deps);
2232
2769
  }
2233
2770
  const result = await callAdapter(ctx, run.connection, run.adapter, run.row, first, deps.ref);
2234
- const outcome = await settle3(ctx, await ctx.ports.db(), { orderId: run.row.orderId, step: first, claimKey: key }, result, deps);
2771
+ const outcome = await settle4(ctx, await ctx.ports.db(), { orderId: run.row.orderId, step: first, claimKey: key }, result, deps);
2235
2772
  return outcome.kind === "skipped" ? outcome : null;
2236
2773
  }
2237
2774
  __name(sendPrerequisite, "sendPrerequisite");
@@ -2279,7 +2816,7 @@ function refOf(row) {
2279
2816
  };
2280
2817
  }
2281
2818
  __name(refOf, "refOf");
2282
- function confirmSkip2(row, adapter) {
2819
+ function confirmSkip3(row, adapter) {
2283
2820
  if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
2284
2821
  if (row.cancellationStatus !== null && row.cancellationStatus !== "FAILED") {
2285
2822
  return `a cancellation request is ${row.cancellationStatus}`;
@@ -2288,7 +2825,7 @@ function confirmSkip2(row, adapter) {
2288
2825
  if (!adapter.capabilities.apiConfirm) return "the marketplace has no confirm API";
2289
2826
  return null;
2290
2827
  }
2291
- __name(confirmSkip2, "confirmSkip");
2828
+ __name(confirmSkip3, "confirmSkip");
2292
2829
  async function stampConfirm(ctx, row, succeeded, now) {
2293
2830
  const db = await ctx.ports.db();
2294
2831
  await db.marketplaceAcceptance.updateMany({
@@ -2344,7 +2881,7 @@ async function connectionFor(ctx, clientId, provider) {
2344
2881
  }
2345
2882
  }
2346
2883
  __name(connectionFor, "connectionFor");
2347
- async function settle4(ctx, payload, row, result, attempt, succeed, fail3) {
2884
+ async function settle5(ctx, payload, row, result, attempt, succeed, fail3) {
2348
2885
  if (result.kind === "accepted") {
2349
2886
  await succeed();
2350
2887
  ctx.ports.publishChanged(payload.clientId);
@@ -2359,9 +2896,9 @@ async function settle4(ctx, payload, row, result, attempt, succeed, fail3) {
2359
2896
  ctx.ports.publishChanged(payload.clientId);
2360
2897
  return { kind: "failed", action: payload.action, reason };
2361
2898
  }
2362
- __name(settle4, "settle");
2899
+ __name(settle5, "settle");
2363
2900
  async function runConfirm(ctx, payload, row, adapter, attempt) {
2364
- const skip = confirmSkip2(row, adapter);
2901
+ const skip = confirmSkip3(row, adapter);
2365
2902
  if (skip) return { kind: "skipped", reason: skip };
2366
2903
  const now = ctx.ports.clock.now();
2367
2904
  const connection = await connectionFor(ctx, payload.clientId, row.provider);
@@ -2371,7 +2908,7 @@ async function runConfirm(ctx, payload, row, adapter, attempt) {
2371
2908
  // The stated preparation time, for a marketplace whose confirm takes one.
2372
2909
  { preparationMinutes: adapter.capabilities.confirmTakesPreparationTime ? row.preparationMinutes : null }
2373
2910
  );
2374
- return settle4(
2911
+ return settle5(
2375
2912
  ctx,
2376
2913
  payload,
2377
2914
  row,
@@ -2414,7 +2951,7 @@ async function runCancellation(ctx, payload, row, adapter, attempt) {
2414
2951
  );
2415
2952
  }
2416
2953
  const taken = adapter.capabilities.asyncCancellationOutcome ? "REQUESTED" : "CONFIRMED";
2417
- return settle4(
2954
+ return settle5(
2418
2955
  ctx,
2419
2956
  payload,
2420
2957
  row,
@@ -2460,6 +2997,7 @@ async function runOnce2(ctx, payload, attempt) {
2460
2997
  if (!adapter) return { kind: "skipped", reason: `no adapter for ${row.provider}` };
2461
2998
  const deps = { attempt, ref: refOf(row), retryError: /* @__PURE__ */ __name((m) => new OutboundRetryError(m), "retryError") };
2462
2999
  if (payload.action === "status") return runStatus(ctx, payload, row, adapter, deps);
3000
+ if (payload.action === "logistics") return runLogistics(ctx, payload, row, adapter, deps);
2463
3001
  if (payload.action === "validatePickupCode") return runPickupCode(ctx, payload, row, adapter, deps);
2464
3002
  return payload.action === "confirm" ? runConfirm(ctx, payload, row, adapter, attempt) : runCancellation(ctx, payload, row, adapter, attempt);
2465
3003
  }
@@ -2469,7 +3007,7 @@ async function runOutbound(ctx, payload, attempt) {
2469
3007
  return await runOnce2(ctx, payload, attempt);
2470
3008
  } catch (error) {
2471
3009
  if (error instanceof OutboundRetryError || attempt.attempt < attempt.maxAttempts) throw error;
2472
- return stampLastAttemptFailure(ctx, payload, error);
3010
+ return payload.action === "logistics" ? failLogisticsJob(ctx, payload, error) : stampLastAttemptFailure(ctx, payload, error);
2473
3011
  }
2474
3012
  }
2475
3013
  __name(runOutbound, "runOutbound");
@@ -2856,31 +3394,12 @@ async function runAvailability(ctx, payload, attempt) {
2856
3394
  __name(runAvailability, "runAvailability");
2857
3395
 
2858
3396
  export {
2859
- requestsFirst,
2860
- tellCancellationFailed,
2861
- MarketplaceAdapterRegistrationError,
2862
- createAdapterRegistry,
2863
- storedReasons,
2864
- reasonsForOrder,
2865
- resolveReason,
2866
- suggestReason,
2867
- NO_STANDING_REQUEST,
2868
- CLAIM_SELECT,
2869
- notPendingProblem,
2870
- planCancellation,
2871
- refusalData,
2872
- requestData,
2873
- failCancellationRequest,
2874
3397
  recordInboxEvent,
2875
3398
  settleInboxEvent,
2876
3399
  deferInboxEvent,
2877
3400
  listRetryableInboxEvents,
2878
- CONFIRMED_BEFORE_ORDER,
2879
- applyMarketplaceConfirmation,
2880
- listPendingAcceptances,
2881
- expireLapsedAcceptances,
2882
- cancelAcceptance,
2883
3401
  sealLink,
3402
+ sealAppLink,
2884
3403
  appCredentialsOf,
2885
3404
  linkTokenKey,
2886
3405
  cacheLinkToken,
@@ -2894,12 +3413,38 @@ export {
2894
3413
  connectionMerchantId,
2895
3414
  resolveIngestionTarget,
2896
3415
  readOutboundConnection,
2897
- listMarketplaceMenuLinks,
2898
- upsertLink,
2899
3416
  MARKETPLACE_OUTBOUND_JOB,
2900
3417
  outboundDedupeKey,
2901
3418
  statusDedupeKey,
2902
3419
  enqueueOutbound,
3420
+ statusTable,
3421
+ readStatusRows,
3422
+ noteMarketplaceStep,
3423
+ LOGISTICS_STEPS,
3424
+ logisticsEngine,
3425
+ logisticsCallContext,
3426
+ requestsFirst,
3427
+ tellCancellationFailed,
3428
+ MarketplaceAdapterRegistrationError,
3429
+ createAdapterRegistry,
3430
+ storedReasons,
3431
+ reasonsForOrder,
3432
+ resolveReason,
3433
+ suggestReason,
3434
+ NO_STANDING_REQUEST,
3435
+ CLAIM_SELECT,
3436
+ notPendingProblem,
3437
+ planCancellation,
3438
+ refusalData,
3439
+ requestData,
3440
+ failCancellationRequest,
3441
+ CONFIRMED_BEFORE_ORDER,
3442
+ applyMarketplaceConfirmation,
3443
+ listPendingAcceptances,
3444
+ expireLapsedAcceptances,
3445
+ cancelAcceptance,
3446
+ listMarketplaceMenuLinks,
3447
+ upsertLink,
2903
3448
  CATALOGUE_ROW_SELECT,
2904
3449
  catalogueTable,
2905
3450
  viewOf,
@@ -2910,9 +3455,6 @@ export {
2910
3455
  catalogueDedupeKey,
2911
3456
  enqueueCatalogue,
2912
3457
  runCatalogue,
2913
- statusTable,
2914
- readStatusRows,
2915
- noteMarketplaceStep,
2916
3458
  validatePickupCode,
2917
3459
  MARKETPLACE_ACKNOWLEDGE_JOB,
2918
3460
  AcknowledgeRetryError,
@@ -2923,6 +3465,13 @@ export {
2923
3465
  CancellationReasonsRetryError,
2924
3466
  runCancellationReasons,
2925
3467
  readOrderReasons,
3468
+ MARKETPLACE_DISPUTE_ANSWER_JOB,
3469
+ disputeView,
3470
+ readDisputes,
3471
+ applyDisputeEvent,
3472
+ answerDispute,
3473
+ DisputeAnswerRetryError,
3474
+ runDisputeAnswer,
2926
3475
  ingestMarketplaceOrder,
2927
3476
  CANCELLED_BEFORE_INGEST_REASON,
2928
3477
  markCancelledBeforeIngest,
@@ -2951,4 +3500,4 @@ export {
2951
3500
  AvailabilityRetryError,
2952
3501
  runAvailability
2953
3502
  };
2954
- //# sourceMappingURL=chunk-TICWLBSA.js.map
3503
+ //# sourceMappingURL=chunk-MDEIRGNL.js.map