@pacspace-io/sdk 0.9.0 → 0.15.2

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 (152) hide show
  1. package/README.md +53 -132
  2. package/dist/blinding-file.d.ts +13 -0
  3. package/dist/blinding-file.d.ts.map +1 -0
  4. package/dist/blinding-guard.d.ts +7 -0
  5. package/dist/blinding-guard.d.ts.map +1 -0
  6. package/dist/blinding.d.ts +32 -0
  7. package/dist/blinding.d.ts.map +1 -0
  8. package/dist/client.d.ts +28 -4
  9. package/dist/client.d.ts.map +1 -1
  10. package/dist/fingerprint.d.ts +26 -5
  11. package/dist/fingerprint.d.ts.map +1 -1
  12. package/dist/index.d.ts +35 -35
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +7366 -186
  15. package/dist/index.js.map +7 -1
  16. package/dist/inputs.txt +132 -0
  17. package/dist/records-crypto-libraries.json +42 -0
  18. package/dist/records-crypto-types/proof/hiding-commitment-v1.d.ts +19 -0
  19. package/dist/records-crypto-types/proof/jcs.d.ts +4 -0
  20. package/dist/records-crypto-types/proof/layout-document-v1.d.ts +72 -0
  21. package/dist/records-crypto-types/proof/ledger-head-v1.d.ts +22 -0
  22. package/dist/records-crypto-types/proof/merkle-v2.d.ts +5 -0
  23. package/dist/records-crypto-types/proof/payload-ref-v1.d.ts +17 -0
  24. package/dist/records-crypto-types/proof/seal-input.d.ts +2 -0
  25. package/dist/records-crypto-types/proof/semantic-receipt-v2.d.ts +89 -0
  26. package/dist/records-crypto-types/proof/semantic-receipt-v3.d.ts +20 -0
  27. package/dist/records-crypto-types/proof/slot-encoding-v1.d.ts +169 -0
  28. package/dist/records-crypto-types/records/flag-threads-v1.d.ts +53 -0
  29. package/dist/records-crypto-types/records/labels.d.ts +37 -0
  30. package/dist/records-crypto-types/records/reader-crypto-v1.d.ts +198 -0
  31. package/dist/records-crypto-types/records/reader-link-v1.d.ts +164 -0
  32. package/dist/records-crypto-types/records/shared-record-ack-v2.d.ts +72 -0
  33. package/dist/records-crypto-types/records/signed-acknowledgment-v1.d.ts +38 -0
  34. package/dist/records-crypto-types/records/signed-acknowledgment-v2.d.ts +12 -0
  35. package/dist/records-crypto-types/records/trail-index-v1.d.ts +89 -0
  36. package/dist/records-crypto-types/records/trail-rule.d.ts +54 -0
  37. package/dist/records-crypto-types/records-crypto/asymmetric/ack-flag-notes-v1.d.ts +57 -0
  38. package/dist/records-crypto-types/records-crypto/asymmetric/flag-notes-v1.d.ts +55 -0
  39. package/dist/records-crypto-types/records-crypto/asymmetric/index.d.ts +4 -0
  40. package/dist/records-crypto-types/records-crypto/asymmetric/reader-wraps-v1.d.ts +83 -0
  41. package/dist/records-crypto-types/records-crypto/asymmetric/records-asymmetric-v1.d.ts +201 -0
  42. package/dist/records-crypto-types/records-crypto/base64url.d.ts +3 -0
  43. package/dist/records-crypto-types/records-crypto/blinding-file.d.ts +16 -0
  44. package/dist/records-crypto-types/records-crypto/blinding-value.d.ts +10 -0
  45. package/dist/records-crypto-types/records-crypto/bundle-entry.d.ts +2 -0
  46. package/dist/records-crypto-types/records-crypto/disclosure-envelope-v1.d.ts +42 -0
  47. package/dist/records-crypto-types/records-crypto/held-file.d.ts +17 -0
  48. package/dist/records-crypto-types/records-crypto/hmac-node.d.ts +8 -0
  49. package/dist/records-crypto-types/records-crypto/hmac-web.d.ts +8 -0
  50. package/dist/records-crypto-types/records-crypto/index.d.ts +13 -0
  51. package/dist/records-crypto-types/records-crypto/platform-crypto.d.ts +9 -0
  52. package/dist/records-crypto-types/records-crypto/record-disclosure-v1.d.ts +171 -0
  53. package/dist/records-crypto-types/records-crypto/record-hash-v2.d.ts +49 -0
  54. package/dist/records-crypto-types/records-crypto/record-hash-v3.d.ts +36 -0
  55. package/dist/records-crypto-types/records-crypto/records-encryption-v1.d.ts +185 -0
  56. package/dist/records-crypto-types/records-crypto/wrap-shapes-v1.d.ts +23 -0
  57. package/dist/records-crypto.d.ts +1 -0
  58. package/dist/records-crypto.js +16105 -0
  59. package/dist/records-crypto.js.map +7 -0
  60. package/dist/records-encryption/base64url.d.ts +5 -0
  61. package/dist/records-encryption/base64url.d.ts.map +1 -0
  62. package/dist/records-encryption/encrypted-records.d.ts +338 -0
  63. package/dist/records-encryption/encrypted-records.d.ts.map +1 -0
  64. package/dist/records-encryption/index.d.ts +14 -0
  65. package/dist/records-encryption/index.d.ts.map +1 -0
  66. package/dist/records-encryption/keys.d.ts +40 -0
  67. package/dist/records-encryption/keys.d.ts.map +1 -0
  68. package/dist/records-encryption/loader.d.ts +15 -0
  69. package/dist/records-encryption/loader.d.ts.map +1 -0
  70. package/dist/records-encryption/pin-store-file.d.ts +8 -0
  71. package/dist/records-encryption/pin-store-file.d.ts.map +1 -0
  72. package/dist/records-encryption/pin-store.d.ts +17 -0
  73. package/dist/records-encryption/pin-store.d.ts.map +1 -0
  74. package/dist/records-encryption/transport.d.ts +23 -0
  75. package/dist/records-encryption/transport.d.ts.map +1 -0
  76. package/dist/records-encryption/words.d.ts +40 -0
  77. package/dist/records-encryption/words.d.ts.map +1 -0
  78. package/dist/records-encryption/workspace-secret.d.ts +9 -0
  79. package/dist/records-encryption/workspace-secret.d.ts.map +1 -0
  80. package/dist/resources/records.d.ts +112 -2
  81. package/dist/resources/records.d.ts.map +1 -1
  82. package/dist/types/common.d.ts +0 -8
  83. package/dist/types/common.d.ts.map +1 -1
  84. package/dist/types/config.d.ts +7 -5
  85. package/dist/types/config.d.ts.map +1 -1
  86. package/dist/types/records-encryption.d.ts +136 -0
  87. package/dist/types/records-encryption.d.ts.map +1 -0
  88. package/dist/types/records.d.ts +171 -20
  89. package/dist/types/records.d.ts.map +1 -1
  90. package/dist/types/verify.d.ts +84 -0
  91. package/dist/types/verify.d.ts.map +1 -0
  92. package/dist/webhooks/index.d.ts +1 -1
  93. package/dist/webhooks/index.d.ts.map +1 -1
  94. package/dist/webhooks/index.js +229 -5
  95. package/dist/webhooks/index.js.map +7 -1
  96. package/dist/webhooks/types.d.ts +15 -7
  97. package/dist/webhooks/types.d.ts.map +1 -1
  98. package/dist/workspace-secret-file.d.ts +18 -0
  99. package/dist/workspace-secret-file.d.ts.map +1 -0
  100. package/package.json +16 -13
  101. package/dist/client.js +0 -553
  102. package/dist/client.js.map +0 -1
  103. package/dist/errors/index.js +0 -223
  104. package/dist/errors/index.js.map +0 -1
  105. package/dist/fingerprint.js +0 -132
  106. package/dist/fingerprint.js.map +0 -1
  107. package/dist/resources/balance.d.ts +0 -384
  108. package/dist/resources/balance.d.ts.map +0 -1
  109. package/dist/resources/balance.js +0 -1120
  110. package/dist/resources/balance.js.map +0 -1
  111. package/dist/resources/customers.d.ts +0 -33
  112. package/dist/resources/customers.d.ts.map +0 -1
  113. package/dist/resources/customers.js +0 -26
  114. package/dist/resources/customers.js.map +0 -1
  115. package/dist/resources/internal/batch-transport.d.ts +0 -65
  116. package/dist/resources/internal/batch-transport.d.ts.map +0 -1
  117. package/dist/resources/internal/batch-transport.js +0 -42
  118. package/dist/resources/internal/batch-transport.js.map +0 -1
  119. package/dist/resources/receipts.d.ts +0 -46
  120. package/dist/resources/receipts.d.ts.map +0 -1
  121. package/dist/resources/receipts.js +0 -133
  122. package/dist/resources/receipts.js.map +0 -1
  123. package/dist/resources/records.js +0 -232
  124. package/dist/resources/records.js.map +0 -1
  125. package/dist/resources/submission.d.ts +0 -79
  126. package/dist/resources/submission.d.ts.map +0 -1
  127. package/dist/resources/submission.js +0 -398
  128. package/dist/resources/submission.js.map +0 -1
  129. package/dist/types/balance.d.ts +0 -966
  130. package/dist/types/balance.d.ts.map +0 -1
  131. package/dist/types/balance.js +0 -3
  132. package/dist/types/balance.js.map +0 -1
  133. package/dist/types/common.js +0 -3
  134. package/dist/types/common.js.map +0 -1
  135. package/dist/types/config.js +0 -3
  136. package/dist/types/config.js.map +0 -1
  137. package/dist/types/records.js +0 -5
  138. package/dist/types/records.js.map +0 -1
  139. package/dist/types/submission.d.ts +0 -125
  140. package/dist/types/submission.d.ts.map +0 -1
  141. package/dist/types/submission.js +0 -3
  142. package/dist/types/submission.js.map +0 -1
  143. package/dist/utils/polling.d.ts +0 -32
  144. package/dist/utils/polling.d.ts.map +0 -1
  145. package/dist/utils/polling.js +0 -52
  146. package/dist/utils/polling.js.map +0 -1
  147. package/dist/utils/retry.js +0 -21
  148. package/dist/utils/retry.js.map +0 -1
  149. package/dist/webhooks/types.js +0 -3
  150. package/dist/webhooks/types.js.map +0 -1
  151. package/dist/webhooks/verify.js +0 -191
  152. package/dist/webhooks/verify.js.map +0 -1
