@devlab.group/agent-commerce 2.6.0 → 2.7.1

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 (129) hide show
  1. package/README.md +17 -12
  2. package/dist/ap2.d.ts +1 -1
  3. package/dist/ap2.js +5 -5
  4. package/dist/{chunk-M6MQ3FYS.js → chunk-5AO5N2XY.js} +11 -5
  5. package/dist/chunk-5AO5N2XY.js.map +1 -0
  6. package/dist/{chunk-DRLBML7Z.js → chunk-5VW32JPV.js} +191 -78
  7. package/dist/chunk-5VW32JPV.js.map +1 -0
  8. package/dist/{chunk-ES3V6ECS.js → chunk-77HLISG4.js} +3 -2
  9. package/dist/chunk-77HLISG4.js.map +1 -0
  10. package/dist/{chunk-5ZYXBCDX.js → chunk-D7FPSGUQ.js} +25 -4
  11. package/dist/chunk-D7FPSGUQ.js.map +1 -0
  12. package/dist/{chunk-G3EYYHKF.js → chunk-DJRWYDKJ.js} +3 -3
  13. package/dist/{chunk-G3EYYHKF.js.map → chunk-DJRWYDKJ.js.map} +1 -1
  14. package/dist/chunk-IGXQMAKM.js +8 -0
  15. package/dist/{chunk-M6BSXXTF.js.map → chunk-IGXQMAKM.js.map} +1 -1
  16. package/dist/chunk-IWXVQYG5.js +6 -0
  17. package/dist/chunk-IWXVQYG5.js.map +1 -0
  18. package/dist/{chunk-M6WW6QIT.js → chunk-WDD2ZUR3.js} +5 -3
  19. package/dist/chunk-WDD2ZUR3.js.map +1 -0
  20. package/dist/{chunk-M52FBNJX.js → chunk-YHNTTMED.js} +6 -4
  21. package/dist/chunk-YHNTTMED.js.map +1 -0
  22. package/dist/cli/{ap2-2YMYA2H6.js → ap2-NTYL7H4I.js} +10 -11
  23. package/dist/cli/ap2-NTYL7H4I.js.map +1 -0
  24. package/dist/cli/chunk-2M2RF3CT.js +8 -0
  25. package/dist/cli/{chunk-4KLYFXMW.js.map → chunk-2M2RF3CT.js.map} +1 -1
  26. package/dist/cli/{chunk-5K4XEAZV.js → chunk-3IEXJ7I3.js} +25 -4
  27. package/dist/cli/chunk-3IEXJ7I3.js.map +1 -0
  28. package/dist/cli/{chunk-VJH6RYRK.js → chunk-3NVJAQRO.js} +3 -3
  29. package/dist/cli/{chunk-VJH6RYRK.js.map → chunk-3NVJAQRO.js.map} +1 -1
  30. package/dist/cli/{chunk-GET3CZGR.js → chunk-55AI6CLW.js} +6 -4
  31. package/dist/cli/chunk-55AI6CLW.js.map +1 -0
  32. package/dist/cli/{chunk-3NOMLMJW.js → chunk-66NTYSXI.js} +3 -3
  33. package/dist/cli/{chunk-3NOMLMJW.js.map → chunk-66NTYSXI.js.map} +1 -1
  34. package/dist/cli/{chunk-VJ4EO4LE.js → chunk-6EBDOH37.js} +3 -3
  35. package/dist/cli/{chunk-VJ4EO4LE.js.map → chunk-6EBDOH37.js.map} +1 -1
  36. package/dist/cli/{chunk-NSYSMDQN.js → chunk-A42BCWZ2.js} +57 -29
  37. package/dist/cli/chunk-A42BCWZ2.js.map +1 -0
  38. package/dist/cli/chunk-APC5BTQM.js +6 -0
  39. package/dist/cli/chunk-APC5BTQM.js.map +1 -0
  40. package/dist/cli/{chunk-SYQLJXIU.js → chunk-C5YISPT6.js} +3 -3
  41. package/dist/cli/chunk-C5YISPT6.js.map +1 -0
  42. package/dist/cli/chunk-DKWO6LLX.js +34 -0
  43. package/dist/cli/chunk-DKWO6LLX.js.map +1 -0
  44. package/dist/cli/{chunk-YOF7IK4V.js → chunk-EVCIEKHN.js} +193 -80
  45. package/dist/cli/chunk-EVCIEKHN.js.map +1 -0
  46. package/dist/cli/{chunk-YWG2ZN3L.js → chunk-FETTSOMT.js} +12 -6
  47. package/dist/cli/chunk-FETTSOMT.js.map +1 -0
  48. package/dist/cli/{chunk-SPAYKVUP.js → chunk-FL4HPCD4.js} +3 -2
  49. package/dist/cli/chunk-FL4HPCD4.js.map +1 -0
  50. package/dist/cli/{chunk-AZL7RPFU.js → chunk-GBBG66O6.js} +77 -16
  51. package/dist/cli/chunk-GBBG66O6.js.map +1 -0
  52. package/dist/cli/{chunk-3EQBCFZY.js → chunk-H7EBJ4I3.js} +3 -3
  53. package/dist/cli/{chunk-3EQBCFZY.js.map → chunk-H7EBJ4I3.js.map} +1 -1
  54. package/dist/cli/{chunk-DHFMIBPG.js → chunk-MBPOKPQM.js} +6 -6
  55. package/dist/cli/{chunk-DHFMIBPG.js.map → chunk-MBPOKPQM.js.map} +1 -1
  56. package/dist/cli/{chunk-PTL7SNOI.js → chunk-OETKXDGA.js} +467 -122
  57. package/dist/cli/chunk-OETKXDGA.js.map +1 -0
  58. package/dist/cli/{chunk-TFV3K6YS.js → chunk-VSSSU4AU.js} +3 -3
  59. package/dist/cli/{chunk-TFV3K6YS.js.map → chunk-VSSSU4AU.js.map} +1 -1
  60. package/dist/cli/config-ODN4IEMZ.js +13 -0
  61. package/dist/cli/{config-3K65QJ22.js.map → config-ODN4IEMZ.js.map} +1 -1
  62. package/dist/cli/index.js +51 -37
  63. package/dist/cli/index.js.map +1 -1
  64. package/dist/cli/{mcp-6F64A7KE.js → mcp-V27OKTOV.js} +7 -7
  65. package/dist/cli/{mcp-6F64A7KE.js.map → mcp-V27OKTOV.js.map} +1 -1
  66. package/dist/cli/payment-providers-SUATT75K.js +6 -0
  67. package/dist/cli/{payment-providers-2ITS6KNR.js.map → payment-providers-SUATT75K.js.map} +1 -1
  68. package/dist/cli/{provider-5BGG5YKQ.js → provider-C3QDAXMR.js} +9 -9
  69. package/dist/cli/{provider-5BGG5YKQ.js.map → provider-C3QDAXMR.js.map} +1 -1
  70. package/dist/cli/receipts-ZS3VZ2D4.js +9 -0
  71. package/dist/cli/{receipts-I4IIE7U6.js.map → receipts-ZS3VZ2D4.js.map} +1 -1
  72. package/dist/cli/reconcile-GS25MQ42.js +4 -0
  73. package/dist/cli/{reconcile-55WNCSFC.js.map → reconcile-GS25MQ42.js.map} +1 -1
  74. package/dist/cli/{run-2P6ZGFUE.js → run-WYFZUO5D.js} +142 -46
  75. package/dist/cli/run-WYFZUO5D.js.map +1 -0
  76. package/dist/cli/{svm-KDSPDFJG.js → svm-NBZY7H6W.js} +9 -6
  77. package/dist/cli/svm-NBZY7H6W.js.map +1 -0
  78. package/dist/cli/{x402-4LPIIELI.js → x402-UGLZ3LA7.js} +11 -10
  79. package/dist/cli/x402-UGLZ3LA7.js.map +1 -0
  80. package/dist/{guardrails-CX_jYXvZ.d.ts → guardrails-CeyLS1ou.d.ts} +2 -2
  81. package/dist/index.d.ts +23 -13
  82. package/dist/index.js +708 -181
  83. package/dist/index.js.map +1 -1
  84. package/dist/mcp.d.ts +2 -2
  85. package/dist/mcp.js +4 -4
  86. package/dist/mpp.js +5 -5
  87. package/dist/{protocol-adapter-1WbtM3xG.d.ts → protocol-adapter-DdFL5LBU.d.ts} +12 -2
  88. package/dist/{runtime-B-kARa2f.d.ts → runtime-BmaSp2Ce.d.ts} +31 -3
  89. package/dist/{store-kIIMpUA-.d.ts → store-DQwbKhnc.d.ts} +25 -8
  90. package/dist/{svm-KNC3PHMS.js → svm-4HR5OEP7.js} +9 -6
  91. package/dist/svm-4HR5OEP7.js.map +1 -0
  92. package/dist/testing.d.ts +1 -1
  93. package/dist/testing.js +156 -2
  94. package/dist/testing.js.map +1 -1
  95. package/dist/{transaction-Dv0UFGg5.d.ts → transaction-BXXJltZ-.d.ts} +1 -1
  96. package/dist/x402.d.ts +7 -2
  97. package/dist/x402.js +7 -6
  98. package/dist/x402.js.map +1 -1
  99. package/package.json +13 -29
  100. package/dist/chunk-5ZYXBCDX.js.map +0 -1
  101. package/dist/chunk-DRLBML7Z.js.map +0 -1
  102. package/dist/chunk-ES3V6ECS.js.map +0 -1
  103. package/dist/chunk-M52FBNJX.js.map +0 -1
  104. package/dist/chunk-M6BSXXTF.js +0 -8
  105. package/dist/chunk-M6MQ3FYS.js.map +0 -1
  106. package/dist/chunk-M6WW6QIT.js.map +0 -1
  107. package/dist/cli/ap2-2YMYA2H6.js.map +0 -1
  108. package/dist/cli/chunk-4KLYFXMW.js +0 -8
  109. package/dist/cli/chunk-5K4XEAZV.js.map +0 -1
  110. package/dist/cli/chunk-6R6WJ4FD.js +0 -18
  111. package/dist/cli/chunk-6R6WJ4FD.js.map +0 -1
  112. package/dist/cli/chunk-AZL7RPFU.js.map +0 -1
  113. package/dist/cli/chunk-FHCFR2GS.js +0 -17
  114. package/dist/cli/chunk-FHCFR2GS.js.map +0 -1
  115. package/dist/cli/chunk-GET3CZGR.js.map +0 -1
  116. package/dist/cli/chunk-NSYSMDQN.js.map +0 -1
  117. package/dist/cli/chunk-PTL7SNOI.js.map +0 -1
  118. package/dist/cli/chunk-SPAYKVUP.js.map +0 -1
  119. package/dist/cli/chunk-SYQLJXIU.js.map +0 -1
  120. package/dist/cli/chunk-YOF7IK4V.js.map +0 -1
  121. package/dist/cli/chunk-YWG2ZN3L.js.map +0 -1
  122. package/dist/cli/config-3K65QJ22.js +0 -12
  123. package/dist/cli/payment-providers-2ITS6KNR.js +0 -6
  124. package/dist/cli/receipts-I4IIE7U6.js +0 -8
  125. package/dist/cli/reconcile-55WNCSFC.js +0 -4
  126. package/dist/cli/run-2P6ZGFUE.js.map +0 -1
  127. package/dist/cli/svm-KDSPDFJG.js.map +0 -1
  128. package/dist/cli/x402-4LPIIELI.js.map +0 -1
  129. package/dist/svm-KNC3PHMS.js.map +0 -1
