@devlab.group/agent-commerce 2.4.1 → 2.6.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 (126) hide show
  1. package/README.md +168 -16
  2. package/dist/ap2.d.ts +42 -17
  3. package/dist/ap2.js +83 -27
  4. package/dist/ap2.js.map +1 -1
  5. package/dist/{chunk-CXWC5LWM.js → chunk-DRLBML7Z.js} +661 -75
  6. package/dist/chunk-DRLBML7Z.js.map +1 -0
  7. package/dist/{chunk-WZW5ORZH.js → chunk-G3EYYHKF.js} +3 -3
  8. package/dist/{chunk-WZW5ORZH.js.map → chunk-G3EYYHKF.js.map} +1 -1
  9. package/dist/chunk-GA3O2A7R.js +92 -0
  10. package/dist/chunk-GA3O2A7R.js.map +1 -0
  11. package/dist/{chunk-DTKU3Z2M.js → chunk-M52FBNJX.js} +36 -5
  12. package/dist/chunk-M52FBNJX.js.map +1 -0
  13. package/dist/chunk-M6BSXXTF.js +8 -0
  14. package/dist/chunk-M6BSXXTF.js.map +1 -0
  15. package/dist/{chunk-QPV3EGJO.js → chunk-M6MQ3FYS.js} +25 -4
  16. package/dist/chunk-M6MQ3FYS.js.map +1 -0
  17. package/dist/chunk-M6WW6QIT.js +18 -0
  18. package/dist/chunk-M6WW6QIT.js.map +1 -0
  19. package/dist/cli/{ap2-GWSP4LYY.js → ap2-2YMYA2H6.js} +85 -29
  20. package/dist/cli/ap2-2YMYA2H6.js.map +1 -0
  21. package/dist/cli/{chunk-OZ4LAWBK.js → chunk-3NOMLMJW.js} +29 -8
  22. package/dist/cli/chunk-3NOMLMJW.js.map +1 -0
  23. package/dist/cli/chunk-4KLYFXMW.js +8 -0
  24. package/dist/cli/{chunk-ITWNSS2B.js.map → chunk-4KLYFXMW.js.map} +1 -1
  25. package/dist/cli/chunk-663ALDZA.js +92 -0
  26. package/dist/cli/chunk-663ALDZA.js.map +1 -0
  27. package/dist/cli/chunk-6R6WJ4FD.js +18 -0
  28. package/dist/cli/chunk-6R6WJ4FD.js.map +1 -0
  29. package/dist/cli/{chunk-G2JEY7MB.js → chunk-AZL7RPFU.js} +39 -33
  30. package/dist/cli/chunk-AZL7RPFU.js.map +1 -0
  31. package/dist/cli/chunk-DHFMIBPG.js +107 -0
  32. package/dist/cli/chunk-DHFMIBPG.js.map +1 -0
  33. package/dist/cli/{chunk-QQ3WY5L3.js → chunk-GET3CZGR.js} +36 -104
  34. package/dist/cli/chunk-GET3CZGR.js.map +1 -0
  35. package/dist/cli/chunk-NSYSMDQN.js +1544 -0
  36. package/dist/cli/chunk-NSYSMDQN.js.map +1 -0
  37. package/dist/cli/{chunk-PIMFPCNZ.js → chunk-PTL7SNOI.js} +313 -138
  38. package/dist/cli/chunk-PTL7SNOI.js.map +1 -0
  39. package/dist/cli/chunk-SYQLJXIU.js +105 -0
  40. package/dist/cli/chunk-SYQLJXIU.js.map +1 -0
  41. package/dist/cli/chunk-TFV3K6YS.js +373 -0
  42. package/dist/cli/chunk-TFV3K6YS.js.map +1 -0
  43. package/dist/cli/{chunk-3MGAJ5FX.js → chunk-VJ4EO4LE.js} +3 -3
  44. package/dist/cli/{chunk-3MGAJ5FX.js.map → chunk-VJ4EO4LE.js.map} +1 -1
  45. package/dist/cli/chunk-VJH6RYRK.js +119 -0
  46. package/dist/cli/chunk-VJH6RYRK.js.map +1 -0
  47. package/dist/cli/{chunk-TNMLDPUO.js → chunk-YOF7IK4V.js} +663 -77
  48. package/dist/cli/chunk-YOF7IK4V.js.map +1 -0
  49. package/dist/cli/{chunk-WYOGIANL.js → chunk-YWG2ZN3L.js} +4 -4
  50. package/dist/cli/{chunk-WYOGIANL.js.map → chunk-YWG2ZN3L.js.map} +1 -1
  51. package/dist/cli/config-3K65QJ22.js +12 -0
  52. package/dist/cli/{config-UI4EDG4L.js.map → config-3K65QJ22.js.map} +1 -1
  53. package/dist/cli/index.js +753 -212
  54. package/dist/cli/index.js.map +1 -1
  55. package/dist/cli/{mcp-PGBRWZVA.js → mcp-6F64A7KE.js} +5 -4
  56. package/dist/cli/mcp-6F64A7KE.js.map +1 -0
  57. package/dist/cli/{near-5AY3HWYF.js → near-U6365VFX.js} +15 -4
  58. package/dist/cli/near-U6365VFX.js.map +1 -0
  59. package/dist/cli/payment-providers-2ITS6KNR.js +6 -0
  60. package/dist/cli/payment-providers-2ITS6KNR.js.map +1 -0
  61. package/dist/cli/{provider-I2ESL6RS.js → provider-5BGG5YKQ.js} +53 -24
  62. package/dist/cli/provider-5BGG5YKQ.js.map +1 -0
  63. package/dist/cli/receipts-I4IIE7U6.js +8 -0
  64. package/dist/cli/receipts-I4IIE7U6.js.map +1 -0
  65. package/dist/cli/reconcile-55WNCSFC.js +4 -0
  66. package/dist/cli/reconcile-55WNCSFC.js.map +1 -0
  67. package/dist/cli/{run-JK4ERPJV.js → run-2P6ZGFUE.js} +356 -173
  68. package/dist/cli/run-2P6ZGFUE.js.map +1 -0
  69. package/dist/cli/svm-KDSPDFJG.js +48 -0
  70. package/dist/cli/svm-KDSPDFJG.js.map +1 -0
  71. package/dist/cli/{x402-7WBFZQXV.js → x402-4LPIIELI.js} +10 -9
  72. package/dist/cli/x402-4LPIIELI.js.map +1 -0
  73. package/dist/index.d.ts +116 -113
  74. package/dist/index.js +1928 -351
  75. package/dist/index.js.map +1 -1
  76. package/dist/logger-CllGwQ8i.d.ts +19 -0
  77. package/dist/mcp.d.ts +3 -2
  78. package/dist/mcp.js +2 -1
  79. package/dist/mcp.js.map +1 -1
  80. package/dist/mpp.d.ts +2 -1
  81. package/dist/mpp.js +48 -19
  82. package/dist/mpp.js.map +1 -1
  83. package/dist/{near-D6C42VPE.js → near-FH7HPZV3.js} +15 -4
  84. package/dist/near-FH7HPZV3.js.map +1 -0
  85. package/dist/{protocol-adapter-C9odYl6l.d.ts → protocol-adapter-1WbtM3xG.d.ts} +12 -85
  86. package/dist/{runtime-Cl_BLVZV.d.ts → runtime-B-kARa2f.d.ts} +218 -15
  87. package/dist/store-kIIMpUA-.d.ts +372 -0
  88. package/dist/svm-KNC3PHMS.js +48 -0
  89. package/dist/svm-KNC3PHMS.js.map +1 -0
  90. package/dist/testing.d.ts +51 -0
  91. package/dist/testing.js +1896 -0
  92. package/dist/testing.js.map +1 -0
  93. package/dist/transaction-Dv0UFGg5.d.ts +129 -0
  94. package/dist/{types-j7MnUXYN.d.ts → types-DWqjz81-.d.ts} +5 -2
  95. package/dist/x402.d.ts +2 -1
  96. package/dist/x402.js +6 -5
  97. package/dist/x402.js.map +1 -1
  98. package/package.json +5 -1
  99. package/dist/authorization-DjAecwuW.d.ts +0 -115
  100. package/dist/chunk-CXWC5LWM.js.map +0 -1
  101. package/dist/chunk-DTKU3Z2M.js.map +0 -1
  102. package/dist/chunk-KA2AX5FH.js +0 -44
  103. package/dist/chunk-KA2AX5FH.js.map +0 -1
  104. package/dist/chunk-QPV3EGJO.js.map +0 -1
  105. package/dist/cli/ap2-GWSP4LYY.js.map +0 -1
  106. package/dist/cli/chunk-G2JEY7MB.js.map +0 -1
  107. package/dist/cli/chunk-GJIMDMYT.js +0 -639
  108. package/dist/cli/chunk-GJIMDMYT.js.map +0 -1
  109. package/dist/cli/chunk-ITWNSS2B.js +0 -8
  110. package/dist/cli/chunk-OSTCU6ZK.js +0 -44
  111. package/dist/cli/chunk-OSTCU6ZK.js.map +0 -1
  112. package/dist/cli/chunk-OZ4LAWBK.js.map +0 -1
  113. package/dist/cli/chunk-PIMFPCNZ.js.map +0 -1
  114. package/dist/cli/chunk-QQ3WY5L3.js.map +0 -1
  115. package/dist/cli/chunk-TNMLDPUO.js.map +0 -1
  116. package/dist/cli/config-UI4EDG4L.js +0 -11
  117. package/dist/cli/mcp-PGBRWZVA.js.map +0 -1
  118. package/dist/cli/near-5AY3HWYF.js.map +0 -1
  119. package/dist/cli/provider-I2ESL6RS.js.map +0 -1
  120. package/dist/cli/run-JK4ERPJV.js.map +0 -1
  121. package/dist/cli/svm-3MMYFPC7.js +0 -33
  122. package/dist/cli/svm-3MMYFPC7.js.map +0 -1
  123. package/dist/cli/x402-7WBFZQXV.js.map +0 -1
  124. package/dist/near-D6C42VPE.js.map +0 -1
  125. package/dist/svm-QEUAUNPQ.js +0 -33
  126. package/dist/svm-QEUAUNPQ.js.map +0 -1