@@ -1,1120 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BalanceResource = void 0;
4
- const polling_1 = require("../utils/polling");
5
- const submission_1 = require("./submission");
6
- const batch_transport_1 = require("./internal/batch-transport");
7
- const receipts_1 = require("./receipts");
8
- const toRecordStatus = (status) => {
9
- const normalized = String(status ?? '').toUpperCase();
10
- if (normalized === 'PROCESSING')
11
- return 'PROCESSING';
12
- if (normalized === 'VERIFIED')
13
- return 'VERIFIED';
14
- if (normalized === 'FAILED')
15
- return 'FAILED';
16
- return 'QUEUED';
17
- };
18
- const toCheckpointType = (value) => {
19
- return String(value) === 'recordId' ? 'recordId' : 'proofRoot';
20
- };
21
- const toApiCheckpointType = (value) => {
22
- if (!value)
23
- return undefined;
24
- return value;
25
- };
26
- /**
27
- * PacSpace Balance API resource.
28
- *
29
- * Provides methods for the five core Balance API operations:
30
- * - `emit()` — Record a credit/debit delta
31
- * - `emitAndWait()` — Record a delta and wait for verification
32
- * - `derive()` — Derive balance from verified deltas
33
- * - `compare()` — Compare balances against neutral truth
34
- * - `receipt()` — Legacy receipt helper (customer-scoped proof generation)
35
- * - `receipts.*` — Headless receipt document APIs by `receiptId`
36
- * - `checkpoint()` — Commit a period-end checkpoint
37
- */
38
- class BalanceResource {
39
- /** @internal */
40
- constructor(client, submissionOptions) {
41
- this.client = client;
42
- this.submission = new submission_1.SubmissionCoordinator({
43
- submitBatch: (deltas) => (0, batch_transport_1.submitInternalBatch)(this.client, deltas),
44
- options: submissionOptions,
45
- });
46
- this.receipts = new receipts_1.ReceiptsResource(this.client);
47
- }
48
- // -------------------------------------------------------------------------
49
- // Emit
50
- // -------------------------------------------------------------------------
51
- /**
52
- * Record a credit or debit delta for a customer.
53
- *
54
- * The delta is queued, independently verified, and confirmed via webhook.
55
- * Returns immediately with `status: 'QUEUED'`. Use `emitAndWait()` to
56
- * block until verification completes.
57
- *
58
- * @param customerId - Unique identifier for the customer account.
59
- * @param delta - Amount to adjust. Positive = credit, negative = debit.
60
- * @param reason - Human-readable reason for the adjustment (audit trail).
61
- * @param options - Optional reference ID, metadata, `adjusts` link, and request overrides.
62
- * @returns The queued delta with its `receiptId`.
63
- *
64
- * @example
65
- * ```typescript
66
- * const delta = await pac.balance.emit('cust_123', -42.50, 'usage_charge');
67
- * console.log(delta.receiptId); // Store this for verification
68
- *
69
- * const adjustment = await pac.balance.emit('cust_123', -10, 'adjustment', {
70
- * adjusts: { referenceId: 'inv_001' },
71
- * });
72
- * ```
73
- */
74
- async emit(customerId, delta, reason, options) {
75
- const { referenceId, metadata, adjusts, ...requestOptions } = options ?? {};
76
- const body = {
77
- customerId,
78
- delta,
79
- reason,
80
- };
81
- if (referenceId !== undefined)
82
- body.referenceId = referenceId;
83
- if (metadata !== undefined)
84
- body.metadata = metadata;
85
- if (adjusts !== undefined)
86
- body.adjusts = adjusts;
87
- const response = await this.client.post('/api/v1/balance/delta', body, requestOptions);
88
- return this.normalizeEmitResponse(response);
89
- }
90
- /**
91
- * Record a delta and wait for it to be verified.
92
- *
93
- * Combines `emit()` with status polling. Resolves when the delta reaches
94
- * a terminal status (`VERIFIED` or `FAILED`), or throws `TimeoutError`
95
- * if the timeout is exceeded.
96
- *
97
- * @param customerId - Unique identifier for the customer account.
98
- * @param delta - Amount to adjust. Positive = credit, negative = debit.
99
- * @param reason - Human-readable reason for the adjustment.
100
- * @param options - Polling timeout, interval, and emit options.
101
- * @returns The verified delta.
102
- *
103
- * @example
104
- * ```typescript
105
- * const verified = await pac.balance.emitAndWait('cust_123', -42.50, 'usage', {
106
- * timeout: 30_000,
107
- * pollInterval: 1000,
108
- * });
109
- * console.log(verified.status); // 'VERIFIED' or 'FAILED'
110
- * ```
111
- */
112
- async emitAndWait(customerId, delta, reason, options) {
113
- const { timeout = 60000, pollInterval = 2000, signal, ...emitOpts } = options ?? {};
114
- const initial = await this.emit(customerId, delta, reason, {
115
- ...emitOpts,
116
- signal,
117
- });
118
- // If already terminal, return immediately
119
- if (['VERIFIED', 'FAILED'].includes(initial.status)) {
120
- return initial;
121
- }
122
- // Poll for terminal status using the balance delta endpoint, then merge
123
- // the latest status with the original emit metadata.
124
- const terminalStatus = await (0, polling_1.pollUntilTerminal)(() => this.deltaStatus(initial.recordId, { signal }), { timeout, pollInterval, signal });
125
- return this.mergeEmitWithStatus(initial, terminalStatus);
126
- }
127
- /**
128
- * Check the status of a previously emitted delta.
129
- *
130
- * @param recordId - The record ID returned from emit.
131
- * @param options - Request overrides.
132
- * @returns Delta status with receipt and transaction details.
133
- *
134
- * @example
135
- * ```typescript
136
- * const status = await pac.balance.deltaStatus('rec_abc123');
137
- * console.log(status.status); // 'QUEUED', 'PROCESSING', etc.
138
- * ```
139
- */
140
- async deltaStatus(recordId, options) {
141
- const response = await this.client.get(`/api/v1/balance/delta/${encodeURIComponent(recordId)}`, options);
142
- return this.normalizeDeltaStatusResponse(response);
143
- }
144
- /**
145
- * Alias for `deltaStatus()` with lifecycle-oriented naming.
146
- */
147
- async getRecordStatus(recordId, options) {
148
- return this.deltaStatus(recordId, options);
149
- }
150
- /**
151
- * Poll record lifecycle until it reaches a terminal status.
152
- *
153
- * Terminal statuses are `VERIFIED` and `FAILED`.
154
- */
155
- async waitForVerified(recordId, options) {
156
- const { timeout = 60000, pollInterval = 2000, signal, ...requestOptions } = options ?? {};
157
- return (0, polling_1.pollUntilTerminal)(() => this.getRecordStatus(recordId, {
158
- ...requestOptions,
159
- signal,
160
- }), { timeout, pollInterval, signal });
161
- }
162
- /**
163
- * Retrieve tenant usage counters and remaining allotment.
164
- */
165
- async usage(options) {
166
- return this.client.get('/api/v1/balance/usage', options);
167
- }
168
- /**
169
- * Detect missing per-customer sequence ranges.
170
- *
171
- * Use this to identify gaps and re-emit missing deltas safely.
172
- */
173
- async gaps(customerId, options) {
174
- const { fromSequence, toSequence, limit, ...requestOptions } = options ?? {};
175
- const params = new URLSearchParams();
176
- if (fromSequence !== undefined)
177
- params.set('fromSequence', fromSequence);
178
- if (toSequence !== undefined)
179
- params.set('toSequence', toSequence);
180
- if (limit !== undefined)
181
- params.set('limit', String(limit));
182
- const query = params.toString();
183
- const path = `/api/v1/balance/gaps/${encodeURIComponent(customerId)}${query ? `?${query}` : ''}`;
184
- const response = await this.client.get(path, requestOptions);
185
- return this.normalizeSequenceGapsResponse(response);
186
- }
187
- /**
188
- * Queue one tenant-produced summary for SDK-managed submission.
189
- */
190
- queueSummary(summary) {
191
- return this.submission.queueSummary(summary);
192
- }
193
- /**
194
- * Queue multiple tenant-produced summaries.
195
- */
196
- queueSummaries(summaries) {
197
- return this.submission.queueSummaries(summaries);
198
- }
199
- /**
200
- * Flush queued summaries immediately.
201
- */
202
- async flushSummaries(options) {
203
- return this.submission.flushSummaries(options);
204
- }
205
- /**
206
- * Start periodic summary submission scheduling.
207
- */
208
- startSummaryScheduler() {
209
- this.submission.start();
210
- }
211
- /**
212
- * Stop periodic summary submission scheduling.
213
- */
214
- stopSummaryScheduler() {
215
- this.submission.stop();
216
- }
217
- /**
218
- * Get queue/scheduler state for summary submission automation.
219
- */
220
- getSummaryQueueState() {
221
- return this.submission.getQueueState();
222
- }
223
- /**
224
- * Stop scheduler and flush queued summaries (best for graceful shutdown).
225
- */
226
- async shutdownSummaryScheduler() {
227
- await this.submission.shutdown();
228
- }
229
- // -------------------------------------------------------------------------
230
- // Derive
231
- // -------------------------------------------------------------------------
232
- /**
233
- * Derive a customer's balance from all verified deltas.
234
- *
235
- * Any party can independently compute the same balance from the same deltas.
236
- * Supports checkpointing to avoid replaying from genesis at scale.
237
- *
238
- * @param customerId - The customer account to derive balance for.
239
- * @param options - Starting balance, checkpoint, and request overrides.
240
- * @returns Derived balance with delta history and window summaries.
241
- *
242
- * @example
243
- * ```typescript
244
- * const { computedBalance, latestReceiptId } = await pac.balance.derive('cust_123');
245
- *
246
- * // Use checkpoint for efficient subsequent derivations:
247
- * const next = await pac.balance.derive('cust_123', {
248
- * startingBalance: computedBalance,
249
- * startingCheckpoint: latestReceiptId,
250
- * });
251
- * ```
252
- */
253
- async derive(customerId, options) {
254
- const { startingBalance, startingCheckpoint, startingCheckpointType, limit, offset, period, timePreset, startDate, endDate, ...requestOptions } = options ?? {};
255
- // Build query string
256
- const params = new URLSearchParams();
257
- if (startingBalance !== undefined) {
258
- params.set('startingBalance', String(startingBalance));
259
- }
260
- if (startingCheckpoint !== undefined) {
261
- params.set('startingCheckpoint', startingCheckpoint);
262
- }
263
- const apiCheckpointType = toApiCheckpointType(startingCheckpointType);
264
- if (apiCheckpointType !== undefined) {
265
- params.set('startingCheckpointType', apiCheckpointType);
266
- }
267
- if (limit !== undefined) {
268
- params.set('limit', String(limit));
269
- }
270
- if (offset !== undefined) {
271
- params.set('offset', String(offset));
272
- }
273
- if (period !== undefined) {
274
- params.set('period', period);
275
- }
276
- if (timePreset !== undefined) {
277
- params.set('timePreset', timePreset);
278
- }
279
- if (startDate !== undefined) {
280
- params.set('startDate', startDate);
281
- }
282
- if (endDate !== undefined) {
283
- params.set('endDate', endDate);
284
- }
285
- const query = params.toString();
286
- const path = `/api/v1/balance/derive/${encodeURIComponent(customerId)}${query ? `?${query}` : ''}`;
287
- const response = await this.client.get(path, requestOptions);
288
- return this.normalizeDeriveResponse(response);
289
- }
290
- /**
291
- * Convenience helper for deriving the current UTC month.
292
- */
293
- async deriveCurrentMonth(customerId, options) {
294
- return this.derive(customerId, {
295
- ...options,
296
- timePreset: 'current_month',
297
- });
298
- }
299
- /**
300
- * Convenience helper for deriving a specific UTC month (`YYYY-MM`).
301
- */
302
- async deriveForPeriod(customerId, period, options) {
303
- return this.derive(customerId, {
304
- ...options,
305
- period,
306
- });
307
- }
308
- /**
309
- * Convenience helper for deriving a rolling window of recent UTC months.
310
- *
311
- * For example, `months = 3` resolves from the start of month N-2 through the
312
- * end of the current UTC month.
313
- */
314
- async deriveMonthsBack(customerId, months, options) {
315
- if (!Number.isInteger(months) || months < 1) {
316
- throw new TypeError('months must be a positive integer');
317
- }
318
- const now = new Date();
319
- const endExclusive = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1));
320
- const start = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - (months - 1), 1));
321
- return this.derive(customerId, {
322
- ...options,
323
- timePreset: 'custom',
324
- startDate: start.toISOString(),
325
- endDate: endExclusive.toISOString(),
326
- });
327
- }
328
- /**
329
- * Convenience helper for deriving the previous N UTC days.
330
- */
331
- async deriveDaysBack(customerId, days, options) {
332
- if (!Number.isInteger(days) || days < 1) {
333
- throw new TypeError('days must be a positive integer');
334
- }
335
- const now = new Date();
336
- const endExclusive = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1, 0, 0, 0, 0));
337
- const start = new Date(endExclusive);
338
- start.setUTCDate(start.getUTCDate() - days);
339
- return this.derive(customerId, {
340
- ...options,
341
- timePreset: 'custom',
342
- startDate: start.toISOString(),
343
- endDate: endExclusive.toISOString(),
344
- });
345
- }
346
- // -------------------------------------------------------------------------
347
- // Compare
348
- // -------------------------------------------------------------------------
349
- /**
350
- * Compare balances against neutral truth for dispute resolution.
351
- *
352
- * Submit your balance and your counterparty's balance. PacSpace derives
353
- * the neutral truth from verified deltas and returns a discrepancy report
354
- * showing which party matches and which window(s) diverged.
355
- *
356
- * @param customerId - The customer account to compare.
357
- * @param balances - Your balance and their balance.
358
- * @param options - Starting balance, checkpoint, and request overrides.
359
- * @returns Comparison result with discrepancy report.
360
- *
361
- * @example
362
- * ```typescript
363
- * const report = await pac.balance.compare('cust_123', {
364
- * yours: 95000,
365
- * theirs: 98000,
366
- * });
367
- *
368
- * if (report.matchesYours) {
369
- * console.log('Your balance is correct');
370
- * }
371
- * ```
372
- */
373
- async compare(customerId, balances, options) {
374
- const { startingBalance = 0, startingCheckpoint, startingCheckpointType, period, timePreset, startDate, endDate, ...requestOptions } = options ?? {};
375
- const body = {
376
- customerId,
377
- yourBalance: balances.yours,
378
- theirBalance: balances.theirs,
379
- startingBalance,
380
- };
381
- if (startingCheckpoint !== undefined) {
382
- body.startingCheckpoint = startingCheckpoint;
383
- }
384
- const apiCheckpointType = toApiCheckpointType(startingCheckpointType);
385
- if (apiCheckpointType !== undefined) {
386
- body.startingCheckpointType = apiCheckpointType;
387
- }
388
- if (period !== undefined) {
389
- body.period = period;
390
- }
391
- if (timePreset !== undefined) {
392
- body.timePreset = timePreset;
393
- }
394
- if (startDate !== undefined) {
395
- body.startDate = startDate;
396
- }
397
- if (endDate !== undefined) {
398
- body.endDate = endDate;
399
- }
400
- const response = await this.client.post('/api/v1/balance/compare', body, requestOptions);
401
- return this.normalizeCompareResponse(response);
402
- }
403
- async receipt(customerId, options) {
404
- const opts = options ?? {};
405
- const hasScopedReceipt = opts.period !== undefined ||
406
- opts.timePreset !== undefined ||
407
- opts.startDate !== undefined ||
408
- opts.endDate !== undefined;
409
- if (hasScopedReceipt) {
410
- return this.receiptForPeriod(customerId, opts);
411
- }
412
- const { period: _period, timePreset: _timePreset, startDate: _startDate, endDate: _endDate, ...requestOptions } = opts;
413
- const hasOverrides = Object.keys(requestOptions).length > 0;
414
- const response = await this.client.get(`/api/v1/balance/receipt/${encodeURIComponent(customerId)}`, hasOverrides ? requestOptions : undefined);
415
- return this.normalizeReceiptResponse(response);
416
- }
417
- /**
418
- * @internal
419
- * Generate a period-specific receipt (proof root, verifyUrl). Used by receipt().
420
- */
421
- async receiptForPeriod(customerId, options) {
422
- const { period, timePreset, startDate, endDate, ...requestOptions } = options ?? {};
423
- const params = new URLSearchParams();
424
- if (period !== undefined)
425
- params.set('period', period);
426
- if (timePreset !== undefined)
427
- params.set('timePreset', timePreset);
428
- if (startDate !== undefined)
429
- params.set('startDate', startDate);
430
- if (endDate !== undefined)
431
- params.set('endDate', endDate);
432
- const query = params.toString();
433
- const path = `/api/v1/balance/invoice-proof/${encodeURIComponent(customerId)}${query ? `?${query}` : ''}`;
434
- const response = await this.client.get(path, requestOptions);
435
- return this.normalizeInvoiceProofResponse(response);
436
- }
437
- // -------------------------------------------------------------------------
438
- // Checkpoint
439
- // -------------------------------------------------------------------------
440
- /**
441
- * Commit a period-end checkpoint.
442
- *
443
- * Computes a proof root over all verified deltas in the billing window
444
- * and records it on the proof layer. The proof root can be
445
- * included in invoices for instant counterparty verification.
446
- *
447
- * @param customerId - Customer to checkpoint (omit for all customers).
448
- * @param options - Period (YYYY-MM) and request overrides.
449
- * @returns Checkpoint details with proof root and status.
450
- *
451
- * @example
452
- * ```typescript
453
- * const checkpoint = await pac.balance.checkpoint('cust_123', {
454
- * period: '2026-02',
455
- * });
456
- * console.log(checkpoint.proofRoot); // Include in your invoice
457
- * ```
458
- */
459
- async checkpoint(customerId, options) {
460
- const { period, timePreset, startDate, endDate, mode, fingerprints, ...requestOptions } = options ?? {};
461
- const body = {};
462
- if (customerId !== undefined)
463
- body.customerId = customerId;
464
- if (period !== undefined)
465
- body.period = period;
466
- if (timePreset !== undefined)
467
- body.timePreset = timePreset;
468
- if (startDate !== undefined)
469
- body.startDate = startDate;
470
- if (endDate !== undefined)
471
- body.endDate = endDate;
472
- if (mode !== undefined)
473
- body.mode = mode;
474
- if (fingerprints !== undefined)
475
- body.fingerprints = fingerprints;
476
- const response = await this.client.post('/api/v1/balance/checkpoint', body, requestOptions);
477
- return this.normalizeCheckpointResponse(response);
478
- }
479
- // -------------------------------------------------------------------------
480
- // List Checkpoints
481
- // -------------------------------------------------------------------------
482
- /**
483
- * List committed checkpoints for your tenant.
484
- *
485
- * Returns a paginated list of checkpoints, optionally filtered by
486
- * customer ID and/or billing period.
487
- *
488
- * @param options - Filter and pagination options.
489
- * @returns Paginated list of checkpoints.
490
- *
491
- * @example
492
- * ```typescript
493
- * const { checkpoints } = await pac.balance.listCheckpoints({
494
- * period: '2026-02',
495
- * limit: 10,
496
- * });
497
- * ```
498
- */
499
- async listCheckpoints(options) {
500
- const { customerId, period, timePreset, startDate, endDate, limit, offset, ...requestOptions } = options ?? {};
501
- const params = new URLSearchParams();
502
- if (customerId !== undefined)
503
- params.set('customerId', customerId);
504
- if (period !== undefined)
505
- params.set('period', period);
506
- if (timePreset !== undefined)
507
- params.set('timePreset', timePreset);
508
- if (startDate !== undefined)
509
- params.set('startDate', startDate);
510
- if (endDate !== undefined)
511
- params.set('endDate', endDate);
512
- if (limit !== undefined)
513
- params.set('limit', String(limit));
514
- if (offset !== undefined)
515
- params.set('offset', String(offset));
516
- const query = params.toString();
517
- const path = `/api/v1/balance/checkpoints${query ? `?${query}` : ''}`;
518
- const response = await this.client.get(path, requestOptions);
519
- return this.normalizeListCheckpointsResponse(response);
520
- }
521
- /**
522
- * List checkpoint timeline points and detected coverage gaps.
523
- */
524
- async listCheckpointTimeline(customerId, options) {
525
- const { monthsBack, startDate, endDate, ...requestOptions } = options ?? {};
526
- const params = new URLSearchParams();
527
- if (monthsBack !== undefined)
528
- params.set('monthsBack', String(monthsBack));
529
- if (startDate !== undefined)
530
- params.set('startDate', startDate);
531
- if (endDate !== undefined)
532
- params.set('endDate', endDate);
533
- const query = params.toString();
534
- const path = `/api/v1/balance/checkpoint-timeline/${encodeURIComponent(customerId)}${query ? `?${query}` : ''}`;
535
- return this.client.get(path, requestOptions);
536
- }
537
- /**
538
- * Compare two checkpoints and return fingerprint and daily divergence deltas.
539
- */
540
- async diffCheckpoints(customerId, leftCheckpointId, rightCheckpointId, options) {
541
- return this.client.post(`/api/v1/balance/checkpoint-diff/${encodeURIComponent(customerId)}`, {
542
- leftCheckpointId,
543
- rightCheckpointId,
544
- }, options);
545
- }
546
- // -------------------------------------------------------------------------
547
- // Webhook Deliveries
548
- // -------------------------------------------------------------------------
549
- /**
550
- * List webhook delivery history.
551
- *
552
- * @param options - Filter and pagination options.
553
- * @returns Paginated list of webhook deliveries.
554
- *
555
- * @example
556
- * ```typescript
557
- * const { deliveries } = await pac.balance.listWebhookDeliveries({
558
- * status: 'failed',
559
- * limit: 10,
560
- * });
561
- * ```
562
- */
563
- async listWebhookDeliveries(options) {
564
- const { status, limit, offset, ...requestOptions } = options ?? {};
565
- const params = new URLSearchParams();
566
- if (status !== undefined)
567
- params.set('status', status);
568
- if (limit !== undefined)
569
- params.set('limit', String(limit));
570
- if (offset !== undefined)
571
- params.set('offset', String(offset));
572
- const query = params.toString();
573
- const path = `/api/v1/balance/webhooks${query ? `?${query}` : ''}`;
574
- return this.client.get(path, requestOptions);
575
- }
576
- /**
577
- * Retry a failed webhook delivery.
578
- *
579
- * @param eventId - The event ID of the failed delivery.
580
- * @param options - Request overrides.
581
- *
582
- * @example
583
- * ```typescript
584
- * await pac.balance.retryWebhook('evt_abc123');
585
- * ```
586
- */
587
- async retryWebhook(eventId, options) {
588
- return this.client.post(`/api/v1/balance/webhooks/${encodeURIComponent(eventId)}/retry`, {}, options);
589
- }
590
- // -------------------------------------------------------------------------
591
- // Customer Ledgers
592
- // -------------------------------------------------------------------------
593
- /**
594
- * List all customer balance records for your account.
595
- *
596
- * Each unique customerId passed to emit() automatically creates an
597
- * isolated customer record. This method returns a paginated list.
598
- *
599
- * @param options - Search, pagination, and request overrides.
600
- * @returns Paginated list of customer records.
601
- *
602
- * @example
603
- * ```typescript
604
- * const { customers } = await pac.balance.customers();
605
- * for (const c of customers) {
606
- * console.log(c.customerId, c.totalDeltas);
607
- * }
608
- * ```
609
- */
610
- async customers(options) {
611
- const { search, limit, page, ...requestOptions } = options ?? {};
612
- const params = new URLSearchParams();
613
- if (search !== undefined)
614
- params.set('search', search);
615
- if (limit !== undefined)
616
- params.set('limit', String(limit));
617
- if (page !== undefined)
618
- params.set('page', String(page));
619
- const query = params.toString();
620
- const path = `/api/v1/balance/customers${query ? `?${query}` : ''}`;
621
- const response = await this.client.get(path, requestOptions);
622
- return this.normalizeListCustomersResponse(response);
623
- }
624
- /**
625
- * Get the full record detail for a specific customer.
626
- *
627
- * Returns the derived customer reference, computed balance, delta count,
628
- * and latest checkpoint. The customer reference is deterministic.
629
- *
630
- * @param customerId - The customer to look up.
631
- * @param options - Activity pagination and request overrides.
632
- * @returns Customer detail including balance and references.
633
- *
634
- * @example
635
- * ```typescript
636
- * const customer = await pac.balance.customer('cust_001');
637
- * console.log(customer.customerReference); // 0xA1b2...Ef34
638
- * console.log(customer.computedBalance); // 4500.00
639
- * ```
640
- */
641
- async customer(customerId, options) {
642
- const { deltaPage, deltaLimit, period, ...requestOptions } = options ?? {};
643
- const params = new URLSearchParams();
644
- if (deltaPage !== undefined)
645
- params.set('deltaPage', String(deltaPage));
646
- if (deltaLimit !== undefined)
647
- params.set('deltaLimit', String(deltaLimit));
648
- if (period !== undefined)
649
- params.set('period', period);
650
- const query = params.toString();
651
- const path = `/api/v1/balance/customers/${encodeURIComponent(customerId)}${query ? `?${query}` : ''}`;
652
- const response = await this.client.get(path, requestOptions);
653
- return this.normalizeCustomerDetailResponse(response);
654
- }
655
- normalizeEmitResponse(data) {
656
- // ADR 0008 §5 (N-4): receiptId and proofRoot are distinct identifiers and
657
- // neither stands in for the other.
658
- return {
659
- recordId: String(data.recordId ?? ''),
660
- customerId: String(data.customerId ?? ''),
661
- delta: Number(data.delta ?? 0),
662
- sequenceNumber: data.sequenceNumber == null ? undefined : String(data.sequenceNumber),
663
- status: toRecordStatus(data.status),
664
- receiptId: String(data.receiptId ?? ''),
665
- proofRoot: String(data.proofRoot ?? ''),
666
- itemHashes: Array.isArray(data.itemHashes)
667
- ? data.itemHashes.map((value) => String(value))
668
- : [],
669
- estimatedVerifiedDeltas: Number(data.estimatedVerifiedDeltas ?? 0),
670
- estimatedCredits: Number(data.estimatedCredits ?? 0),
671
- receivedAt: String(data.receivedAt ?? ''),
672
- message: String(data.message ?? ''),
673
- };
674
- }
675
- mergeEmitWithStatus(initial, status) {
676
- const firstDelta = status.deltas[0];
677
- const customerId = status.customerId ?? firstDelta?.customerId ?? initial.customerId;
678
- const delta = status.delta ?? firstDelta?.delta ?? initial.delta;
679
- const sequenceNumber = firstDelta?.sequenceNumber ?? initial.sequenceNumber;
680
- return {
681
- ...initial,
682
- recordId: status.recordId || initial.recordId,
683
- customerId: customerId == null ? initial.customerId : String(customerId),
684
- delta: delta == null ? initial.delta : Number(delta),
685
- sequenceNumber: sequenceNumber ?? undefined,
686
- status: status.status,
687
- receiptId: status.receiptId ?? initial.receiptId,
688
- // The status response carries no proof root; the one from the emit stands.
689
- proofRoot: initial.proofRoot,
690
- receivedAt: status.receivedAt || initial.receivedAt,
691
- message: status.status === 'VERIFIED'
692
- ? 'Delta verified.'
693
- : status.status === 'FAILED'
694
- ? 'Delta verification failed.'
695
- : initial.message,
696
- };
697
- }
698
- normalizeDeltaStatusResponse(data) {
699
- const deltas = Array.isArray(data.deltas)
700
- ? data.deltas.map((entry) => {
701
- const item = entry;
702
- return {
703
- customerId: item.customerId == null ? null : String(item.customerId),
704
- delta: item.delta == null ? null : Number(item.delta),
705
- sequenceNumber: item.sequenceNumber == null ? null : String(item.sequenceNumber),
706
- };
707
- })
708
- : [];
709
- return {
710
- recordId: String(data.recordId ?? ''),
711
- status: toRecordStatus(data.status),
712
- deltaCount: Number(data.deltaCount ?? deltas.length),
713
- customerId: data.customerId == null ? null : String(data.customerId),
714
- delta: data.delta == null ? null : Number(data.delta),
715
- deltas,
716
- receiptId: data.receiptId == null ? null : String(data.receiptId),
717
- verificationReference: data.verificationReference == null ? null : String(data.verificationReference),
718
- receivedAt: String(data.receivedAt ?? ''),
719
- verifiedAt: data.verifiedAt == null ? null : String(data.verifiedAt),
720
- };
721
- }
722
- normalizeDeriveResponse(data) {
723
- const deltas = Array.isArray(data.deltas)
724
- ? data.deltas.map((entry) => {
725
- const item = entry;
726
- return {
727
- recordId: String(item.recordId ?? ''),
728
- itemHash: String(item.itemHash ?? ''),
729
- proofRoot: String(item.proofRoot ?? ''),
730
- receiptId: String(item.receiptId ?? ''),
731
- sequenceNumber: item.sequenceNumber == null ? null : String(item.sequenceNumber),
732
- delta: Number(item.delta ?? 0),
733
- reason: item.reason == null ? null : String(item.reason),
734
- referenceId: item.referenceId == null ? null : String(item.referenceId),
735
- window: String(item.window ?? ''),
736
- declaredTimestamp: item.declaredTimestamp == null
737
- ? null
738
- : String(item.declaredTimestamp),
739
- blockTimestamp: item.blockTimestamp == null ? null : String(item.blockTimestamp),
740
- dataPurged: Boolean(item.dataPurged),
741
- verified: true,
742
- };
743
- })
744
- : [];
745
- const verificationProof = (data.verificationProof ??
746
- {});
747
- const windowSummaries = Array.isArray(data.windowSummaries)
748
- ? data.windowSummaries.map((entry) => {
749
- const item = entry;
750
- return {
751
- window: String(item.window ?? ''),
752
- deltasCount: Number(item.deltasCount ?? 0),
753
- netDelta: Number(item.netDelta ?? 0),
754
- firstBlockTimestamp: item.firstBlockTimestamp == null
755
- ? null
756
- : String(item.firstBlockTimestamp),
757
- lastBlockTimestamp: item.lastBlockTimestamp == null
758
- ? null
759
- : String(item.lastBlockTimestamp),
760
- };
761
- })
762
- : [];
763
- const scope = (data.scope ?? null);
764
- const monthlyBreakdown = Array.isArray(data.monthlyBreakdown)
765
- ? data.monthlyBreakdown.map((entry) => {
766
- const item = entry;
767
- const checkpoint = (item.checkpoint ?? null);
768
- return {
769
- period: String(item.period ?? ''),
770
- periodStart: String(item.periodStart ?? ''),
771
- periodEndExclusive: String(item.periodEndExclusive ?? ''),
772
- deltaCount: Number(item.deltaCount ?? 0),
773
- netDelta: Number(item.netDelta ?? 0),
774
- runningBalance: Number(item.runningBalance ?? 0),
775
- checkpoint: checkpoint
776
- ? {
777
- checkpointId: String(checkpoint.checkpointId ?? ''),
778
- proofRoot: checkpoint.proofRoot == null
779
- ? null
780
- : String(checkpoint.proofRoot),
781
- status: toRecordStatus(checkpoint.status),
782
- }
783
- : null,
784
- };
785
- })
786
- : undefined;
787
- const pagination = (data.pagination ?? {});
788
- const hint = data._hint;
789
- return {
790
- customerId: String(data.customerId ?? ''),
791
- startingBalance: Number(data.startingBalance ?? 0),
792
- startingCheckpoint: String(data.startingCheckpoint ?? 'genesis'),
793
- startingCheckpointType: toCheckpointType(data.startingCheckpointType),
794
- deltasCount: Number(data.deltasCount ?? deltas.length),
795
- computedBalance: Number(data.computedBalance ?? 0),
796
- latestCheckpoint: data.latestCheckpoint == null ? null : String(data.latestCheckpoint),
797
- latestReceiptId: data.latestReceiptId == null ? null : String(data.latestReceiptId),
798
- deltas,
799
- windowSummaries,
800
- verificationProof: {
801
- proofRoot: verificationProof.proofRoot == null
802
- ? null
803
- : String(verificationProof.proofRoot),
804
- message: String(verificationProof.message ?? ''),
805
- },
806
- scope: scope
807
- ? {
808
- kind: String(scope.kind ?? 'period') === 'custom'
809
- ? 'custom'
810
- : String(scope.kind ?? 'period') === 'preset'
811
- ? 'preset'
812
- : 'period',
813
- periodId: scope.periodId == null ? null : String(scope.periodId),
814
- preset: scope.preset == null
815
- ? null
816
- : String(scope.preset),
817
- startDate: String(scope.startDate ?? ''),
818
- endDateExclusive: String(scope.endDateExclusive ?? ''),
819
- label: String(scope.label ?? ''),
820
- }
821
- : null,
822
- monthlyBreakdown,
823
- cumulativeBalance: data.cumulativeBalance == null
824
- ? undefined
825
- : Number(data.cumulativeBalance),
826
- pagination: {
827
- total: Number(pagination.total ?? deltas.length),
828
- limit: Number(pagination.limit ?? deltas.length),
829
- offset: Number(pagination.offset ?? 0),
830
- },
831
- _hint: hint == null
832
- ? undefined
833
- : {
834
- message: String(hint.message ?? ''),
835
- recommendation: String(hint.recommendation ?? ''),
836
- docsUrl: String(hint.docsUrl ?? ''),
837
- },
838
- };
839
- }
840
- normalizeCompareResponse(data) {
841
- const proof = (data.proof ?? {});
842
- const scope = (data.scope ?? null);
843
- const monthlyBreakdown = Array.isArray(data.monthlyBreakdown)
844
- ? data.monthlyBreakdown.map((entry) => {
845
- const item = entry;
846
- const checkpoint = (item.checkpoint ?? null);
847
- return {
848
- period: String(item.period ?? ''),
849
- periodStart: String(item.periodStart ?? ''),
850
- periodEndExclusive: String(item.periodEndExclusive ?? ''),
851
- deltaCount: Number(item.deltaCount ?? 0),
852
- netDelta: Number(item.netDelta ?? 0),
853
- runningBalance: Number(item.runningBalance ?? 0),
854
- checkpoint: checkpoint
855
- ? {
856
- checkpointId: String(checkpoint.checkpointId ?? ''),
857
- proofRoot: checkpoint.proofRoot == null
858
- ? null
859
- : String(checkpoint.proofRoot),
860
- status: toRecordStatus(checkpoint.status),
861
- }
862
- : null,
863
- };
864
- })
865
- : undefined;
866
- return {
867
- customerId: String(data.customerId ?? ''),
868
- yourBalance: Number(data.yourBalance ?? 0),
869
- theirBalance: Number(data.theirBalance ?? 0),
870
- neutralBalance: Number(data.neutralBalance ?? 0),
871
- matchesYours: Boolean(data.matchesYours),
872
- matchesTheirs: Boolean(data.matchesTheirs),
873
- deltasVerified: Number(data.deltasVerified ?? 0),
874
- discrepancyReport: data.discrepancyReport ?? null,
875
- proof: {
876
- proofRoot: proof.proofRoot == null ? null : String(proof.proofRoot),
877
- latestCheckpoint: proof.latestCheckpoint == null ? null : String(proof.latestCheckpoint),
878
- windowSummaries: proof.windowSummaries ??
879
- [],
880
- },
881
- scope: scope
882
- ? {
883
- kind: String(scope.kind ?? 'period') === 'custom'
884
- ? 'custom'
885
- : String(scope.kind ?? 'period') === 'preset'
886
- ? 'preset'
887
- : 'period',
888
- periodId: scope.periodId == null ? null : String(scope.periodId),
889
- preset: scope.preset == null
890
- ? null
891
- : String(scope.preset),
892
- startDate: String(scope.startDate ?? ''),
893
- endDateExclusive: String(scope.endDateExclusive ?? ''),
894
- label: String(scope.label ?? ''),
895
- }
896
- : null,
897
- monthlyBreakdown,
898
- cumulativeBalance: data.cumulativeBalance == null
899
- ? undefined
900
- : Number(data.cumulativeBalance),
901
- };
902
- }
903
- normalizeReceiptResponse(data) {
904
- const verification = (data.verification ?? {});
905
- return {
906
- customerId: String(data.customerId ?? ''),
907
- generatedAt: String(data.generatedAt ?? ''),
908
- deltasCount: Number(data.deltasCount ?? 0),
909
- finalBalance: Number(data.finalBalance ?? 0),
910
- proofRoot: data.proofRoot == null ? null : String(data.proofRoot),
911
- receiptId: data.receiptId == null ? null : String(data.receiptId),
912
- latestCheckpoint: data.latestCheckpoint == null ? null : String(data.latestCheckpoint),
913
- deltas: data.deltas ?? [],
914
- windowSummaries: data.windowSummaries ?? [],
915
- verification: {
916
- message: String(verification.message ?? ''),
917
- itemHashes: Array.isArray(verification.itemHashes)
918
- ? verification.itemHashes.map((value) => String(value))
919
- : [],
920
- },
921
- };
922
- }
923
- normalizeInvoiceProofResponse(data) {
924
- return {
925
- customerId: String(data.customerId ?? ''),
926
- period: String(data.period ?? ''),
927
- proofRoot: String(data.proofRoot ?? ''),
928
- verificationReference: data.verificationReference == null
929
- ? null
930
- : String(data.verificationReference),
931
- verificationApiUrl: data.verificationApiUrl == null ? null : String(data.verificationApiUrl),
932
- verificationExplorerUrl: data.verificationExplorerUrl == null
933
- ? null
934
- : String(data.verificationExplorerUrl),
935
- verifyUrl: data.verifyUrl == null ? null : String(data.verifyUrl),
936
- accessHint: data.accessHint == null ? null : String(data.accessHint),
937
- customerLinkUrl: data.customerLinkUrl == null ? null : String(data.customerLinkUrl),
938
- customerLinkHost: data.customerLinkHost == null ? null : String(data.customerLinkHost),
939
- deltaCount: Number(data.deltaCount ?? 0),
940
- startingBalance: Number(data.startingBalance ?? 0),
941
- finalBalance: Number(data.finalBalance ?? 0),
942
- windowSummary: data.windowSummary ??
943
- {
944
- window: '',
945
- deltasCount: 0,
946
- netDelta: 0,
947
- firstDeltaAt: null,
948
- lastDeltaAt: null,
949
- },
950
- deltas: data.deltas ?? [],
951
- verification: data.verification ??
952
- {
953
- proofRoot: null,
954
- totalBalance: 0,
955
- periodBalance: 0,
956
- },
957
- };
958
- }
959
- normalizeCheckpointResponse(data) {
960
- return {
961
- checkpointId: String(data.checkpointId ?? ''),
962
- period: String(data.period ?? ''),
963
- proofRoot: String(data.proofRoot ?? ''),
964
- scope: data.scope,
965
- mode: data.mode,
966
- deltaCount: Number(data.deltaCount ?? 0),
967
- selectedFingerprintCount: data.selectedFingerprintCount == null
968
- ? undefined
969
- : Number(data.selectedFingerprintCount),
970
- eligibleFingerprintCount: data.eligibleFingerprintCount == null
971
- ? undefined
972
- : Number(data.eligibleFingerprintCount),
973
- selectedFingerprints: Array.isArray(data.selectedFingerprints)
974
- ? data.selectedFingerprints.map((value) => String(value))
975
- : undefined,
976
- fromIndex: Number(data.fromIndex ?? 0),
977
- toIndex: Number(data.toIndex ?? 0),
978
- customerId: String(data.customerId ?? ''),
979
- status: toRecordStatus(data.status),
980
- message: String(data.message ?? ''),
981
- };
982
- }
983
- normalizeListCheckpointsResponse(data) {
984
- const checkpoints = Array.isArray(data.checkpoints)
985
- ? data.checkpoints.map((entry) => {
986
- const item = entry;
987
- return {
988
- checkpointId: String(item.checkpointId ?? ''),
989
- period: String(item.period ?? ''),
990
- proofRoot: item.proofRoot == null ? null : String(item.proofRoot),
991
- scope: item.scope,
992
- mode: item.mode,
993
- deltaCount: Number(item.deltaCount ?? 0),
994
- selectedFingerprintCount: item.selectedFingerprintCount == null
995
- ? undefined
996
- : Number(item.selectedFingerprintCount),
997
- eligibleFingerprintCount: item.eligibleFingerprintCount == null
998
- ? undefined
999
- : Number(item.eligibleFingerprintCount),
1000
- customerId: String(item.customerId ?? ''),
1001
- status: toRecordStatus(item.status),
1002
- verificationReference: item.verificationReference == null
1003
- ? null
1004
- : String(item.verificationReference),
1005
- verifiedAt: item.verifiedAt == null ? null : String(item.verifiedAt),
1006
- receivedAt: String(item.receivedAt ?? ''),
1007
- };
1008
- })
1009
- : [];
1010
- const pagination = (data.pagination ?? {});
1011
- return {
1012
- checkpoints,
1013
- pagination: {
1014
- total: Number(pagination.total ?? checkpoints.length),
1015
- limit: Number(pagination.limit ?? checkpoints.length),
1016
- offset: Number(pagination.offset ?? 0),
1017
- },
1018
- };
1019
- }
1020
- normalizeSequenceGapsResponse(data) {
1021
- const gaps = Array.isArray(data.gaps)
1022
- ? data.gaps.map((entry) => {
1023
- const item = entry;
1024
- return {
1025
- startSequence: String(item.startSequence ?? ''),
1026
- endSequence: String(item.endSequence ?? ''),
1027
- missingCount: String(item.missingCount ?? '0'),
1028
- };
1029
- })
1030
- : [];
1031
- return {
1032
- customerId: String(data.customerId ?? ''),
1033
- customerReference: String(data.customerReference ?? ''),
1034
- customerPartition: String(data.customerPartition ?? ''),
1035
- nextSequence: String(data.nextSequence ?? '0'),
1036
- rangeStart: String(data.rangeStart ?? '0'),
1037
- rangeEnd: String(data.rangeEnd ?? '0'),
1038
- gaps,
1039
- hasGaps: Boolean(data.hasGaps),
1040
- missingRanges: Number(data.missingRanges ?? gaps.length),
1041
- missingCountInPage: String(data.missingCountInPage ?? '0'),
1042
- truncated: Boolean(data.truncated),
1043
- };
1044
- }
1045
- normalizeListCustomersResponse(data) {
1046
- const customers = Array.isArray(data.customers)
1047
- ? data.customers.map((entry) => {
1048
- const item = entry;
1049
- return {
1050
- customerId: String(item.customerId ?? ''),
1051
- customerReference: String(item.customerReference ?? ''),
1052
- totalDeltas: Number(item.totalDeltas ?? 0),
1053
- firstDeltaAt: item.firstDeltaAt == null ? null : String(item.firstDeltaAt),
1054
- lastDeltaAt: item.lastDeltaAt == null ? null : String(item.lastDeltaAt),
1055
- };
1056
- })
1057
- : [];
1058
- const pagination = (data.pagination ?? {});
1059
- return {
1060
- customers,
1061
- pagination: {
1062
- total: Number(pagination.total ?? customers.length),
1063
- page: Number(pagination.page ?? 1),
1064
- limit: Number(pagination.limit ?? customers.length),
1065
- totalPages: Number(pagination.totalPages ?? 1),
1066
- },
1067
- };
1068
- }
1069
- normalizeCustomerDetailResponse(data) {
1070
- const period = (data.period ?? null);
1071
- return {
1072
- customerId: String(data.customerId ?? ''),
1073
- customerReference: String(data.customerReference ?? ''),
1074
- totalDeltas: Number(data.totalDeltas ?? 0),
1075
- firstDeltaAt: data.firstDeltaAt == null ? null : String(data.firstDeltaAt),
1076
- lastDeltaAt: data.lastDeltaAt == null ? null : String(data.lastDeltaAt),
1077
- customerPartition: String(data.customerPartition ?? ''),
1078
- computedBalance: Number(data.computedBalance ?? 0),
1079
- period: period
1080
- ? {
1081
- id: String(period.id ?? ''),
1082
- startDate: String(period.startDate ?? ''),
1083
- endDateExclusive: String(period.endDateExclusive ?? ''),
1084
- label: String(period.label ?? ''),
1085
- }
1086
- : undefined,
1087
- mostRecentActivePeriod: data.mostRecentActivePeriod == null
1088
- ? null
1089
- : String(data.mostRecentActivePeriod),
1090
- latestCheckpoint: data.latestCheckpoint == null ? null : String(data.latestCheckpoint),
1091
- privacyNote: String(data.privacyNote ?? ''),
1092
- recentActivity: data.recentActivity ??
1093
- {
1094
- items: [],
1095
- pagination: {
1096
- total: 0,
1097
- page: 1,
1098
- limit: 20,
1099
- totalPages: 1,
1100
- },
1101
- },
1102
- };
1103
- }
1104
- // -------------------------------------------------------------------------
1105
- // Invoice Proof (deprecated — use receipt with period)
1106
- // -------------------------------------------------------------------------
1107
- /**
1108
- * Generate an invoice-ready receipt for a customer's billing period.
1109
- *
1110
- * @deprecated Use `receipt(customerId, { period })` instead.
1111
- * @param customerId - The customer to generate the receipt for.
1112
- * @param options - Period selection and request overrides.
1113
- * @returns Receipt with proof root, verifyUrl, and verification data.
1114
- */
1115
- async invoiceProof(customerId, options) {
1116
- return this.receiptForPeriod(customerId, options);
1117
- }
1118
- }
1119
- exports.BalanceResource = BalanceResource;
1120
- //# sourceMappingURL=balance.js.map