@@ -1,6 +1,8 @@
1
- import { SETTLE_AFTER_BACKEND_METADATA_KEY, REUSE_REJECTED_AUTHORIZATION_METADATA_KEY, canonicalJson } from './chunk-3NOMLMJW.js';
2
- import { RESERVED_INPUT_FIELDS, NOOP_LOGGER, DEFAULT_BACKEND_TIMEOUT_MS, RECONCILIATION_METADATA_KEY } from './chunk-GET3CZGR.js';
3
- import { CommerceError, isCommerceError, describeError, toCommerceError } from './chunk-SYQLJXIU.js';
1
+ import { hasMethodGroup } from './chunk-DKWO6LLX.js';
2
+ import { PAYMENT_KEY_ENDPOINT_PREFIX } from './chunk-APC5BTQM.js';
3
+ import { SETTLE_AFTER_BACKEND_METADATA_KEY, REUSE_REJECTED_AUTHORIZATION_METADATA_KEY, canonicalJson } from './chunk-66NTYSXI.js';
4
+ import { RESERVED_INPUT_FIELDS, NOOP_LOGGER, DEFAULT_BACKEND_TIMEOUT_MS, RECONCILIATION_METADATA_KEY } from './chunk-55AI6CLW.js';
5
+ import { CommerceError, isCommerceError, describeError, toCommerceError } from './chunk-C5YISPT6.js';
4
6
  import { isRecord } from './chunk-3M6U7ILB.js';