@@ -0,0 +1,1544 @@
1
+ import { openSqliteDatabase } from './chunk-VJ4EO4LE.js';
2
+ import { PACKAGE_VERSION } from './chunk-4KLYFXMW.js';
3
+ import { NOOP_LOGGER, systemClock, transactionState, RESERVED_INPUT_FIELDS } from './chunk-GET3CZGR.js';
4
+ import { CommerceError, toCommerceError } from './chunk-SYQLJXIU.js';
5
+ import { accessSync, constants, existsSync } from 'fs';
6
+ import { resolve } from 'path';
7
+ import Database from 'better-sqlite3';
8
+ import { randomUUID } from 'crypto';
9
+
10
+ // src/storage/receipts/schema.ts
11
+ var MIGRATIONS = [
12
+ {
13
+ version: 1,
14
+ up(db) {
15
+ db.exec(`
16
+ CREATE TABLE IF NOT EXISTS receipts (
17
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
18
+ id TEXT NOT NULL UNIQUE,
19
+ request_id TEXT NOT NULL,
20
+ resource_id TEXT NOT NULL,
21
+ payment_json TEXT,
22
+ delivered_at TEXT NOT NULL,
23
+ backend_status INTEGER NOT NULL,
24
+ duration_ms INTEGER,
25
+ protocol TEXT,
26
+ metadata_json TEXT
27
+ );
28
+ CREATE INDEX IF NOT EXISTS idx_receipts_request_id ON receipts(request_id);
29
+ CREATE INDEX IF NOT EXISTS idx_receipts_delivered_at ON receipts(delivered_at);
30
+
31
+ CREATE TABLE IF NOT EXISTS events (
32
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
33
+ id TEXT NOT NULL UNIQUE,
34
+ type TEXT NOT NULL,
35
+ request_id TEXT NOT NULL,
36
+ resource_id TEXT,
37
+ at TEXT NOT NULL,
38
+ adapter TEXT,
39
+ payment_provider TEXT,
40
+ duration_ms INTEGER,
41
+ status TEXT,
42
+ data_json TEXT
43
+ );
44
+ CREATE INDEX IF NOT EXISTS idx_events_request_id ON events(request_id);
45
+ CREATE INDEX IF NOT EXISTS idx_events_at ON events(at);
46
+
47
+ CREATE TABLE IF NOT EXISTS payment_attempts (
48
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
49
+ id TEXT NOT NULL UNIQUE,
50
+ request_id TEXT NOT NULL,
51
+ resource_id TEXT NOT NULL,
52
+ provider TEXT NOT NULL,
53
+ replay_key TEXT NOT NULL UNIQUE,
54
+ status TEXT NOT NULL,
55
+ amount TEXT NOT NULL,
56
+ currency TEXT NOT NULL,
57
+ payer TEXT,
58
+ payee TEXT,
59
+ external_reference TEXT,
60
+ rejection_reason TEXT,
61
+ created_at TEXT NOT NULL,
62
+ updated_at TEXT NOT NULL
63
+ );
64
+ CREATE INDEX IF NOT EXISTS idx_payment_attempts_request_id ON payment_attempts(request_id);
65
+ CREATE INDEX IF NOT EXISTS idx_payment_attempts_created_at ON payment_attempts(created_at);
66
+ `);
67
+ }
68
+ },
69
+ {
70
+ version: 2,
71
+ up(db) {
72
+ db.exec(`ALTER TABLE receipts ADD COLUMN authorization_json TEXT;`);
73
+ }
74
+ },
75
+ {
76
+ version: 3,
77
+ up(db) {
78
+ db.exec(`
79
+ CREATE TABLE IF NOT EXISTS payment_attempt_history (
80
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
81
+ id TEXT NOT NULL,
82
+ request_id TEXT NOT NULL,
83
+ resource_id TEXT NOT NULL,
84
+ provider TEXT NOT NULL,
85
+ replay_key TEXT NOT NULL,
86
+ status TEXT NOT NULL,
87
+ amount TEXT NOT NULL,
88
+ currency TEXT NOT NULL,
89
+ payer TEXT,
90
+ payee TEXT,
91
+ external_reference TEXT,
92
+ rejection_reason TEXT,
93
+ created_at TEXT NOT NULL,
94
+ updated_at TEXT NOT NULL,
95
+ superseded_at TEXT NOT NULL
96
+ );
97
+ CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_replay_key ON payment_attempt_history(replay_key);
98
+ CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_request_id ON payment_attempt_history(request_id);
99
+ `);
100
+ }
101
+ },
102
+ {
103
+ version: 4,
104
+ up(db) {
105
+ db.exec(`
106
+ CREATE TABLE IF NOT EXISTS transactions (
107
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
108
+ id TEXT NOT NULL UNIQUE,
109
+ request_id TEXT NOT NULL,
110
+ resource_id TEXT NOT NULL,
111
+ protocol TEXT NOT NULL,
112
+ state TEXT NOT NULL,
113
+ provider TEXT NOT NULL,
114
+ attempt_id TEXT NOT NULL,
115
+ replay_key TEXT NOT NULL,
116
+ network TEXT,
117
+ asset TEXT,
118
+ authorization_json TEXT,
119
+ reservation_id TEXT,
120
+ locator_json TEXT,
121
+ expires_at TEXT,
122
+ input_digest TEXT,
123
+ config_digest TEXT NOT NULL,
124
+ settling_at TEXT,
125
+ backend_dispatched_at TEXT,
126
+ backend_deadline_at TEXT,
127
+ backend_status INTEGER,
128
+ backend_error_code TEXT,
129
+ receipt_id TEXT,
130
+ persistence_failures_json TEXT,
131
+ completed_at TEXT,
132
+ created_at TEXT NOT NULL,
133
+ updated_at TEXT NOT NULL
134
+ );
135
+ CREATE INDEX IF NOT EXISTS idx_transactions_state_seq ON transactions(state, seq);
136
+ CREATE INDEX IF NOT EXISTS idx_transactions_request_id ON transactions(request_id);
137
+ CREATE INDEX IF NOT EXISTS idx_transactions_replay_key ON transactions(replay_key);
138
+
139
+ ALTER TABLE receipts ADD COLUMN transaction_id TEXT;
140
+ ALTER TABLE events ADD COLUMN transaction_id TEXT;
141
+ ALTER TABLE payment_attempts ADD COLUMN transaction_id TEXT;
142
+ ALTER TABLE payment_attempts ADD COLUMN resolution_json TEXT;
143
+ ALTER TABLE payment_attempt_history ADD COLUMN transaction_id TEXT;
144
+ ALTER TABLE payment_attempt_history ADD COLUMN resolution_json TEXT;
145
+ CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_id ON payment_attempt_history(id);
146
+ `);
147
+ }
148
+ },
149
+ {
150
+ version: 5,
151
+ up(db) {
152
+ db.exec(`
153
+ CREATE TABLE IF NOT EXISTS authorization_holds (
154
+ reference TEXT PRIMARY KEY,
155
+ method TEXT NOT NULL,
156
+ binding_reference TEXT NOT NULL,
157
+ resource_id TEXT NOT NULL,
158
+ request_id TEXT NOT NULL,
159
+ state TEXT NOT NULL
160
+ CHECK (state IN ('reserved', 'consumed', 'released', 'uncertain')),
161
+ metadata_json TEXT,
162
+ created_at TEXT NOT NULL,
163
+ updated_at TEXT NOT NULL
164
+ );
165
+ CREATE INDEX IF NOT EXISTS idx_authorization_holds_binding ON authorization_holds(binding_reference);
166
+ CREATE INDEX IF NOT EXISTS idx_authorization_holds_request_id ON authorization_holds(request_id);
167
+ CREATE INDEX IF NOT EXISTS idx_authorization_holds_state_updated ON authorization_holds(state, updated_at);
168
+
169
+ CREATE TABLE IF NOT EXISTS idempotency_keys (
170
+ deployment TEXT NOT NULL,
171
+ endpoint TEXT NOT NULL,
172
+ idempotency_key TEXT NOT NULL,
173
+ fingerprint TEXT NOT NULL,
174
+ state TEXT NOT NULL,
175
+ status INTEGER,
176
+ body_json TEXT,
177
+ created_at TEXT NOT NULL,
178
+ expires_at TEXT NOT NULL,
179
+ PRIMARY KEY (deployment, endpoint, idempotency_key)
180
+ );
181
+ CREATE INDEX IF NOT EXISTS idx_idempotency_keys_expires_at ON idempotency_keys(expires_at);
182
+
183
+ CREATE TABLE IF NOT EXISTS pending_tasks (
184
+ id TEXT PRIMARY KEY,
185
+ protocol TEXT NOT NULL,
186
+ resource_id TEXT NOT NULL,
187
+ input_json TEXT NOT NULL,
188
+ adapter_data_json TEXT,
189
+ created_at TEXT NOT NULL,
190
+ expires_at TEXT NOT NULL
191
+ );
192
+ CREATE INDEX IF NOT EXISTS idx_pending_tasks_expires_at ON pending_tasks(expires_at);
193
+
194
+ -- path is NULL when the feature started with nothing to import
195
+ CREATE TABLE IF NOT EXISTS legacy_imports (
196
+ source TEXT PRIMARY KEY,
197
+ path TEXT,
198
+ rows INTEGER NOT NULL,
199
+ imported_at TEXT NOT NULL
200
+ );
201
+ `);
202
+ }
203
+ }
204
+ ];
205
+ var SCHEMA_VERSION = MIGRATIONS.at(-1)?.version ?? 0;
206
+ function hasTable(db, name) {
207
+ return db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== void 0;
208
+ }
209
+ function migrate(db, target = SCHEMA_VERSION) {
210
+ const current = db.pragma("user_version", { simple: true });
211
+ for (const migration of MIGRATIONS) {
212
+ if (migration.version <= current || migration.version > target) continue;
213
+ const apply = db.transaction(() => {
214
+ migration.up(db);
215
+ db.pragma(`user_version = ${migration.version}`);
216
+ });
217
+ apply();
218
+ }
219
+ }
220
+
221
+ // src/storage/receipts/legacy-import.ts
222
+ var NOTHING = { rows: 0, write: () => {
223
+ } };
224
+ var SOURCES = [
225
+ {
226
+ name: "ap2-replay",
227
+ option: "ap2Replay",
228
+ feature: "ap2",
229
+ key: "authorization.ap2.replay.path",
230
+ usedSql: `SELECT 1 FROM receipts WHERE authorization_json IS NOT NULL
231
+ UNION ALL SELECT 1 FROM transactions WHERE authorization_json IS NOT NULL LIMIT 1`,
232
+ read(file) {
233
+ if (!hasTable(file, "ap2_authorizations")) return NOTHING;
234
+ const rows = file.prepare(
235
+ `SELECT reference, checkout_jti, mandate_issuer, checkout_issuer, resource_id,
236
+ request_id, state, created_at, updated_at
237
+ FROM ap2_authorizations`
238
+ ).all();
239
+ return {
240
+ rows: rows.length,
241
+ write(db) {
242
+ const insert = db.prepare(
243
+ `INSERT INTO authorization_holds
244
+ (reference, method, binding_reference, resource_id, request_id, state,
245
+ metadata_json, created_at, updated_at)
246
+ VALUES (@reference, 'ap2', @checkout_jti, @resource_id, @request_id, @state,
247
+ @metadata_json, @created_at, @updated_at)
248
+ ON CONFLICT (reference) DO UPDATE SET
249
+ binding_reference = excluded.binding_reference, resource_id = excluded.resource_id,
250
+ request_id = excluded.request_id, state = excluded.state,
251
+ metadata_json = excluded.metadata_json, updated_at = excluded.updated_at
252
+ WHERE authorization_holds.state = 'released'`
253
+ );
254
+ for (const row of rows) {
255
+ insert.run({
256
+ ...row,
257
+ metadata_json: JSON.stringify({
258
+ mandateIssuer: row.mandate_issuer,
259
+ checkoutIssuer: row.checkout_issuer
260
+ })
261
+ });
262
+ }
263
+ }
264
+ };
265
+ }
266
+ },
267
+ {
268
+ name: "acp-idempotency",
269
+ option: "acpIdempotency",
270
+ feature: "acp",
271
+ key: "protocols.acp.idempotency.path",
272
+ usedSql: "SELECT 1 FROM events WHERE adapter = 'acp' LIMIT 1",
273
+ read(file, logger) {
274
+ if (!hasTable(file, "acp_idempotency")) return NOTHING;
275
+ if (file.pragma("user_version", { simple: true }) < 2) {
276
+ const { count } = file.prepare("SELECT COUNT(*) AS count FROM acp_idempotency WHERE state != 'completed'").get();
277
+ if (count > 0) {
278
+ logger.warn(
279
+ { unresolved: count },
280
+ "acp idempotency: the schema v1 file holds claims keyed by an old bearer-token digest, which are not imported; reconcile these operations against the merchant before trusting a retry"
281
+ );
282
+ }
283
+ return NOTHING;
284
+ }
285
+ const rows = file.prepare(
286
+ `SELECT deployment, endpoint, idempotency_key, fingerprint, state, status, body_json,
287
+ created_at, expires_at
288
+ FROM acp_idempotency`
289
+ ).all();
290
+ return {
291
+ rows: rows.length,
292
+ write(db) {
293
+ const insert = db.prepare(
294
+ `INSERT INTO idempotency_keys
295
+ (deployment, endpoint, idempotency_key, fingerprint, state, status, body_json,
296
+ created_at, expires_at)
297
+ VALUES (@deployment, @endpoint, @idempotency_key, @fingerprint, @state, @status,
298
+ @body_json, @created_at, @expires_at)
299
+ ON CONFLICT DO NOTHING`
300
+ );
301
+ for (const row of rows) insert.run(row);
302
+ }
303
+ };
304
+ }
305
+ }
306
+ ];
307
+ function storageError(message, details, cause) {
308
+ return new CommerceError("STORAGE_ERROR", message, { details, cause });
309
+ }
310
+ function selectMarker(db, source) {
311
+ return db.prepare("SELECT path FROM legacy_imports WHERE source = ?").get(source);
312
+ }
313
+ var usedBefore = (db, source) => db.prepare(source.usedSql).get() !== void 0;
314
+ function missingLegacyImports(db) {
315
+ const recorded = hasTable(db, "legacy_imports");
316
+ return SOURCES.filter(
317
+ (source) => !(recorded && selectMarker(db, source.name) !== void 0) && usedBefore(db, source)
318
+ ).map((source) => source.name);
319
+ }
320
+ function readMissingLegacyImports(path) {
321
+ let db;
322
+ try {
323
+ db = new Database(path, { readonly: true, fileMustExist: true });
324
+ return missingLegacyImports(db);
325
+ } catch {
326
+ return void 0;
327
+ } finally {
328
+ db?.close();
329
+ }
330
+ }
331
+ function importLegacyStores(db, receiptsPath, options, clock, logger) {
332
+ const recordMarker = db.prepare(
333
+ `INSERT INTO legacy_imports (source, path, rows, imported_at) VALUES (?, ?, ?, ?)
334
+ ON CONFLICT (source) DO UPDATE SET
335
+ path = excluded.path, rows = excluded.rows, imported_at = excluded.imported_at`
336
+ );
337
+ const locks = [];
338
+ const release = () => {
339
+ for (const lock of locks.splice(0)) lock.close();
340
+ };
341
+ try {
342
+ for (const source of SOURCES) {
343
+ const given = options[source.option];
344
+ const marker = selectMarker(db, source.name);
345
+ const importedPath = marker?.path ?? void 0;
346
+ const path = given !== void 0 && given !== ":memory:" ? resolve(given) : void 0;
347
+ if (path !== void 0 && receiptsPath !== ":memory:" && path === resolve(receiptsPath)) {
348
+ throw storageError(`${source.key} names the receipt database "${path}"`, {
349
+ key: source.key,
350
+ path
351
+ });
352
+ }
353
+ if (path !== void 0 && importedPath !== void 0 && importedPath !== path) {
354
+ throw storageError(
355
+ `${source.key} names "${path}", but "${importedPath}" was imported from it already. Point ${source.key} back at the imported file, or remove the key.`,
356
+ { key: source.key, path, importedPath }
357
+ );
358
+ }
359
+ if (path === void 0 || !existsSync(path)) {
360
+ if (marker === void 0 && options.enabled?.[source.feature] === true) {
361
+ if (given !== ":memory:" && usedBefore(db, source)) {
362
+ throw forgottenKey(source, path);
363
+ }
364
+ recordMarker.run(source.name, null, 0, clock.nowIso());
365
+ }
366
+ if (given !== void 0) {
367
+ logger.info(
368
+ { key: source.key, path: path ?? given },
369
+ "deprecated store has no file to import; the key can be removed"
370
+ );
371
+ }
372
+ continue;
373
+ }
374
+ let file;
375
+ try {
376
+ file = new Database(path, { fileMustExist: true });
377
+ file.exec("BEGIN EXCLUSIVE");
378
+ } catch (cause) {
379
+ file?.close();
380
+ const cantOpen = cause.code === "SQLITE_CANTOPEN";
381
+ if (importedPath !== void 0 && cantOpen) {
382
+ logger.warn(
383
+ { key: source.key, path },
384
+ "deprecated store file cannot be opened to lock it; its rows are already imported"
385
+ );
386
+ continue;
387
+ }
388
+ throw storageError(
389
+ cantOpen ? `${source.key} "${path}" cannot be opened to import it, as on a read-only mount. Make its directory writable for the first start of this version, or copy the file somewhere writable and point the key at the copy.` : `${source.key} "${path}" cannot be locked for import: ${cause instanceof Error ? cause.message : String(cause)}`,
390
+ { key: source.key, path },
391
+ cause
392
+ );
393
+ }
394
+ locks.push(file);
395
+ if (importedPath !== void 0) continue;
396
+ let imported;
397
+ try {
398
+ imported = source.read(file, logger);
399
+ } catch (cause) {
400
+ throw storageError(
401
+ `${source.key} "${path}" cannot be read for import: ${cause instanceof Error ? cause.message : String(cause)}`,
402
+ { key: source.key, path },
403
+ cause
404
+ );
405
+ }
406
+ db.transaction(() => {
407
+ imported.write(db);
408
+ recordMarker.run(source.name, path, imported.rows, clock.nowIso());
409
+ })();
410
+ logger.info(
411
+ { key: source.key, path, rows: imported.rows },
412
+ "imported deprecated store file; it stays locked against writes while this gateway runs"
413
+ );
414
+ }
415
+ } catch (err) {
416
+ release();
417
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to import deprecated store files");
418
+ }
419
+ return release;
420
+ }
421
+ function forgottenKey(source, path) {
422
+ return storageError(
423
+ `${source.feature.toUpperCase()} ran on this receipt database before, but ${source.key} ${path === void 0 ? "is not set" : `names a missing file "${path}"`}, so its records would be lost. Set ${source.key} to the file the previous version used to import them, or to an empty file to accept the loss.`,
424
+ { key: source.key, ...path !== void 0 ? { path } : {} }
425
+ );
426
+ }
427
+
428
+ // src/storage/receipts/params.ts
429
+ var DEFAULT_LIST_LIMIT = 50;
430
+ var MAX_LIST_LIMIT = 500;
431
+ function clampListLimit(limit) {
432
+ const base = limit !== void 0 && Number.isFinite(limit) ? limit : DEFAULT_LIST_LIMIT;
433
+ return Math.min(Math.max(Math.trunc(base), 1), MAX_LIST_LIMIT);
434
+ }
435
+ function storedIso(value, field) {
436
+ const ms = Date.parse(value);
437
+ if (!Number.isFinite(ms)) {
438
+ throw new CommerceError("STORAGE_ERROR", `${field} is not a valid timestamp`);
439
+ }
440
+ return new Date(ms).toISOString();
441
+ }
442
+
443
+ // src/storage/receipts/redact.ts
444
+ var SECRET_KEY_PATTERN = /private[-_ ]?key|secret|password|mnemonic|seed[-_ ]?phrase|api[-_ ]?key|authoriz(e|ation)|^auth$|auth[-_]?header|payment[-_ ]?proof|^proof$|x-payment|signature|signed[-_ ]?message|token|bearer|credential|cookie|session|jwt/i;
445
+ var REDACTED = "[REDACTED]";
446
+ function isSecretKey(key) {
447
+ return SECRET_KEY_PATTERN.test(key);
448
+ }
449
+ function redact(value) {
450
+ return redactValue(value);
451
+ }
452
+ function redactValue(value) {
453
+ if (Array.isArray(value)) {
454
+ return value.map(redactValue);
455
+ }
456
+ if (value !== null && typeof value === "object") {
457
+ const out = {};
458
+ for (const [key, inner] of Object.entries(value)) {
459
+ out[key] = isSecretKey(key) ? REDACTED : redactValue(inner);
460
+ }
461
+ return out;
462
+ }
463
+ return value;
464
+ }
465
+
466
+ // src/storage/receipts/holds.ts
467
+ var TRANSITION_TARGETS = /* @__PURE__ */ new Set(["consumed", "released", "uncertain"]);
468
+ var ORPHAN_HOLD_WHERE = `h.state = 'reserved' AND h.updated_at < ?
469
+ AND NOT EXISTS (SELECT 1 FROM payment_attempts a WHERE a.request_id = h.request_id)
470
+ AND NOT EXISTS (SELECT 1 FROM payment_attempt_history p WHERE p.request_id = h.request_id)`;
471
+ function rowToHold(row) {
472
+ return {
473
+ method: row.method,
474
+ reference: row.reference,
475
+ bindingReference: row.binding_reference,
476
+ resourceId: row.resource_id,
477
+ requestId: row.request_id,
478
+ ...row.metadata_json !== null ? { metadata: JSON.parse(row.metadata_json) } : {},
479
+ state: row.state,
480
+ createdAt: row.created_at,
481
+ updatedAt: row.updated_at
482
+ };
483
+ }
484
+ function createHoldMethods(db, clock) {
485
+ const selectHold = db.prepare(
486
+ "SELECT * FROM authorization_holds WHERE reference = ?"
487
+ );
488
+ const selectLiveBinding = db.prepare(
489
+ `SELECT state FROM authorization_holds
490
+ WHERE binding_reference = ? AND reference != ? AND state != 'released' LIMIT 1`
491
+ );
492
+ const insertHold = db.prepare(
493
+ `INSERT INTO authorization_holds
494
+ (reference, method, binding_reference, resource_id, request_id, state, metadata_json, created_at, updated_at)
495
+ VALUES (@reference, @method, @binding_reference, @resource_id, @request_id, 'reserved', @metadata_json, @at, @at)`
496
+ );
497
+ const reReserveHold = db.prepare(
498
+ `UPDATE authorization_holds
499
+ SET state = 'reserved', method = @method, binding_reference = @binding_reference,
500
+ resource_id = @resource_id, request_id = @request_id,
501
+ metadata_json = @metadata_json, updated_at = @at
502
+ WHERE reference = @reference AND state = 'released'`
503
+ );
504
+ const transitionHold = db.prepare(
505
+ `UPDATE authorization_holds SET state = @state, updated_at = @at
506
+ WHERE reference = @reference AND state IN ('reserved', 'uncertain')
507
+ AND (@request_id IS NULL OR request_id = @request_id)`
508
+ );
509
+ const listOrphans = db.prepare(
510
+ `SELECT h.* FROM authorization_holds h WHERE ${ORPHAN_HOLD_WHERE}
511
+ ORDER BY h.updated_at, h.reference LIMIT ?`
512
+ );
513
+ const reserve = db.transaction(
514
+ (reservation) => {
515
+ const existing = selectHold.get(reservation.reference);
516
+ if (existing !== void 0 && existing.state !== "released") {
517
+ return { kind: "replayed", state: existing.state };
518
+ }
519
+ const binding = selectLiveBinding.get(reservation.bindingReference, reservation.reference);
520
+ if (binding !== void 0) {
521
+ return { kind: "replayed", state: binding.state };
522
+ }
523
+ const params = {
524
+ reference: reservation.reference,
525
+ method: reservation.method,
526
+ binding_reference: reservation.bindingReference,
527
+ resource_id: reservation.resourceId,
528
+ request_id: reservation.requestId,
529
+ metadata_json: reservation.metadata !== void 0 ? JSON.stringify(redact(reservation.metadata)) : null,
530
+ at: clock.nowIso()
531
+ };
532
+ (existing !== void 0 ? reReserveHold : insertHold).run(params);
533
+ return { kind: "reserved" };
534
+ }
535
+ );
536
+ const transition = db.transaction(
537
+ (reference, to, requestId) => {
538
+ const { changes } = transitionHold.run({
539
+ reference,
540
+ state: to,
541
+ request_id: requestId ?? null,
542
+ at: clock.nowIso()
543
+ });
544
+ if (changes > 0) return true;
545
+ const row = selectHold.get(reference);
546
+ if (row === void 0) return false;
547
+ if (requestId !== void 0 && row.request_id !== requestId) return to === "released";
548
+ return row.state === to;
549
+ }
550
+ );
551
+ return {
552
+ async reserveAuthorizationHold(reservation) {
553
+ try {
554
+ return reserve.immediate(reservation);
555
+ } catch (err) {
556
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to reserve authorization hold");
557
+ }
558
+ },
559
+ async transitionAuthorizationHold(reference, to, requestId) {
560
+ try {
561
+ if (!TRANSITION_TARGETS.has(to)) {
562
+ throw new CommerceError("STORAGE_ERROR", `Invalid authorization hold target: ${to}`);
563
+ }
564
+ return transition.immediate(reference, to, requestId);
565
+ } catch (err) {
566
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to update authorization hold");
567
+ }
568
+ },
569
+ async getAuthorizationHoldState(reference) {
570
+ return selectHold.get(reference)?.state;
571
+ },
572
+ async listOrphanAuthorizationHolds(options) {
573
+ const before = storedIso(options.updatedBefore, "updatedBefore");
574
+ return listOrphans.all(before, clampListLimit(options.limit)).map(rowToHold);
575
+ }
576
+ };
577
+ }
578
+
579
+ // src/storage/receipts/idempotency.ts
580
+ var scopeParams = (scope) => ({
581
+ deployment: scope.deployment,
582
+ endpoint: scope.endpoint,
583
+ idempotency_key: scope.key
584
+ });
585
+ function createIdempotencyMethods(db, clock) {
586
+ const SCOPE = "deployment = @deployment AND endpoint = @endpoint AND idempotency_key = @idempotency_key";
587
+ const selectClaim = db.prepare(
588
+ `SELECT state, fingerprint, status, body_json FROM idempotency_keys WHERE ${SCOPE}`
589
+ );
590
+ const insertClaim = db.prepare(
591
+ `INSERT INTO idempotency_keys
592
+ (deployment, endpoint, idempotency_key, fingerprint, state, created_at, expires_at)
593
+ VALUES (@deployment, @endpoint, @idempotency_key, @fingerprint, 'in_flight', @created_at, @expires_at)`
594
+ );
595
+ const expireCompleted = db.prepare(
596
+ "DELETE FROM idempotency_keys WHERE expires_at <= ? AND state = 'completed'"
597
+ );
598
+ const completeClaim = db.prepare(
599
+ `UPDATE idempotency_keys SET state = 'completed', status = @status, body_json = @body_json
600
+ WHERE ${SCOPE}`
601
+ );
602
+ const markUnresolved = db.prepare(
603
+ `UPDATE idempotency_keys SET state = 'unresolved' WHERE ${SCOPE}`
604
+ );
605
+ const deleteClaim = db.prepare(`DELETE FROM idempotency_keys WHERE ${SCOPE}`);
606
+ const releaseInFlight = db.prepare("DELETE FROM idempotency_keys WHERE state = 'in_flight'");
607
+ const unresolveInFlight = db.prepare(
608
+ "UPDATE idempotency_keys SET state = 'unresolved' WHERE state = 'in_flight'"
609
+ );
610
+ const claim = db.transaction(
611
+ (scope, fingerprint, expiresAt) => {
612
+ const now = clock.nowIso();
613
+ expireCompleted.run(now);
614
+ const existing = selectClaim.get(scopeParams(scope));
615
+ if (existing === void 0) {
616
+ insertClaim.run({
617
+ ...scopeParams(scope),
618
+ fingerprint,
619
+ created_at: now,
620
+ expires_at: expiresAt
621
+ });
622
+ return { kind: "reserved" };
623
+ }
624
+ if (existing.fingerprint !== fingerprint) return { kind: "conflict" };
625
+ if (existing.state === "unresolved") return { kind: "unresolved" };
626
+ if (existing.state !== "completed") return { kind: "in-flight" };
627
+ return {
628
+ kind: "replay",
629
+ status: existing.status ?? 500,
630
+ body: existing.body_json === null ? null : JSON.parse(existing.body_json)
631
+ };
632
+ }
633
+ );
634
+ return {
635
+ async claimIdempotencyKey(scope, fingerprint, expiresAt) {
636
+ try {
637
+ return claim.immediate(scope, fingerprint, storedIso(expiresAt, "expiresAt"));
638
+ } catch (err) {
639
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to claim idempotency key");
640
+ }
641
+ },
642
+ async updateIdempotencyKey(scope, update) {
643
+ try {
644
+ switch (update.kind) {
645
+ case "completed":
646
+ completeClaim.run({
647
+ ...scopeParams(scope),
648
+ status: update.status,
649
+ body_json: JSON.stringify(update.body ?? null)
650
+ });
651
+ break;
652
+ case "unresolved":
653
+ markUnresolved.run(scopeParams(scope));
654
+ break;
655
+ case "released":
656
+ deleteClaim.run(scopeParams(scope));
657
+ break;
658
+ }
659
+ } catch (err) {
660
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to update idempotency key");
661
+ }
662
+ },
663
+ async recoverIdempotencyKeys(options) {
664
+ try {
665
+ return (options.release ? releaseInFlight : unresolveInFlight).run().changes;
666
+ } catch (err) {
667
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to recover idempotency keys");
668
+ }
669
+ }
670
+ };
671
+ }
672
+
673
+ // src/storage/receipts/pending-tasks.ts
674
+ function rowToTask(row) {
675
+ return {
676
+ id: row.id,
677
+ protocol: row.protocol,
678
+ resourceId: row.resource_id,
679
+ input: JSON.parse(row.input_json),
680
+ ...row.adapter_data_json !== null ? { adapterData: JSON.parse(row.adapter_data_json) } : {},
681
+ expiresAt: row.expires_at
682
+ };
683
+ }
684
+ function withoutReservedFields(input) {
685
+ return Object.fromEntries(
686
+ Object.entries(input).filter(([key]) => !RESERVED_INPUT_FIELDS.includes(key))
687
+ );
688
+ }
689
+ var SWEEP_EXPIRED = "DELETE FROM pending_tasks WHERE expires_at <= ?";
690
+ function sweepExpiredPendingTasks(db, now) {
691
+ db.prepare(SWEEP_EXPIRED).run(now);
692
+ }
693
+ function createPendingTaskMethods(db, clock) {
694
+ const sweepExpired = db.prepare(SWEEP_EXPIRED);
695
+ const countLive = db.prepare(
696
+ "SELECT COUNT(*) AS count FROM pending_tasks WHERE expires_at > ?"
697
+ );
698
+ const upsertTask = db.prepare(
699
+ `INSERT OR REPLACE INTO pending_tasks
700
+ (id, protocol, resource_id, input_json, adapter_data_json, created_at, expires_at)
701
+ VALUES (@id, @protocol, @resource_id, @input_json, @adapter_data_json, @created_at, @expires_at)`
702
+ );
703
+ const selectLive = db.prepare(
704
+ "SELECT * FROM pending_tasks WHERE id = ? AND expires_at > ?"
705
+ );
706
+ const takeLive = db.prepare(
707
+ "DELETE FROM pending_tasks WHERE id = ? AND expires_at > ? RETURNING *"
708
+ );
709
+ const put = db.transaction((task, maxTasks, expiresAt) => {
710
+ const now = clock.nowIso();
711
+ sweepExpired.run(now);
712
+ if ((countLive.get(now)?.count ?? 0) >= maxTasks) return false;
713
+ upsertTask.run({
714
+ id: task.id,
715
+ protocol: task.protocol,
716
+ resource_id: task.resourceId,
717
+ input_json: JSON.stringify(withoutReservedFields(task.input)),
718
+ adapter_data_json: task.adapterData !== void 0 ? JSON.stringify(task.adapterData) : null,
719
+ created_at: now,
720
+ expires_at: expiresAt
721
+ });
722
+ return true;
723
+ });
724
+ return {
725
+ async putPendingTask(task, options) {
726
+ try {
727
+ if (!Number.isInteger(options.maxTasks) || options.maxTasks < 0) {
728
+ throw new CommerceError("STORAGE_ERROR", "maxTasks must be a non-negative integer");
729
+ }
730
+ return put.immediate(task, options.maxTasks, storedIso(task.expiresAt, "expiresAt"));
731
+ } catch (err) {
732
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to store pending task");
733
+ }
734
+ },
735
+ async getPendingTask(id) {
736
+ const row = selectLive.get(id, clock.nowIso());
737
+ return row !== void 0 ? rowToTask(row) : void 0;
738
+ },
739
+ async takePendingTask(id) {
740
+ try {
741
+ const now = clock.nowIso();
742
+ sweepExpired.run(now);
743
+ const row = takeLive.get(id, now);
744
+ return row !== void 0 ? rowToTask(row) : void 0;
745
+ } catch (err) {
746
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to take pending task");
747
+ }
748
+ }
749
+ };
750
+ }
751
+
752
+ // src/storage/receipts/rows.ts
753
+ function receiptToRow(receipt) {
754
+ return {
755
+ id: receipt.id,
756
+ request_id: receipt.requestId,
757
+ resource_id: receipt.resourceId,
758
+ payment_json: receipt.payment !== void 0 ? JSON.stringify(redact(receipt.payment)) : null,
759
+ delivered_at: receipt.deliveredAt,
760
+ backend_status: receipt.backendStatus,
761
+ duration_ms: receipt.durationMs ?? null,
762
+ protocol: receipt.protocol ?? null,
763
+ metadata_json: receipt.metadata !== void 0 ? JSON.stringify(redact(receipt.metadata)) : null,
764
+ authorization_json: receipt.authorization !== void 0 ? JSON.stringify(redact(receipt.authorization)) : null,
765
+ transaction_id: receipt.transactionId ?? null
766
+ };
767
+ }
768
+ function rowToReceipt(row) {
769
+ const payment = row.payment_json !== null ? JSON.parse(row.payment_json) : void 0;
770
+ const metadata = row.metadata_json !== null ? JSON.parse(row.metadata_json) : void 0;
771
+ const authorization = row.authorization_json !== null ? JSON.parse(row.authorization_json) : void 0;
772
+ return {
773
+ id: row.id,
774
+ requestId: row.request_id,
775
+ resourceId: row.resource_id,
776
+ deliveredAt: row.delivered_at,
777
+ backendStatus: row.backend_status,
778
+ ...payment !== void 0 ? { payment } : {},
779
+ ...row.duration_ms !== null ? { durationMs: row.duration_ms } : {},
780
+ ...row.protocol !== null ? { protocol: row.protocol } : {},
781
+ ...metadata !== void 0 ? { metadata } : {},
782
+ ...authorization !== void 0 ? { authorization } : {},
783
+ ...row.transaction_id !== null ? { transactionId: row.transaction_id } : {}
784
+ };
785
+ }
786
+ function eventToRow(event) {
787
+ return {
788
+ id: event.id,
789
+ type: event.type,
790
+ request_id: event.requestId,
791
+ resource_id: event.resourceId ?? null,
792
+ at: event.at,
793
+ adapter: event.adapter ?? null,
794
+ payment_provider: event.paymentProvider ?? null,
795
+ duration_ms: event.durationMs ?? null,
796
+ status: event.status ?? null,
797
+ data_json: event.data !== void 0 ? JSON.stringify(redact(event.data)) : null,
798
+ transaction_id: event.transactionId ?? null
799
+ };
800
+ }
801
+ function rowToEvent(row) {
802
+ const data = row.data_json !== null ? JSON.parse(row.data_json) : void 0;
803
+ return {
804
+ id: row.id,
805
+ type: row.type,
806
+ requestId: row.request_id,
807
+ at: row.at,
808
+ ...row.resource_id !== null ? { resourceId: row.resource_id } : {},
809
+ ...row.adapter !== null ? { adapter: row.adapter } : {},
810
+ ...row.payment_provider !== null ? { paymentProvider: row.payment_provider } : {},
811
+ ...row.duration_ms !== null ? { durationMs: row.duration_ms } : {},
812
+ ...row.status !== null ? { status: row.status } : {},
813
+ ...data !== void 0 ? { data } : {},
814
+ ...row.transaction_id !== null ? { transactionId: row.transaction_id } : {}
815
+ };
816
+ }
817
+ function rowToPaymentAttempt(row) {
818
+ return {
819
+ id: row.id,
820
+ requestId: row.request_id,
821
+ resourceId: row.resource_id,
822
+ provider: row.provider,
823
+ replayKey: row.replay_key,
824
+ status: row.status,
825
+ amount: row.amount,
826
+ currency: row.currency,
827
+ ...row.payer !== null ? { payer: row.payer } : {},
828
+ ...row.payee !== null ? { payee: row.payee } : {},
829
+ ...row.external_reference !== null ? { externalReference: row.external_reference } : {},
830
+ ...row.rejection_reason !== null ? { rejectionReason: row.rejection_reason } : {},
831
+ createdAt: row.created_at,
832
+ updatedAt: row.updated_at,
833
+ ...row.transaction_id !== null ? { transactionId: row.transaction_id } : {},
834
+ ...row.resolution_json !== null ? { resolution: JSON.parse(row.resolution_json) } : {}
835
+ };
836
+ }
837
+ function rowToTransaction(row, now) {
838
+ const status = row.payment_status;
839
+ const backend = row.backend_dispatched_at !== null && row.backend_deadline_at !== null ? {
840
+ dispatchedAt: row.backend_dispatched_at,
841
+ deadlineAt: row.backend_deadline_at,
842
+ ...row.backend_status !== null ? { status: row.backend_status } : {},
843
+ ...row.backend_error_code !== null ? { errorCode: row.backend_error_code } : {}
844
+ } : void 0;
845
+ const completedAt = row.completed_at ?? void 0;
846
+ const authorization = row.authorization_json !== null && row.reservation_id !== null ? {
847
+ ...JSON.parse(row.authorization_json),
848
+ reservationId: row.reservation_id
849
+ } : void 0;
850
+ return {
851
+ id: row.id,
852
+ requestId: row.request_id,
853
+ resourceId: row.resource_id,
854
+ protocol: row.protocol,
855
+ state: transactionState(
856
+ {
857
+ payment: { status },
858
+ ...backend !== void 0 ? { backend } : {},
859
+ ...completedAt !== void 0 ? { completedAt } : {}
860
+ },
861
+ now
862
+ ),
863
+ payment: {
864
+ provider: row.provider,
865
+ attemptId: row.attempt_id,
866
+ replayKey: row.replay_key,
867
+ status,
868
+ amount: row.payment_amount,
869
+ currency: row.payment_currency,
870
+ ...row.network !== null ? { network: row.network } : {},
871
+ ...row.asset !== null ? { asset: row.asset } : {},
872
+ ...row.payment_payee !== null ? { payee: row.payment_payee } : {},
873
+ ...row.payment_external_reference !== null ? { externalReference: row.payment_external_reference } : {},
874
+ ...row.locator_json !== null ? { locator: JSON.parse(row.locator_json) } : {},
875
+ ...row.settling_at !== null ? { settlingAt: row.settling_at } : {},
876
+ ...row.expires_at !== null ? { expiresAt: row.expires_at } : {}
877
+ },
878
+ ...authorization !== void 0 ? { authorization } : {},
879
+ ...backend !== void 0 ? { backend } : {},
880
+ ...row.receipt_id !== null ? { receiptId: row.receipt_id } : {},
881
+ ...row.input_digest !== null ? { inputDigest: row.input_digest } : {},
882
+ configDigest: row.config_digest,
883
+ ...row.persistence_failures_json !== null ? { persistenceFailures: JSON.parse(row.persistence_failures_json) } : {},
884
+ createdAt: row.created_at,
885
+ updatedAt: row.updated_at,
886
+ ...completedAt !== void 0 ? { completedAt } : {}
887
+ };
888
+ }
889
+
890
+ // src/storage/receipts/store.ts
891
+ var UNDELIVERED = "backend_status NOT BETWEEN 200 AND 299";
892
+ var UNCERTAIN = "status IN ('settlement-uncertain', 'failed')";
893
+ var TRANSACTION_SELECT = `
894
+ SELECT t.*,
895
+ COALESCE(a.status, h.status) AS payment_status,
896
+ COALESCE(a.amount, h.amount) AS payment_amount,
897
+ COALESCE(a.currency, h.currency) AS payment_currency,
898
+ COALESCE(a.payee, h.payee) AS payment_payee,
899
+ COALESCE(a.external_reference, h.external_reference) AS payment_external_reference
900
+ FROM transactions t
901
+ LEFT JOIN payment_attempts a ON a.id = t.attempt_id
902
+ LEFT JOIN payment_attempt_history h ON a.id IS NULL AND h.seq = (
903
+ SELECT MAX(seq) FROM payment_attempt_history
904
+ WHERE replay_key = t.replay_key AND id = t.attempt_id
905
+ )`;
906
+ var TIME_DEPENDENT = "t.backend_deadline_at IS NOT NULL AND t.completed_at IS NULL";
907
+ var RESOLVED_STATES = ["delivered", "payment-failed"];
908
+ var CURSOR_PATTERN = /^[1-9][0-9]{0,15}$/;
909
+ var defaultIds = {
910
+ next: (prefix) => prefix !== void 0 ? `${prefix}_${randomUUID()}` : randomUUID()
911
+ };
912
+ function isUniqueConstraintOn(err, column) {
913
+ return err instanceof Error && "code" in err && err.code === "SQLITE_CONSTRAINT_UNIQUE" && err.message.includes(column);
914
+ }
915
+ function createSqliteReceiptStore(options) {
916
+ const db = openSqliteDatabase({
917
+ path: options.path,
918
+ label: "Receipt database",
919
+ logger: options.logger ?? NOOP_LOGGER
920
+ });
921
+ migrate(db);
922
+ return storeOn(db, options);
923
+ }
924
+ function openSqliteReceiptStoreReadOnly(path) {
925
+ let db;
926
+ let schemaVersion;
927
+ try {
928
+ db = new Database(path, { readonly: true, fileMustExist: true });
929
+ schemaVersion = db.pragma("user_version", { simple: true });
930
+ } catch (cause) {
931
+ db?.close();
932
+ throw new CommerceError(
933
+ "STORAGE_ERROR",
934
+ `Receipt database "${path}" cannot be opened: ${cause instanceof Error ? cause.message : String(cause)}`,
935
+ { details: { path }, cause }
936
+ );
937
+ }
938
+ if (schemaVersion !== SCHEMA_VERSION) {
939
+ db.close();
940
+ throw new CommerceError(
941
+ "STORAGE_ERROR",
942
+ `Receipt database "${path}" is at schema v${schemaVersion}, not v${SCHEMA_VERSION}`,
943
+ { details: { path, schemaVersion, expected: SCHEMA_VERSION } }
944
+ );
945
+ }
946
+ return storeOn(db, { path });
947
+ }
948
+ function storeOn(db, options) {
949
+ const logger = options.logger ?? NOOP_LOGGER;
950
+ const clock = options.clock ?? systemClock;
951
+ const ids = options.ids ?? defaultIds;
952
+ const path = options.path;
953
+ const isFileBacked = path !== ":memory:";
954
+ const insertReceiptStmt = db.prepare(
955
+ `INSERT INTO receipts (id, request_id, resource_id, payment_json, delivered_at, backend_status, duration_ms, protocol, metadata_json, authorization_json, transaction_id)
956
+ VALUES (@id, @request_id, @resource_id, @payment_json, @delivered_at, @backend_status, @duration_ms, @protocol, @metadata_json, @authorization_json, @transaction_id)`
957
+ );
958
+ const getReceiptStmt = db.prepare("SELECT * FROM receipts WHERE id = ?");
959
+ const listReceiptsStmt = db.prepare(
960
+ "SELECT * FROM receipts ORDER BY delivered_at DESC, seq DESC LIMIT ?"
961
+ );
962
+ const listReceiptsByRequestStmt = db.prepare(
963
+ "SELECT * FROM receipts WHERE request_id = ? ORDER BY delivered_at DESC, seq DESC LIMIT ?"
964
+ );
965
+ const listUndeliveredReceiptsStmt = db.prepare(
966
+ `SELECT * FROM receipts WHERE ${UNDELIVERED} ORDER BY delivered_at DESC, seq DESC LIMIT ?`
967
+ );
968
+ const listUndeliveredReceiptsByRequestStmt = db.prepare(
969
+ `SELECT * FROM receipts WHERE request_id = ? AND ${UNDELIVERED} ORDER BY delivered_at DESC, seq DESC LIMIT ?`
970
+ );
971
+ const countReceiptsStmt = db.prepare(
972
+ "SELECT COUNT(*) AS count FROM receipts"
973
+ );
974
+ const countUndeliveredReceiptsStmt = db.prepare(
975
+ `SELECT COUNT(*) AS count FROM receipts WHERE ${UNDELIVERED}`
976
+ );
977
+ const insertEventStmt = db.prepare(
978
+ `INSERT INTO events (id, type, request_id, resource_id, at, adapter, payment_provider, duration_ms, status, data_json, transaction_id)
979
+ VALUES (@id, @type, @request_id, @resource_id, @at, @adapter, @payment_provider, @duration_ms, @status, @data_json, @transaction_id)`
980
+ );
981
+ const listEventsStmt = db.prepare(
982
+ "SELECT * FROM events ORDER BY at DESC, seq DESC LIMIT ?"
983
+ );
984
+ const listEventsByRequestStmt = db.prepare(
985
+ "SELECT * FROM events WHERE request_id = ? ORDER BY at DESC, seq DESC LIMIT ?"
986
+ );
987
+ const insertPaymentAttemptStmt = db.prepare(
988
+ `INSERT INTO payment_attempts (id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at, transaction_id)
989
+ VALUES (@id, @request_id, @resource_id, @provider, @replay_key, @status, @amount, @currency, @payer, @payee, @external_reference, @rejection_reason, @created_at, @updated_at, @transaction_id)
990
+ RETURNING *`
991
+ );
992
+ const archiveRejectedAttemptStmt = db.prepare(
993
+ `INSERT INTO payment_attempt_history (id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at, superseded_at, transaction_id, resolution_json)
994
+ SELECT id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at, @created_at, transaction_id, resolution_json
995
+ FROM payment_attempts
996
+ WHERE replay_key = @replay_key AND provider = @provider AND status = 'rejected'`
997
+ );
998
+ const reclaimPaymentAttemptStmt = db.prepare(
999
+ `UPDATE payment_attempts SET id = @id, request_id = @request_id, resource_id = @resource_id,
1000
+ status = 'reserved', amount = @amount, currency = @currency,
1001
+ payer = @payer, payee = @payee, external_reference = NULL, rejection_reason = NULL,
1002
+ created_at = @created_at, updated_at = @updated_at,
1003
+ transaction_id = @transaction_id, resolution_json = NULL
1004
+ WHERE replay_key = @replay_key AND provider = @provider AND status = 'rejected'
1005
+ RETURNING *`
1006
+ );
1007
+ const updatePaymentAttemptStmt = db.prepare(
1008
+ `UPDATE payment_attempts SET status = @status,
1009
+ external_reference = COALESCE(@external_reference, external_reference),
1010
+ rejection_reason = COALESCE(@rejection_reason, rejection_reason),
1011
+ updated_at = @updated_at
1012
+ WHERE replay_key = @replay_key AND resolution_json IS NULL`
1013
+ );
1014
+ const listPaymentAttemptsStmt = db.prepare(
1015
+ "SELECT * FROM payment_attempts ORDER BY created_at DESC, seq DESC LIMIT ?"
1016
+ );
1017
+ const listPaymentAttemptsByRequestStmt = db.prepare(
1018
+ "SELECT * FROM payment_attempts WHERE request_id = ? ORDER BY created_at DESC, seq DESC LIMIT ?"
1019
+ );
1020
+ const listUncertainPaymentAttemptsStmt = db.prepare(
1021
+ `SELECT * FROM payment_attempts WHERE ${UNCERTAIN} ORDER BY created_at DESC, seq DESC LIMIT ?`
1022
+ );
1023
+ const listUncertainPaymentAttemptsByRequestStmt = db.prepare(
1024
+ `SELECT * FROM payment_attempts WHERE request_id = ? AND ${UNCERTAIN} ORDER BY created_at DESC, seq DESC LIMIT ?`
1025
+ );
1026
+ const countUncertainPaymentAttemptsStmt = db.prepare(
1027
+ `SELECT COUNT(*) AS count FROM payment_attempts WHERE ${UNCERTAIN}`
1028
+ );
1029
+ const paymentAttemptStatusStmt = db.prepare("SELECT id, status, resolution_json FROM payment_attempts WHERE replay_key = ?");
1030
+ const insertTransactionStmt = db.prepare(
1031
+ `INSERT INTO transactions (id, request_id, resource_id, protocol, state, provider, attempt_id, replay_key, network, asset, authorization_json, reservation_id, locator_json, expires_at, input_digest, config_digest, created_at, updated_at)
1032
+ VALUES (@id, @request_id, @resource_id, @protocol, @state, @provider, @attempt_id, @replay_key, @network, @asset, @authorization_json, @reservation_id, @locator_json, @expires_at, @input_digest, @config_digest, @created_at, @created_at)`
1033
+ );
1034
+ const getTransactionStmt = db.prepare(
1035
+ `${TRANSACTION_SELECT} WHERE t.id = ?`
1036
+ );
1037
+ const transactionsOfAttemptStmt = db.prepare(
1038
+ `SELECT t.id FROM payment_attempts a
1039
+ JOIN transactions t ON t.replay_key = a.replay_key AND t.attempt_id = a.id
1040
+ WHERE a.replay_key = ?`
1041
+ );
1042
+ const transactionsOfAttemptIdStmt = db.prepare(
1043
+ `SELECT t.id FROM payment_attempts a
1044
+ JOIN transactions t ON t.replay_key = a.replay_key AND t.attempt_id = a.id
1045
+ WHERE a.id = ?`
1046
+ );
1047
+ const setTransactionStateStmt = db.prepare("UPDATE transactions SET state = ? WHERE id = ?");
1048
+ const stepStmts = {
1049
+ settling: db.prepare(
1050
+ "UPDATE transactions SET settling_at = @at, updated_at = @at WHERE id = @id"
1051
+ ),
1052
+ // A transaction without an authorization has no hold to record
1053
+ hold: db.prepare(
1054
+ `UPDATE transactions SET authorization_json = json_set(authorization_json, '$.hold', @hold), updated_at = @at
1055
+ WHERE id = @id AND authorization_json IS NOT NULL`
1056
+ ),
1057
+ "backend-dispatched": db.prepare(
1058
+ `UPDATE transactions SET backend_dispatched_at = @at, backend_deadline_at = @deadline_at, updated_at = @at
1059
+ WHERE id = @id`
1060
+ ),
1061
+ // Preserve a backend result even when the dispatch step was not saved:
1062
+ // use the result time for missing dispatch and deadline timestamps
1063
+ "backend-result": db.prepare(
1064
+ `UPDATE transactions SET backend_status = @status, backend_error_code = @error_code,
1065
+ backend_dispatched_at = COALESCE(backend_dispatched_at, @at),
1066
+ backend_deadline_at = COALESCE(backend_deadline_at, @at), updated_at = @at
1067
+ WHERE id = @id`
1068
+ ),
1069
+ receipt: db.prepare(
1070
+ "UPDATE transactions SET receipt_id = @receipt_id, updated_at = @at WHERE id = @id"
1071
+ ),
1072
+ completed: db.prepare(
1073
+ `UPDATE transactions SET completed_at = @at, persistence_failures_json = @persistence_failures_json, updated_at = @at
1074
+ WHERE id = @id`
1075
+ )
1076
+ };
1077
+ const getPaymentAttemptStmt = db.prepare(
1078
+ "SELECT * FROM payment_attempts WHERE id = ?"
1079
+ );
1080
+ const getArchivedPaymentAttemptStmt = db.prepare(
1081
+ "SELECT * FROM payment_attempt_history WHERE id = ? ORDER BY seq DESC LIMIT 1"
1082
+ );
1083
+ const paymentAttemptByReplayKeyStmt = db.prepare(
1084
+ "SELECT * FROM payment_attempts WHERE replay_key = ?"
1085
+ );
1086
+ const resolvePaymentAttemptStmt = db.prepare(
1087
+ `UPDATE payment_attempts SET status = @status,
1088
+ rejection_reason = COALESCE(@rejection_reason, rejection_reason),
1089
+ external_reference = COALESCE(@external_reference, external_reference),
1090
+ resolution_json = @resolution_json, updated_at = @updated_at
1091
+ WHERE id = @id AND status = @expected_status AND resolution_json IS NULL`
1092
+ );
1093
+ function refreshTransactionState(id, now) {
1094
+ const row = getTransactionStmt.get(id);
1095
+ if (row !== void 0) setTransactionStateStmt.run(rowToTransaction(row, now).state, id);
1096
+ }
1097
+ const reserve = db.transaction(
1098
+ (reservation, params) => {
1099
+ let row;
1100
+ if (reservation.reclaimRejected === true) {
1101
+ archiveRejectedAttemptStmt.run(params);
1102
+ row = reclaimPaymentAttemptStmt.get(params);
1103
+ }
1104
+ row ??= insertPaymentAttemptStmt.get({
1105
+ ...params,
1106
+ status: "reserved",
1107
+ external_reference: null,
1108
+ rejection_reason: null
1109
+ });
1110
+ const txn = reservation.transaction;
1111
+ if (txn !== void 0) {
1112
+ const { reservationId, ...authorization } = txn.authorization ?? {};
1113
+ insertTransactionStmt.run({
1114
+ id: txn.id,
1115
+ request_id: reservation.requestId,
1116
+ resource_id: reservation.resourceId,
1117
+ protocol: txn.protocol,
1118
+ state: transactionState({ payment: { status: "reserved" } }, row.created_at),
1119
+ provider: reservation.provider,
1120
+ attempt_id: row.id,
1121
+ replay_key: reservation.replayKey,
1122
+ network: txn.network ?? null,
1123
+ asset: txn.asset ?? null,
1124
+ authorization_json: reservationId !== void 0 ? JSON.stringify(redact({ ...authorization, hold: "reserved" })) : null,
1125
+ reservation_id: reservationId ?? null,
1126
+ locator_json: txn.locator !== void 0 ? JSON.stringify(redact(txn.locator)) : null,
1127
+ expires_at: txn.expiresAt ?? null,
1128
+ input_digest: txn.inputDigest ?? null,
1129
+ config_digest: txn.configDigest,
1130
+ created_at: row.created_at
1131
+ });
1132
+ }
1133
+ return row;
1134
+ }
1135
+ );
1136
+ const updateAttempt = db.transaction((update, now) => {
1137
+ const { changes } = updatePaymentAttemptStmt.run({
1138
+ replay_key: update.replayKey,
1139
+ status: update.status,
1140
+ external_reference: update.externalReference ?? null,
1141
+ rejection_reason: update.rejectionReason ?? null,
1142
+ updated_at: now
1143
+ });
1144
+ for (const { id } of transactionsOfAttemptStmt.all(update.replayKey)) {
1145
+ refreshTransactionState(id, now);
1146
+ }
1147
+ return changes;
1148
+ });
1149
+ const recordStep = db.transaction((step) => {
1150
+ const base = { id: step.transactionId, at: step.at };
1151
+ let changes;
1152
+ switch (step.kind) {
1153
+ case "settling":
1154
+ changes = stepStmts.settling.run(base).changes;
1155
+ break;
1156
+ case "hold":
1157
+ changes = stepStmts.hold.run({ ...base, hold: step.hold }).changes;
1158
+ break;
1159
+ case "backend-dispatched":
1160
+ changes = stepStmts["backend-dispatched"].run({
1161
+ ...base,
1162
+ deadline_at: step.deadlineAt
1163
+ }).changes;
1164
+ break;
1165
+ case "backend-result":
1166
+ changes = stepStmts["backend-result"].run({
1167
+ ...base,
1168
+ status: step.status,
1169
+ error_code: step.errorCode ?? null
1170
+ }).changes;
1171
+ break;
1172
+ case "receipt":
1173
+ changes = stepStmts.receipt.run({ ...base, receipt_id: step.receiptId }).changes;
1174
+ break;
1175
+ case "completed":
1176
+ changes = stepStmts.completed.run({
1177
+ ...base,
1178
+ persistence_failures_json: step.persistenceFailures !== void 0 && step.persistenceFailures.length > 0 ? JSON.stringify(step.persistenceFailures) : null
1179
+ }).changes;
1180
+ break;
1181
+ }
1182
+ if (changes > 0) refreshTransactionState(step.transactionId, step.at);
1183
+ return changes;
1184
+ });
1185
+ const resolveAttempt = db.transaction(
1186
+ (request, now) => {
1187
+ const { changes } = resolvePaymentAttemptStmt.run({
1188
+ id: request.attemptId,
1189
+ expected_status: request.expectedStatus,
1190
+ status: request.status,
1191
+ rejection_reason: request.rejectionReason ?? null,
1192
+ // An operator's reference is unverified; it stays in resolution_json only
1193
+ external_reference: request.resolution.method === "reconcile" ? request.resolution.externalReference ?? null : null,
1194
+ resolution_json: JSON.stringify(redact(request.resolution)),
1195
+ updated_at: now
1196
+ });
1197
+ if (changes === 0) return false;
1198
+ for (const { id } of transactionsOfAttemptIdStmt.all(request.attemptId)) {
1199
+ refreshTransactionState(id, now);
1200
+ }
1201
+ return true;
1202
+ }
1203
+ );
1204
+ const unresolvedTransactionsStmt = db.prepare(
1205
+ `${TRANSACTION_SELECT} WHERE t.state NOT IN (?, ?)`
1206
+ );
1207
+ const countOrphanHoldsStmt = db.prepare(
1208
+ `SELECT COUNT(*) AS count FROM authorization_holds h WHERE ${ORPHAN_HOLD_WHERE}`
1209
+ );
1210
+ const countUnresolvedKeysStmt = db.prepare(
1211
+ "SELECT COUNT(*) AS count FROM idempotency_keys WHERE state = 'unresolved'"
1212
+ );
1213
+ const countLiveTasksStmt = db.prepare(
1214
+ "SELECT COUNT(*) AS count FROM pending_tasks WHERE expires_at > ?"
1215
+ );
1216
+ const legacyImportsStmt = db.prepare(
1217
+ "SELECT source, path, rows, imported_at FROM legacy_imports WHERE path IS NOT NULL ORDER BY source"
1218
+ );
1219
+ let closed = false;
1220
+ let releaseLegacyLocks;
1221
+ const descriptor = {
1222
+ name: "sqlite-receipt-store",
1223
+ kind: "storage",
1224
+ implementationVersion: PACKAGE_VERSION,
1225
+ supportedSpec: `sqlite-schema-v${SCHEMA_VERSION}`,
1226
+ capabilities: [
1227
+ "receipts",
1228
+ "events",
1229
+ "payment-attempts",
1230
+ "transactions",
1231
+ "idempotency-keys",
1232
+ "authorization-holds",
1233
+ "pending-tasks"
1234
+ ],
1235
+ status: "stable"
1236
+ };
1237
+ const store = {
1238
+ async init() {
1239
+ const version = db.pragma("user_version", { simple: true });
1240
+ if (version !== SCHEMA_VERSION) {
1241
+ throw new CommerceError(
1242
+ "STORAGE_ERROR",
1243
+ `Receipt store schema version mismatch (found ${version}, expected ${SCHEMA_VERSION})`
1244
+ );
1245
+ }
1246
+ if (!db.readonly) sweepExpiredPendingTasks(db, clock.nowIso());
1247
+ if (options.legacyStores !== void 0 && releaseLegacyLocks === void 0) {
1248
+ releaseLegacyLocks = importLegacyStores(
1249
+ db,
1250
+ options.path,
1251
+ options.legacyStores,
1252
+ clock,
1253
+ logger
1254
+ );
1255
+ }
1256
+ },
1257
+ async appendEvent(event) {
1258
+ try {
1259
+ insertEventStmt.run(eventToRow(event));
1260
+ } catch (err) {
1261
+ logger.warn(
1262
+ {
1263
+ err: err instanceof Error ? err.message : String(err),
1264
+ eventId: event.id,
1265
+ requestId: event.requestId
1266
+ },
1267
+ "receipt-store: failed to persist commerce event"
1268
+ );
1269
+ }
1270
+ },
1271
+ async reservePaymentAttempt(reservation) {
1272
+ const now = clock.nowIso();
1273
+ const params = {
1274
+ id: ids.next("attempt"),
1275
+ request_id: reservation.requestId,
1276
+ resource_id: reservation.resourceId,
1277
+ provider: reservation.provider,
1278
+ replay_key: reservation.replayKey,
1279
+ amount: reservation.amount,
1280
+ currency: reservation.currency,
1281
+ payer: reservation.payer ?? null,
1282
+ payee: reservation.payee ?? null,
1283
+ created_at: now,
1284
+ updated_at: now,
1285
+ transaction_id: reservation.transaction?.id ?? null
1286
+ };
1287
+ let row;
1288
+ try {
1289
+ row = reserve.immediate(reservation, params);
1290
+ } catch (err) {
1291
+ if (isUniqueConstraintOn(err, "payment_attempts.replay_key")) {
1292
+ const existing = paymentAttemptStatusStmt.get(reservation.replayKey);
1293
+ throw new CommerceError(
1294
+ "PAYMENT_REPLAYED",
1295
+ `Payment authorization has already been used (replayKey=${reservation.replayKey})`,
1296
+ {
1297
+ requestId: reservation.requestId,
1298
+ resourceId: reservation.resourceId,
1299
+ ...existing !== void 0 ? { details: { attemptStatus: existing.status } } : {}
1300
+ }
1301
+ );
1302
+ }
1303
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to reserve payment attempt");
1304
+ }
1305
+ return rowToPaymentAttempt(row);
1306
+ },
1307
+ async updatePaymentAttempt(update) {
1308
+ try {
1309
+ if (updateAttempt(update, clock.nowIso()) === 0) {
1310
+ const existing = paymentAttemptStatusStmt.get(update.replayKey);
1311
+ if (existing?.resolution_json != null) {
1312
+ logger.warn(
1313
+ {
1314
+ attemptId: existing.id,
1315
+ resolvedStatus: existing.status,
1316
+ status: update.status,
1317
+ ...update.externalReference !== void 0 ? { externalReference: update.externalReference } : {}
1318
+ },
1319
+ "receipt-store: payment attempt already resolved; update not applied"
1320
+ );
1321
+ throw new CommerceError(
1322
+ "STORAGE_ERROR",
1323
+ `Payment attempt ${existing.id} is already resolved; the update was not applied`
1324
+ );
1325
+ }
1326
+ throw new CommerceError(
1327
+ "STORAGE_ERROR",
1328
+ `No payment attempt found for replayKey=${update.replayKey}`
1329
+ );
1330
+ }
1331
+ } catch (err) {
1332
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to update payment attempt");
1333
+ }
1334
+ },
1335
+ async saveReceipt(receipt) {
1336
+ try {
1337
+ insertReceiptStmt.run(receiptToRow(receipt));
1338
+ } catch (err) {
1339
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to save receipt");
1340
+ }
1341
+ },
1342
+ async getReceipt(id) {
1343
+ const row = getReceiptStmt.get(id);
1344
+ return row !== void 0 ? rowToReceipt(row) : void 0;
1345
+ },
1346
+ async listReceipts(listOptions = {}) {
1347
+ const limit = clampListLimit(listOptions.limit);
1348
+ const undelivered = listOptions.undelivered === true;
1349
+ const rows = listOptions.requestId !== void 0 ? (undelivered ? listUndeliveredReceiptsByRequestStmt : listReceiptsByRequestStmt).all(
1350
+ listOptions.requestId,
1351
+ limit
1352
+ ) : (undelivered ? listUndeliveredReceiptsStmt : listReceiptsStmt).all(limit);
1353
+ return rows.map(rowToReceipt);
1354
+ },
1355
+ // Exact total, not bounded by the listReceipts clamp (see ReceiptStore.countReceipts)
1356
+ async countReceipts() {
1357
+ return countReceiptsStmt.get()?.count ?? 0;
1358
+ },
1359
+ // Exact count of non-2xx receipts (see ReceiptStore.countUndeliveredReceipts)
1360
+ async countUndeliveredReceipts() {
1361
+ return countUndeliveredReceiptsStmt.get()?.count ?? 0;
1362
+ },
1363
+ async countUncertainPaymentAttempts() {
1364
+ return countUncertainPaymentAttemptsStmt.get()?.count ?? 0;
1365
+ },
1366
+ async listEvents(listOptions = {}) {
1367
+ const limit = clampListLimit(listOptions.limit);
1368
+ const rows = listOptions.requestId !== void 0 ? listEventsByRequestStmt.all(listOptions.requestId, limit) : listEventsStmt.all(limit);
1369
+ return rows.map(rowToEvent);
1370
+ },
1371
+ async listPaymentAttempts(listOptions = {}) {
1372
+ const limit = clampListLimit(listOptions.limit);
1373
+ const uncertain = listOptions.uncertain === true;
1374
+ const rows = listOptions.requestId !== void 0 ? (uncertain ? listUncertainPaymentAttemptsByRequestStmt : listPaymentAttemptsByRequestStmt).all(listOptions.requestId, limit) : (uncertain ? listUncertainPaymentAttemptsStmt : listPaymentAttemptsStmt).all(limit);
1375
+ return rows.map(rowToPaymentAttempt);
1376
+ },
1377
+ async recordTransactionStep(step) {
1378
+ try {
1379
+ if (recordStep(step) === 0) {
1380
+ throw new CommerceError(
1381
+ "STORAGE_ERROR",
1382
+ step.kind === "hold" ? `No transaction with an authorization hold found for transactionId=${step.transactionId}` : `No transaction found for transactionId=${step.transactionId}`
1383
+ );
1384
+ }
1385
+ } catch (err) {
1386
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to record transaction step");
1387
+ }
1388
+ },
1389
+ async getTransaction(id) {
1390
+ const row = getTransactionStmt.get(id);
1391
+ return row !== void 0 ? rowToTransaction(row, clock.nowIso()) : void 0;
1392
+ },
1393
+ async listTransactions(listOptions = {}) {
1394
+ const { cursor, state, unresolved, pendingHold, requestId } = listOptions;
1395
+ if (cursor !== void 0 && !CURSOR_PATTERN.test(cursor)) {
1396
+ throw new CommerceError("INPUT_INVALID", "Malformed transaction list cursor");
1397
+ }
1398
+ const limit = clampListLimit(listOptions.limit);
1399
+ const where = [];
1400
+ const params = [];
1401
+ if (cursor !== void 0) {
1402
+ where.push("t.seq < ?");
1403
+ params.push(Number(cursor));
1404
+ }
1405
+ if (requestId !== void 0) {
1406
+ where.push("t.request_id = ?");
1407
+ params.push(requestId);
1408
+ }
1409
+ if (state !== void 0) {
1410
+ where.push(`(t.state = ? OR (${TIME_DEPENDENT}))`);
1411
+ params.push(state);
1412
+ }
1413
+ if (pendingHold === true) {
1414
+ where.push("json_extract(t.authorization_json, '$.hold') IN ('reserved', 'uncertain')");
1415
+ }
1416
+ if (unresolved === true) {
1417
+ where.push(`t.state NOT IN (${RESOLVED_STATES.map(() => "?").join(", ")})`);
1418
+ params.push(...RESOLVED_STATES);
1419
+ }
1420
+ const rows = db.prepare(
1421
+ `${TRANSACTION_SELECT}${where.length > 0 ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY t.seq DESC LIMIT ?`
1422
+ ).all(...params, limit);
1423
+ const now = clock.nowIso();
1424
+ const resolved = RESOLVED_STATES;
1425
+ const transactions = rows.map((row) => rowToTransaction(row, now)).filter(
1426
+ (t) => (state === void 0 || t.state === state) && (unresolved !== true || !resolved.includes(t.state))
1427
+ );
1428
+ const last = rows.at(-1);
1429
+ return {
1430
+ transactions,
1431
+ ...rows.length === limit && last !== void 0 ? { nextCursor: String(last.seq) } : {}
1432
+ };
1433
+ },
1434
+ async getPaymentAttempt(id) {
1435
+ const row = getPaymentAttemptStmt.get(id) ?? getArchivedPaymentAttemptStmt.get(id);
1436
+ return row !== void 0 ? rowToPaymentAttempt(row) : void 0;
1437
+ },
1438
+ async findPaymentAttemptByReplayKey(replayKey) {
1439
+ const row = paymentAttemptByReplayKeyStmt.get(replayKey);
1440
+ return row !== void 0 ? rowToPaymentAttempt(row) : void 0;
1441
+ },
1442
+ async resolvePaymentAttempt(request) {
1443
+ try {
1444
+ return resolveAttempt(request, clock.nowIso());
1445
+ } catch (err) {
1446
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to resolve payment attempt");
1447
+ }
1448
+ },
1449
+ ...createIdempotencyMethods(db, clock),
1450
+ ...createHoldMethods(db, clock),
1451
+ ...createPendingTaskMethods(db, clock),
1452
+ // Reads all unresolved transactions at once. Page this query if large
1453
+ // journals make operator diagnostics too costly.
1454
+ async summary({ orphanHoldMinAgeMs }) {
1455
+ const now = clock.nowIso();
1456
+ const unresolvedTransactions = {};
1457
+ for (const row of unresolvedTransactionsStmt.all(...RESOLVED_STATES)) {
1458
+ const { state } = rowToTransaction(row, now);
1459
+ unresolvedTransactions[state] = (unresolvedTransactions[state] ?? 0) + 1;
1460
+ }
1461
+ const orphansBefore = new Date(Date.parse(now) - orphanHoldMinAgeMs).toISOString();
1462
+ return {
1463
+ unresolvedTransactions,
1464
+ orphanHolds: countOrphanHoldsStmt.get(orphansBefore)?.count ?? 0,
1465
+ unresolvedIdempotencyKeys: countUnresolvedKeysStmt.get()?.count ?? 0,
1466
+ unexpiredPendingTasks: countLiveTasksStmt.get(now)?.count ?? 0,
1467
+ legacyImports: legacyImportsStmt.all().map((row) => ({
1468
+ source: row.source,
1469
+ path: row.path,
1470
+ rows: row.rows,
1471
+ importedAt: row.imported_at
1472
+ })),
1473
+ missingLegacyImports: missingLegacyImports(db)
1474
+ };
1475
+ },
1476
+ descriptor,
1477
+ async health() {
1478
+ const startedAt = clock.monotonicMs();
1479
+ if (closed) {
1480
+ return { status: "fail", detail: "store-unavailable", checkedAt: clock.nowIso() };
1481
+ }
1482
+ if (isFileBacked) {
1483
+ try {
1484
+ accessSync(path, constants.W_OK);
1485
+ } catch (err) {
1486
+ logger.warn(
1487
+ { err: err instanceof Error ? err.message : String(err) },
1488
+ "receipt-store: health check failed (store not writable)"
1489
+ );
1490
+ return {
1491
+ status: "fail",
1492
+ detail: "store-unwritable",
1493
+ checkedAt: clock.nowIso(),
1494
+ durationMs: clock.monotonicMs() - startedAt
1495
+ };
1496
+ }
1497
+ }
1498
+ try {
1499
+ const version = db.pragma("user_version", { simple: true });
1500
+ if (version !== SCHEMA_VERSION) {
1501
+ logger.warn(
1502
+ { found: version, expected: SCHEMA_VERSION },
1503
+ "receipt-store: health check failed (schema version mismatch)"
1504
+ );
1505
+ return {
1506
+ status: "fail",
1507
+ detail: "store-schema-mismatch",
1508
+ checkedAt: clock.nowIso(),
1509
+ durationMs: clock.monotonicMs() - startedAt
1510
+ };
1511
+ }
1512
+ return {
1513
+ status: "pass",
1514
+ detail: `sqlite schema v${SCHEMA_VERSION} writable`,
1515
+ checkedAt: clock.nowIso(),
1516
+ durationMs: clock.monotonicMs() - startedAt
1517
+ };
1518
+ } catch (err) {
1519
+ logger.warn(
1520
+ { err: err instanceof Error ? err.message : String(err) },
1521
+ "receipt-store: health check failed (store unavailable)"
1522
+ );
1523
+ return {
1524
+ status: "fail",
1525
+ detail: "store-unavailable",
1526
+ checkedAt: clock.nowIso(),
1527
+ durationMs: clock.monotonicMs() - startedAt
1528
+ };
1529
+ }
1530
+ },
1531
+ async close() {
1532
+ if (!closed) {
1533
+ closed = true;
1534
+ releaseLegacyLocks?.();
1535
+ db.close();
1536
+ }
1537
+ }
1538
+ };
1539
+ return store;
1540
+ }
1541
+
1542
+ export { SCHEMA_VERSION, createSqliteReceiptStore, hasTable, openSqliteReceiptStoreReadOnly, readMissingLegacyImports };
1543
+ //# sourceMappingURL=chunk-NSYSMDQN.js.map
1544
+ //# sourceMappingURL=chunk-NSYSMDQN.js.map