5
7
  import { createHash } from 'crypto';
6
8
  import { isDeepStrictEqual } from 'util';
@@ -48,6 +50,333 @@ var ACP_FORWARDED_HEADERS = [
48
50
  var ACP_MAX_FORWARDED_HEADER_LENGTH = 2048;
49
51
  var ACP_MERCHANT_RETRY_AFTER_DEFAULT_SECONDS = 5;
50
52
  var ACP_MERCHANT_RETRY_AFTER_MAX_SECONDS = 300;
53
+ function createFlow(request, transactionId) {
54
+ return { request, transactionId, persistenceFailures: [], journaled: false, chargeRisk: false };
55
+ }
56
+ function failuresOf(flow) {
57
+ return flow.persistenceFailures.length > 0 ? { persistenceFailures: [...flow.persistenceFailures] } : {};
58
+ }
59
+ function sha256(text) {
60
+ return `sha256:${createHash("sha256").update(text, "utf8").digest("hex")}`;
61
+ }
62
+ function inputDigest(input) {
63
+ const json = canonicalJson(input);
64
+ return json !== void 0 ? sha256(json) : void 0;
65
+ }
66
+ function configDigest(resource, requirement) {
67
+ const terms = {
68
+ resourceId: resource.id,
69
+ pricing: resource.pricing,
70
+ paymentMethods: resource.paymentMethods,
71
+ authorization: resource.authorization?.required ?? [],
72
+ requirement: {
73
+ provider: requirement.provider,
74
+ amount: requirement.amount,
75
+ currency: requirement.currency,
76
+ destination: requirement.destination ?? null,
77
+ network: requirement.network ?? null,
78
+ asset: requirement.asset ?? null,
79
+ settleAfterBackend: requirement.metadata?.[SETTLE_AFTER_BACKEND_METADATA_KEY] === true
80
+ }
81
+ };
82
+ return sha256(canonicalJson(terms) ?? JSON.stringify(terms));
83
+ }
84
+ function newTransaction(flow, resource, requirement, verification, digest, authorization) {
85
+ const raw = verification.metadata?.[RECONCILIATION_METADATA_KEY];
86
+ const locator = isRecord(raw) ? raw : void 0;
87
+ const expiresAt = typeof locator?.["expiresAt"] === "string" ? locator["expiresAt"] : void 0;
88
+ const network = verification.network ?? requirement.network;
89
+ const asset = verification.asset ?? requirement.asset;
90
+ return {
91
+ id: flow.transactionId,
92
+ protocol: flow.request.protocol,
93
+ ...network !== void 0 ? { network } : {},
94
+ ...asset !== void 0 ? { asset } : {},
95
+ ...locator !== void 0 ? { locator } : {},
96
+ ...expiresAt !== void 0 ? { expiresAt } : {},
97
+ ...authorization !== void 0 ? { authorization } : {},
98
+ ...digest !== void 0 ? { inputDigest: digest } : {},
99
+ configDigest: configDigest(resource, requirement)
100
+ };
101
+ }
102
+ function sha256Hex(text) {
103
+ return createHash("sha256").update(text).digest("hex");
104
+ }
105
+ function paidOperationKey(operation) {
106
+ const { deployment, resourceId, replayKey, inputDigest: digest, clientKey, payer } = operation;
107
+ if (digest === void 0) return void 0;
108
+ const identity = clientKey && payer ? `retry:${sha256Hex(clientKey)}:${payer}` : replayKey;
109
+ return sha256Hex(JSON.stringify(["paid-operation", deployment, resourceId, identity, digest]));
110
+ }
111
+
112
+ // src/core/execution/pipeline/retry.ts
113
+ var MAX_REDELIVERY_RETENTION_HOURS = 8760;
114
+ var IN_FLIGHT_RETRY_AFTER_SECONDS = 1;
115
+ var REFUSALS = {
116
+ conflict: {
117
+ reason: "payment_identifier_conflict",
118
+ message: "This payment identifier belongs to another request"
119
+ },
120
+ "in-flight": {
121
+ reason: "payment_identifier_in_flight",
122
+ message: "A request with this payment identifier is in progress"
123
+ },
124
+ unresolved: {
125
+ reason: "payment_identifier_unresolved",
126
+ message: "The earlier request with this payment identifier may have been charged and has no stored response"
127
+ }
128
+ };
129
+ function assertRetrySupport(resource, store, deployment, requestId) {
130
+ const { merchantKey, redelivery } = resource.idempotency ?? {};
131
+ if (merchantKey !== true && redelivery === void 0) return void 0;
132
+ const invalid = (message) => new CommerceError("CONFIG_INVALID", message, {
133
+ ...requestId !== void 0 ? { requestId } : {},
134
+ resourceId: resource.id
135
+ });
136
+ const unsupported = (needs) => invalid(`Resource "${resource.id}" sets idempotency, which requires ${needs}`);
137
+ const hours = redelivery?.retentionHours;
138
+ if (hours !== void 0 && !(Number.isInteger(hours) && hours >= 1 && hours <= MAX_REDELIVERY_RETENTION_HOURS)) {
139
+ throw invalid(
140
+ `Resource "${resource.id}" sets idempotency.redelivery.retentionHours outside 1 to ${MAX_REDELIVERY_RETENTION_HOURS}`
141
+ );
142
+ }
143
+ if (deployment === void 0) throw unsupported("the pipeline's deployment option");
144
+ if (redelivery === void 0) return { deployment };
145
+ if (!hasMethodGroup(store, "idempotency_claims") || !hasMethodGroup(store, "response_redelivery")) {
146
+ throw unsupported("a store with idempotency claims and getIdempotencyKey");
147
+ }
148
+ return { deployment, store };
149
+ }
150
+ function createRetryGate(ctx) {
151
+ const { options, safeEmit, safePersist, buildEvent } = ctx;
152
+ async function open(flow, resource, provider, validInput, support, pipelineStart) {
153
+ const { request } = flow;
154
+ const retentionHours = resource.idempotency?.redelivery?.retentionHours;
155
+ const { payment } = request;
156
+ if (support?.store === void 0 || retentionHours === void 0 || payment === void 0) {
157
+ return void 0;
158
+ }
159
+ const clientKey = request.retryKey ?? await providerRetryKey(flow, resource, provider, payment);
160
+ if (clientKey === void 0) return void 0;
161
+ const fingerprint = inputDigest(validInput);
162
+ if (fingerprint === void 0) {
163
+ throw await rejected(
164
+ flow,
165
+ resource,
166
+ provider,
167
+ new CommerceError(
168
+ "INPUT_INVALID",
169
+ `Input for resource "${resource.id}" is not I-JSON, so a retry key cannot identify it`,
170
+ { requestId: request.requestId, resourceId: resource.id }
171
+ )
172
+ );
173
+ }
174
+ const { store } = support;
175
+ const { authorization } = request;
176
+ const ticket = {
177
+ kind: "retry",
178
+ store,
179
+ scope: {
180
+ deployment: support.deployment,
181
+ endpoint: `${PAYMENT_KEY_ENDPOINT_PREFIX}${resource.id}`,
182
+ key: sha256Hex(clientKey)
183
+ },
184
+ fingerprint,
185
+ expiresAt: new Date(
186
+ options.clock.now().getTime() + retentionHours * 60 * 60 * 1e3
187
+ ).toISOString(),
188
+ clientKey,
189
+ proofDigest: sha256Hex(`${payment.method}:${payment.payload}`),
190
+ ...authorization !== void 0 ? { authorizationDigest: sha256Hex(`${authorization.method}:${authorization.payload}`) } : {}
191
+ };
192
+ const existing = await reading(
193
+ flow,
194
+ resource,
195
+ () => store.getIdempotencyKey(ticket.scope, fingerprint)
196
+ );
197
+ if (existing?.kind === "in-flight" || existing?.kind === "unresolved") {
198
+ if (existing.owner !== ticket.proofDigest) return ticket;
199
+ throw await refusal(flow, resource, provider, existing.kind);
200
+ }
201
+ if (existing?.kind !== "replay") return ticket;
202
+ const stored = readStoredDelivery(existing.body);
203
+ return stored?.proofDigest === ticket.proofDigest && authorizes(resource, stored, ticket) ? redeliver(flow, resource, provider, existing.status, stored, pipelineStart) : ticket;
204
+ }
205
+ async function claim(flow, resource, provider, ticket, verification, pipelineStart) {
206
+ const { scope, fingerprint, expiresAt, proofDigest } = ticket;
207
+ const claimed = await reading(
208
+ flow,
209
+ resource,
210
+ () => ticket.store.claimIdempotencyKey(scope, fingerprint, expiresAt, proofDigest)
211
+ );
212
+ const replay = await acceptOrRefuse(flow, resource, provider, claimed);
213
+ if (replay === void 0) return void 0;
214
+ const stored = await storedDelivery(flow, resource, provider, replay);
215
+ const samePayer = verification.payer !== void 0 && verification.payer === stored.payer;
216
+ if (!samePayer || !authorizes(resource, stored, ticket)) {
217
+ throw await refusal(flow, resource, provider, "conflict");
218
+ }
219
+ return redeliver(flow, resource, provider, replay.status, stored, pipelineStart);
220
+ }
221
+ async function finishDelivered(flow, ticket, verification, response, receipt) {
222
+ const contentType = response.headers["content-type"];
223
+ const stored = {
224
+ proofDigest: ticket.proofDigest,
225
+ ...ticket.authorizationDigest !== void 0 ? { authorizationDigest: ticket.authorizationDigest } : {},
226
+ // Record the verified buyer; settlement may name a fee payer instead
227
+ ...verification.payer !== void 0 ? { payer: verification.payer } : {},
228
+ // Keep only Content-Type; never persist a backend Set-Cookie header
229
+ ...contentType !== void 0 ? { contentType } : {},
230
+ body: response.body ?? null,
231
+ receiptId: receipt.id
232
+ };
233
+ const receiptSaved = !flow.persistenceFailures.includes("receipt");
234
+ const update = { kind: "completed", status: response.status, body: stored };
235
+ if (receiptSaved && await write(flow, ticket, update)) return;
236
+ if (!flow.persistenceFailures.includes("response")) flow.persistenceFailures.push("response");
237
+ await write(flow, ticket, { kind: "unresolved" });
238
+ }
239
+ async function finishFailed(flow, ticket) {
240
+ await write(flow, ticket, { kind: flow.chargeRisk ? "unresolved" : "released" });
241
+ }
242
+ function write(flow, ticket, update) {
243
+ return safePersist(
244
+ flow,
245
+ () => ticket.store.updateIdempotencyKey(ticket.scope, update),
246
+ `updateIdempotencyKey(${update.kind})`,
247
+ "response"
248
+ );
249
+ }
250
+ async function reading(flow, resource, read) {
251
+ try {
252
+ return await read();
253
+ } catch (error) {
254
+ throw new CommerceError("STORAGE_ERROR", "Payment retry state could not be read", {
255
+ requestId: flow.request.requestId,
256
+ resourceId: resource.id,
257
+ cause: error
258
+ });
259
+ }
260
+ }
261
+ async function acceptOrRefuse(flow, resource, provider, claimed) {
262
+ if (claimed === void 0 || claimed.kind === "reserved") return void 0;
263
+ if (claimed.kind === "replay") return claimed;
264
+ throw await refusal(flow, resource, provider, claimed.kind);
265
+ }
266
+ async function storedDelivery(flow, resource, provider, replay) {
267
+ const stored = readStoredDelivery(replay.body);
268
+ if (stored === void 0) throw await refusal(flow, resource, provider, "unresolved");
269
+ return stored;
270
+ }
271
+ function refusal(flow, resource, provider, kind) {
272
+ const { reason, message } = REFUSALS[kind];
273
+ const inFlight = kind === "in-flight";
274
+ return rejected(
275
+ flow,
276
+ resource,
277
+ provider,
278
+ new CommerceError("PAYMENT_REPLAYED", message, {
279
+ requestId: flow.request.requestId,
280
+ resourceId: resource.id,
281
+ details: {
282
+ reason,
283
+ ...inFlight ? { retryAfterSeconds: IN_FLIGHT_RETRY_AFTER_SECONDS } : {}
284
+ },
285
+ ...inFlight ? { retryable: true } : {}
286
+ })
287
+ );
288
+ }
289
+ async function rejected(flow, resource, provider, error) {
290
+ const reason = error.details?.["reason"];
291
+ await safeEmit(
292
+ buildEvent(flow, {
293
+ type: "payment.rejected",
294
+ resourceId: resource.id,
295
+ adapter: flow.request.protocol,
296
+ paymentProvider: provider.name,
297
+ status: "error",
298
+ data: { reason: typeof reason === "string" ? reason : error.code }
299
+ })
300
+ );
301
+ if (error.requestId !== void 0) return error;
302
+ return new CommerceError(error.code, error.message, {
303
+ requestId: flow.request.requestId,
304
+ resourceId: error.resourceId ?? resource.id,
305
+ httpStatus: error.httpStatus,
306
+ retryable: error.retryable,
307
+ ...error.details !== void 0 ? { details: error.details } : {},
308
+ ...error.cause !== void 0 ? { cause: error.cause } : {}
309
+ });
310
+ }
311
+ async function providerRetryKey(flow, resource, provider, submission) {
312
+ try {
313
+ return provider.retryKey?.({ resource, submission });
314
+ } catch (error) {
315
+ const typed = isCommerceError(error) ? error : new CommerceError("PAYMENT_PROVIDER_UNAVAILABLE", "Payment provider is unavailable", {
316
+ cause: error
317
+ });
318
+ throw await rejected(flow, resource, provider, typed);
319
+ }
320
+ }
321
+ async function redeliver(flow, resource, provider, status, stored, pipelineStart) {
322
+ const { request } = flow;
323
+ const receipt = await reading(flow, resource, () => options.store.getReceipt(stored.receiptId));
324
+ if (receipt?.payment === void 0) {
325
+ throw await refusal(flow, resource, provider, "unresolved");
326
+ }
327
+ const durationMs = Math.round(options.clock.monotonicMs() - pipelineStart);
328
+ const original = receipt.transactionId;
329
+ await safeEmit(
330
+ buildEvent(flow, {
331
+ type: "resource.delivered",
332
+ resourceId: resource.id,
333
+ adapter: request.protocol,
334
+ status: "ok",
335
+ durationMs,
336
+ data: {
337
+ redelivered: true,
338
+ ...original !== void 0 ? { originalTransactionId: original } : {}
339
+ }
340
+ })
341
+ );
342
+ return {
343
+ kind: "delivered",
344
+ requestId: request.requestId,
345
+ transactionId: flow.transactionId,
346
+ resourceId: resource.id,
347
+ backendStatus: status,
348
+ body: stored.body,
349
+ headers: stored.contentType !== void 0 ? { "content-type": stored.contentType } : {},
350
+ payment: receipt.payment,
351
+ receipt,
352
+ durationMs,
353
+ redelivered: true
354
+ };
355
+ }
356
+ return { open, claim, finishDelivered, finishFailed };
357
+ }
358
+ function authorizes(resource, stored, ticket) {
359
+ if ((resource.authorization?.required.length ?? 0) === 0) return true;
360
+ return stored.authorizationDigest !== void 0 && stored.authorizationDigest === ticket.authorizationDigest;
361
+ }
362
+ function readStoredDelivery(value) {
363
+ if (!isRecord(value) || !Object.hasOwn(value, "body")) return void 0;
364
+ const { proofDigest, authorizationDigest, payer, contentType, body, receiptId } = value;
365
+ if (typeof proofDigest !== "string" || typeof receiptId !== "string") return void 0;
366
+ if (authorizationDigest !== void 0 && typeof authorizationDigest !== "string") {
367
+ return void 0;
368
+ }
369
+ if (payer !== void 0 && typeof payer !== "string") return void 0;
370
+ if (contentType !== void 0 && typeof contentType !== "string") return void 0;
371
+ return {
372
+ proofDigest,
373
+ ...authorizationDigest !== void 0 ? { authorizationDigest } : {},
374
+ ...payer !== void 0 ? { payer } : {},
375
+ ...contentType !== void 0 ? { contentType } : {},
376
+ body,
377
+ receiptId
378
+ };
379
+ }
51
380
 
52
381
  // src/core/execution/backend-request.ts
53
382
  var NEVER_FORWARDED_HEADER = /^(authorization|cookie|set-cookie|host|content-length|content-type|connection|keep-alive|te|trailer|transfer-encoding|upgrade|idempotency-key|proxy-.*)$/;
@@ -395,56 +724,6 @@ function safeStringify(value) {
395
724
  function isAbortError(error) {
396
725
  return error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
397
726
  }
398
- function createFlow(request, transactionId) {
399
- return { request, transactionId, persistenceFailures: [], journaled: false };
400
- }
401
- function failuresOf(flow) {
402
- return flow.persistenceFailures.length > 0 ? { persistenceFailures: [...flow.persistenceFailures] } : {};
403
- }
404
- function sha256(text) {
405
- return `sha256:${createHash("sha256").update(text, "utf8").digest("hex")}`;
406
- }
407
- function inputDigest(input) {
408
- const json = canonicalJson(input);
409
- return json !== void 0 ? sha256(json) : void 0;
410
- }
411
- function configDigest(resource, requirement) {
412
- const terms = {
413
- resourceId: resource.id,
414
- pricing: resource.pricing,
415
- paymentMethods: resource.paymentMethods,
416
- authorization: resource.authorization?.required ?? [],
417
- requirement: {
418
- provider: requirement.provider,
419
- amount: requirement.amount,
420
- currency: requirement.currency,
421
- destination: requirement.destination ?? null,
422
- network: requirement.network ?? null,
423
- asset: requirement.asset ?? null,
424
- settleAfterBackend: requirement.metadata?.[SETTLE_AFTER_BACKEND_METADATA_KEY] === true
425
- }
426
- };
427
- return sha256(canonicalJson(terms) ?? JSON.stringify(terms));
428
- }
429
- function newTransaction(flow, resource, requirement, verification, validInput, authorization) {
430
- const raw = verification.metadata?.[RECONCILIATION_METADATA_KEY];
431
- const locator = isRecord(raw) ? raw : void 0;
432
- const expiresAt = typeof locator?.["expiresAt"] === "string" ? locator["expiresAt"] : void 0;
433
- const network = verification.network ?? requirement.network;
434
- const asset = verification.asset ?? requirement.asset;
435
- const digest = inputDigest(validInput);
436
- return {
437
- id: flow.transactionId,
438
- protocol: flow.request.protocol,
439
- ...network !== void 0 ? { network } : {},
440
- ...asset !== void 0 ? { asset } : {},
441
- ...locator !== void 0 ? { locator } : {},
442
- ...expiresAt !== void 0 ? { expiresAt } : {},
443
- ...authorization !== void 0 ? { authorization } : {},
444
- ...digest !== void 0 ? { inputDigest: digest } : {},
445
- configDigest: configDigest(resource, requirement)
446
- };
447
- }
448
727
  var SUPPORTED_TYPES = /* @__PURE__ */ new Set([
449
728
  "object",
450
729
  "string",
@@ -709,9 +988,15 @@ function replayError(error, requirement) {
709
988
  }
710
989
 
711
990
  // src/core/execution/pipeline/admission.ts
712
- function createPaymentAdmission(ctx, authorizeAndReserve) {
991
+ function createPaymentAdmission(ctx, authorizeAndReserve, retryGate) {
713
992
  const { options, safeEmit, buildEvent } = ctx;
714
- return async function admitPayment(flow, request, resource, pricing, validInput) {
993
+ return async function admitPayment(flow, request, resource, pricing, validInput, pipelineStart) {
994
+ const support = assertRetrySupport(
995
+ resource,
996
+ options.store,
997
+ options.deployment,
998
+ request.requestId
999
+ );
715
1000
  const provider = pickProvider(options.paymentProviders, resource.paymentMethods);
716
1001
  if (!provider) {
717
1002
  throw new CommerceError(
@@ -729,6 +1014,15 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
729
1014
  resource,
730
1015
  request.requestId
731
1016
  );
1017
+ const retry = await retryGate.open(
1018
+ flow,
1019
+ resource,
1020
+ provider,
1021
+ validInput,
1022
+ support,
1023
+ pipelineStart
1024
+ );
1025
+ if (retry?.kind === "delivered") return retry;
732
1026
  let requirement;
733
1027
  try {
734
1028
  requirement = await provider.createRequirement({
@@ -833,77 +1127,104 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
833
1127
  });
834
1128
  }
835
1129
  const replayKey = verification.replayKey;
836
- const hold = await authorizeAndReserve(
837
- flow,
838
- request,
839
- resource,
840
- authProviders,
841
- requirement,
842
- validInput
843
- );
1130
+ const digest = retry?.fingerprint ?? inputDigest(validInput);
1131
+ if (retry !== void 0) {
1132
+ const stored = await retryGate.claim(
1133
+ flow,
1134
+ resource,
1135
+ provider,
1136
+ retry,
1137
+ verification,
1138
+ pipelineStart
1139
+ );
1140
+ if (stored !== void 0) return stored;
1141
+ }
844
1142
  try {
845
- const attempt = await options.store.reservePaymentAttempt({
846
- requestId: request.requestId,
847
- resourceId: resource.id,
848
- provider: provider.name,
849
- replayKey,
850
- amount: verification.amount,
851
- currency: verification.currency,
852
- ...verification.payer !== void 0 ? { payer: verification.payer } : {},
853
- ...verification.payee !== void 0 ? { payee: verification.payee } : {},
854
- ...requirement.metadata?.[REUSE_REJECTED_AUTHORIZATION_METADATA_KEY] === true ? { reclaimRejected: true } : {},
855
- transaction: newTransaction(
856
- flow,
857
- resource,
858
- requirement,
859
- verification,
860
- validInput,
861
- hold !== void 0 ? { ...hold.record, reservationId: hold.reservationId } : void 0
862
- )
863
- });
864
- flow.journaled = attempt.transactionId === flow.transactionId && options.store.recordTransactionStep !== void 0;
865
- } catch (error) {
866
- const mapped = toCommerceError(
867
- error,
868
- "STORAGE_ERROR",
869
- "Payment attempt could not be recorded"
1143
+ const hold = await authorizeAndReserve(
1144
+ flow,
1145
+ request,
1146
+ resource,
1147
+ authProviders,
1148
+ requirement,
1149
+ validInput
870
1150
  );
871
- await hold?.finalize("release");
1151
+ try {
1152
+ const attempt = await options.store.reservePaymentAttempt({
1153
+ requestId: request.requestId,
1154
+ resourceId: resource.id,
1155
+ provider: provider.name,
1156
+ replayKey,
1157
+ amount: verification.amount,
1158
+ currency: verification.currency,
1159
+ ...verification.payer !== void 0 ? { payer: verification.payer } : {},
1160
+ ...verification.payee !== void 0 ? { payee: verification.payee } : {},
1161
+ ...requirement.metadata?.[REUSE_REJECTED_AUTHORIZATION_METADATA_KEY] === true ? { reclaimRejected: true } : {},
1162
+ transaction: newTransaction(
1163
+ flow,
1164
+ resource,
1165
+ requirement,
1166
+ verification,
1167
+ digest,
1168
+ hold !== void 0 ? { ...hold.record, reservationId: hold.reservationId } : void 0
1169
+ )
1170
+ });
1171
+ flow.journaled = attempt.transactionId === flow.transactionId && options.store.recordTransactionStep !== void 0;
1172
+ } catch (error) {
1173
+ const mapped = toCommerceError(
1174
+ error,
1175
+ "STORAGE_ERROR",
1176
+ "Payment attempt could not be recorded"
1177
+ );
1178
+ await hold?.finalize("release");
1179
+ await safeEmit(
1180
+ buildEvent(flow, {
1181
+ type: "payment.rejected",
1182
+ resourceId: resource.id,
1183
+ adapter: request.protocol,
1184
+ paymentProvider: provider.name,
1185
+ status: "error",
1186
+ data: { reason: mapped.code }
1187
+ })
1188
+ );
1189
+ throw replayError(mapped, requirement);
1190
+ }
872
1191
  await safeEmit(
873
1192
  buildEvent(flow, {
874
- type: "payment.rejected",
1193
+ type: "payment.verified",
875
1194
  resourceId: resource.id,
876
1195
  adapter: request.protocol,
877
1196
  paymentProvider: provider.name,
878
- status: "error",
879
- data: { reason: mapped.code }
1197
+ status: "ok"
880
1198
  })
881
1199
  );
882
- throw replayError(mapped, requirement);
883
- }
884
- await safeEmit(
885
- buildEvent(flow, {
886
- type: "payment.verified",
1200
+ const merchantKey = support !== void 0 && resource.idempotency?.merchantKey === true ? paidOperationKey({
1201
+ deployment: support.deployment,
887
1202
  resourceId: resource.id,
888
- adapter: request.protocol,
889
- paymentProvider: provider.name,
890
- status: "ok"
891
- })
892
- );
893
- return {
894
- kind: "admitted",
895
- settleArgs: {
896
- flow,
897
- request,
898
- resource,
899
- provider,
900
- requirement,
901
- payment,
902
- verification,
903
1203
  replayKey,
904
- hold
905
- }
906
- };
1204
+ inputDigest: digest,
1205
+ ...retry !== void 0 ? { clientKey: retry.clientKey } : {},
1206
+ ...verification.payer !== void 0 ? { payer: verification.payer } : {}
1207
+ }) : void 0;
1208
+ return {
1209
+ kind: "admitted",
1210
+ settleArgs: {
1211
+ flow,
1212
+ request,
1213
+ resource,
1214
+ provider,
1215
+ requirement,
1216
+ payment,
1217
+ verification,
1218
+ replayKey,
1219
+ hold,
1220
+ ...merchantKey !== void 0 ? { merchantKey } : {},
1221
+ ...retry !== void 0 ? { retry } : {}
1222
+ }
1223
+ };
1224
+ } catch (error) {
1225
+ if (retry !== void 0) await retryGate.finishFailed(flow, retry);
1226
+ throw error;
1227
+ }
907
1228
  };
908
1229
  async function refusalFor(verification, requirement, request, resource) {
909
1230
  const ids = { requestId: request.requestId, resourceId: resource.id };
@@ -1029,6 +1350,7 @@ function createSettlement(ctx) {
1029
1350
  hold
1030
1351
  } = args;
1031
1352
  await recordStep(flow, { kind: "settling" });
1353
+ flow.chargeRisk = true;
1032
1354
  let settlement;
1033
1355
  try {
1034
1356
  settlement = await provider.settle({
@@ -1041,6 +1363,7 @@ function createSettlement(ctx) {
1041
1363
  } catch (error) {
1042
1364
  const notSubmitted = notSubmittedReason(error);
1043
1365
  if (notSubmitted !== void 0) {
1366
+ flow.chargeRisk = false;
1044
1367
  await finalizeHold(flow, hold, "release");
1045
1368
  await safePersist(
1046
1369
  flow,
@@ -1111,6 +1434,7 @@ function createSettlement(ctx) {
1111
1434
  });
1112
1435
  }
1113
1436
  if (settlement.status !== "settled") {
1437
+ flow.chargeRisk = false;
1114
1438
  await finalizeHold(flow, hold, "release");
1115
1439
  await safePersist(
1116
1440
  flow,
@@ -1232,7 +1556,8 @@ function createExecutionPipeline(options) {
1232
1556
  const ctx = createPipelineContext(options);
1233
1557
  const { safeEmit, safePersist, recordStep, buildEvent } = ctx;
1234
1558
  const { settle, abandonSettlement } = createSettlement(ctx);
1235
- const admitPayment = createPaymentAdmission(ctx, createAuthorizeAndReserve(ctx));
1559
+ const retryGate = createRetryGate(ctx);
1560
+ const admitPayment = createPaymentAdmission(ctx, createAuthorizeAndReserve(ctx), retryGate);
1236
1561
  async function execute(request) {
1237
1562
  const pipelineStart = options.clock.monotonicMs();
1238
1563
  const resource = options.resources.get(request.resourceId);
@@ -1296,12 +1621,22 @@ function createExecutionPipeline(options) {
1296
1621
  }
1297
1622
  let settleArgs;
1298
1623
  if (resource.pricing.type === "fixed") {
1299
- const admission = await admitPayment(flow, request, resource, resource.pricing, validInput);
1300
- if (admission.kind === "payment-required") return admission;
1624
+ const admission = await admitPayment(
1625
+ flow,
1626
+ request,
1627
+ resource,
1628
+ resource.pricing,
1629
+ validInput,
1630
+ pipelineStart
1631
+ );
1632
+ if (admission.kind !== "admitted") return admission;
1301
1633
  settleArgs = admission.settleArgs;
1302
1634
  }
1303
1635
  try {
1304
1636
  return await settleAndDeliver(flow, resource, validInput, settleArgs, pipelineStart);
1637
+ } catch (error) {
1638
+ if (settleArgs?.retry !== void 0) await retryGate.finishFailed(flow, settleArgs.retry);
1639
+ throw error;
1305
1640
  } finally {
1306
1641
  await recordStep(flow, { kind: "completed", ...failuresOf(flow) });
1307
1642
  }
@@ -1323,13 +1658,14 @@ function createExecutionPipeline(options) {
1323
1658
  deadlineAt: backendDeadline(options.clock.now(), resource)
1324
1659
  });
1325
1660
  const backendStart = options.clock.monotonicMs();
1661
+ const idempotencyKey = request.idempotencyKey ?? settleArgs?.merchantKey;
1326
1662
  let backendResponse;
1327
1663
  try {
1328
1664
  backendResponse = await options.backend.call(resource.handler, {
1329
1665
  requestId: request.requestId,
1330
1666
  resourceId: resource.id,
1331
1667
  input: validInput,
1332
- ...request.idempotencyKey !== void 0 ? { idempotencyKey: request.idempotencyKey } : {},
1668
+ ...idempotencyKey !== void 0 ? { idempotencyKey } : {},
1333
1669
  ...request.backendHeaders !== void 0 ? { backendHeaders: request.backendHeaders } : {}
1334
1670
  });
1335
1671
  } catch (error) {
@@ -1422,6 +1758,15 @@ function createExecutionPipeline(options) {
1422
1758
  transactionId: flow.transactionId
1423
1759
  };
1424
1760
  await saveReceipt(flow, receipt, "saveReceipt");
1761
+ if (settleArgs?.retry !== void 0) {
1762
+ await retryGate.finishDelivered(
1763
+ flow,
1764
+ settleArgs.retry,
1765
+ settleArgs.verification,
1766
+ backendResponse,
1767
+ receipt
1768
+ );
1769
+ }
1425
1770
  const totalDurationMs = Math.round(options.clock.monotonicMs() - pipelineStart);
1426
1771
  const failures = failuresOf(flow);
1427
1772
  await safeEmit(
@@ -1523,6 +1868,6 @@ function createStoreEventSink(options) {
1523
1868
  };
1524
1869
  }
1525
1870
 
1526
- export { ACP_API_VERSION, ACP_API_VERSION_HEADER, ACP_CHECKOUT_OPERATIONS, ACP_FORWARDED_HEADERS, ACP_IDEMPOTENCY_KEY_HEADER, ACP_IDEMPOTENT_REPLAYED_HEADER, ACP_IN_FLIGHT_RETRY_AFTER_SECONDS, ACP_JSON_MEDIA_TYPE, ACP_MAX_FORWARDED_HEADER_LENGTH, ACP_MAX_REQUEST_ID_LENGTH, ACP_MERCHANT_RETRY_AFTER_DEFAULT_SECONDS, ACP_MERCHANT_RETRY_AFTER_MAX_SECONDS, ACP_OPERATION_INPUT_KEYS, ACP_OPERATION_OPTIONAL_INPUT_KEYS, ACP_REQUEST_ID_HEADER, ACP_SESSION_ID_INPUT_KEY, ACP_SPEC_VERSION, ACP_WELL_KNOWN_PATH, BackendErrorResponse, DEFAULT_CONFIG_FILENAME, HttpBackendExecutor, createExecutionPipeline, createResourceRegistry, createStoreEventSink, extractPathParameterNames, findUnparsedBraceToken, isObjectSchemaNode };
1527
- //# sourceMappingURL=chunk-PTL7SNOI.js.map
1528
- //# sourceMappingURL=chunk-PTL7SNOI.js.map
1871
+ export { ACP_API_VERSION, ACP_API_VERSION_HEADER, ACP_CHECKOUT_OPERATIONS, ACP_FORWARDED_HEADERS, ACP_IDEMPOTENCY_KEY_HEADER, ACP_IDEMPOTENT_REPLAYED_HEADER, ACP_IN_FLIGHT_RETRY_AFTER_SECONDS, ACP_JSON_MEDIA_TYPE, ACP_MAX_FORWARDED_HEADER_LENGTH, ACP_MAX_REQUEST_ID_LENGTH, ACP_MERCHANT_RETRY_AFTER_DEFAULT_SECONDS, ACP_MERCHANT_RETRY_AFTER_MAX_SECONDS, ACP_OPERATION_INPUT_KEYS, ACP_OPERATION_OPTIONAL_INPUT_KEYS, ACP_REQUEST_ID_HEADER, ACP_SESSION_ID_INPUT_KEY, ACP_SPEC_VERSION, ACP_WELL_KNOWN_PATH, BackendErrorResponse, DEFAULT_CONFIG_FILENAME, HttpBackendExecutor, MAX_REDELIVERY_RETENTION_HOURS, assertRetrySupport, createExecutionPipeline, createResourceRegistry, createStoreEventSink, extractPathParameterNames, findUnparsedBraceToken, isObjectSchemaNode };
1872
+ //# sourceMappingURL=chunk-OETKXDGA.js.map
1873
+ //# sourceMappingURL=chunk-OETKXDGA.js.map