@exactrows/mcp 0.0.0-stage → 0.2.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.
@@ -0,0 +1,3065 @@
1
+ // @generated standalone MCP bundle for @exactrows/mcp
2
+
3
+ // packages/exactrows-mcp/src/server.ts
4
+ import { createServer } from "node:http";
5
+
6
+ // src/lib/parser/fitid-v1.ts
7
+ var FITID_PREFIX = "EXR1";
8
+ var FITID_MAX_LENGTH = 32;
9
+ var SEQ_CAPACITY = 36 * 36 - 1;
10
+ var K = new Uint32Array([
11
+ 1116352408,
12
+ 1899447441,
13
+ 3049323471,
14
+ 3921009573,
15
+ 961987163,
16
+ 1508970993,
17
+ 2453635748,
18
+ 2870763221,
19
+ 3624381080,
20
+ 310598401,
21
+ 607225278,
22
+ 1426881987,
23
+ 1925078388,
24
+ 2162078206,
25
+ 2614888103,
26
+ 3248222580,
27
+ 3835390401,
28
+ 4022224774,
29
+ 264347078,
30
+ 604807628,
31
+ 770255983,
32
+ 1249150122,
33
+ 1555081692,
34
+ 1996064986,
35
+ 2554220882,
36
+ 2821834349,
37
+ 2952996808,
38
+ 3210313671,
39
+ 3336571891,
40
+ 3584528711,
41
+ 113926993,
42
+ 338241895,
43
+ 666307205,
44
+ 773529912,
45
+ 1294757372,
46
+ 1396182291,
47
+ 1695183700,
48
+ 1986661051,
49
+ 2177026350,
50
+ 2456956037,
51
+ 2730485921,
52
+ 2820302411,
53
+ 3259730800,
54
+ 3345764771,
55
+ 3516065817,
56
+ 3600352804,
57
+ 4094571909,
58
+ 275423344,
59
+ 430227734,
60
+ 506948616,
61
+ 659060556,
62
+ 883997877,
63
+ 958139571,
64
+ 1322822218,
65
+ 1537002063,
66
+ 1747873779,
67
+ 1955562222,
68
+ 2024104815,
69
+ 2227730452,
70
+ 2361852424,
71
+ 2428436474,
72
+ 2756734187,
73
+ 3204031479,
74
+ 3329325298
75
+ ]);
76
+ var W = new Uint32Array(64);
77
+ function sha256Bytes(input) {
78
+ const msg = typeof input === "string" ? new TextEncoder().encode(input) : input;
79
+ const len = msg.length;
80
+ const total = len + 9 + 63 >> 6 << 6;
81
+ const buf = new Uint8Array(total);
82
+ buf.set(msg);
83
+ buf[len] = 128;
84
+ const dv = new DataView(buf.buffer);
85
+ dv.setUint32(total - 8, Math.floor(len * 8 / 4294967296));
86
+ dv.setUint32(total - 4, len * 8 >>> 0);
87
+ let h0 = 1779033703, h1 = 3144134277, h2 = 1013904242, h3 = 2773480762;
88
+ let h4 = 1359893119, h5 = 2600822924, h6 = 528734635, h7 = 1541459225;
89
+ for (let off = 0; off < total; off += 64) {
90
+ for (let i = 0; i < 16; i++) W[i] = dv.getUint32(off + i * 4);
91
+ for (let i = 16; i < 64; i++) {
92
+ const a2 = W[i - 15], b2 = W[i - 2];
93
+ const s0 = (a2 >>> 7 | a2 << 25) ^ (a2 >>> 18 | a2 << 14) ^ a2 >>> 3;
94
+ const s1 = (b2 >>> 17 | b2 << 15) ^ (b2 >>> 19 | b2 << 13) ^ b2 >>> 10;
95
+ W[i] = W[i - 16] + s0 + W[i - 7] + s1 | 0;
96
+ }
97
+ let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7;
98
+ for (let i = 0; i < 64; i++) {
99
+ const S1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);
100
+ const ch = e & f ^ ~e & g;
101
+ const t1 = h + S1 + ch + K[i] + W[i] | 0;
102
+ const S0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10);
103
+ const maj = a & b ^ a & c ^ b & c;
104
+ const t2 = S0 + maj | 0;
105
+ h = g;
106
+ g = f;
107
+ f = e;
108
+ e = d + t1 | 0;
109
+ d = c;
110
+ c = b;
111
+ b = a;
112
+ a = t1 + t2 | 0;
113
+ }
114
+ h0 = h0 + a | 0;
115
+ h1 = h1 + b | 0;
116
+ h2 = h2 + c | 0;
117
+ h3 = h3 + d | 0;
118
+ h4 = h4 + e | 0;
119
+ h5 = h5 + f | 0;
120
+ h6 = h6 + g | 0;
121
+ h7 = h7 + h | 0;
122
+ }
123
+ const out = new Uint8Array(32);
124
+ const odv = new DataView(out.buffer);
125
+ [h0, h1, h2, h3, h4, h5, h6, h7].forEach((v, i) => odv.setUint32(i * 4, v >>> 0));
126
+ return out;
127
+ }
128
+ function sha256Hex(input) {
129
+ const d = sha256Bytes(input);
130
+ let s = "";
131
+ for (let i = 0; i < d.length; i++) s += d[i].toString(16).padStart(2, "0");
132
+ return s;
133
+ }
134
+ var CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
135
+ function crockford10(digest) {
136
+ let out = "";
137
+ let acc = 0;
138
+ let bits = 0;
139
+ let i = 0;
140
+ while (out.length < 10) {
141
+ if (bits < 5) {
142
+ acc = (acc << 8 | digest[i++]) & 65535;
143
+ bits += 8;
144
+ }
145
+ bits -= 5;
146
+ out += CROCKFORD[acc >> bits & 31];
147
+ }
148
+ return out;
149
+ }
150
+ var SEQ_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
151
+ function encodeSeq2(n) {
152
+ if (!Number.isInteger(n) || n < 1 || n > SEQ_CAPACITY) throw new RangeError(`SEQ out of range: ${n}`);
153
+ return SEQ_ALPHABET[Math.floor(n / 36)] + SEQ_ALPHABET[n % 36];
154
+ }
155
+ function normalizeAccountId(accountId) {
156
+ const alnum = String(accountId ?? "").normalize("NFKC").replace(/[^A-Za-z0-9]/g, "").toUpperCase();
157
+ return alnum.length > 4 ? alnum.slice(-Math.max(4, Math.min(alnum.length, 12))) : alnum;
158
+ }
159
+ function normalizeDescription(description) {
160
+ return String(description ?? "").normalize("NFKC").replace(/[\u200B-\u200D\u2060\uFEFF]/g, "").toUpperCase().replace(/\s+/g, " ").trim();
161
+ }
162
+ function normalizeDate(date) {
163
+ const s = String(date ?? "").trim();
164
+ const m = /^(\d{4})-?(\d{2})-?(\d{2})(?:$|[T\s])/.exec(s);
165
+ if (!m) throw new Error(`Invalid FITID date: ${date}`);
166
+ const y = +m[1], mo = +m[2], d = +m[3];
167
+ const dim = [31, y % 4 === 0 && y % 100 !== 0 || y % 400 === 0 ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
168
+ if (mo < 1 || mo > 12 || d < 1 || d > dim[mo - 1]) throw new Error(`Invalid FITID date: ${date}`);
169
+ return `${m[1]}-${m[2]}-${m[3]}`;
170
+ }
171
+ function canonicalPayload(row) {
172
+ if (!Number.isSafeInteger(row.amountCents)) throw new Error("amountCents must be a safe integer");
173
+ return [
174
+ normalizeAccountId(row.accountId),
175
+ normalizeDate(row.date),
176
+ String(row.amountCents === 0 ? 0 : row.amountCents),
177
+ normalizeDescription(row.description)
178
+ ].join("|");
179
+ }
180
+ function idFor(payload, n, dateCompact) {
181
+ const bucket = Math.floor((n - 1) / SEQ_CAPACITY);
182
+ const seq = (n - 1) % SEQ_CAPACITY + 1;
183
+ const hash = crockford10(sha256Bytes(bucket === 0 ? payload : `${payload}|~${bucket}`));
184
+ return `${FITID_PREFIX}-${dateCompact}-${hash}-${encodeSeq2(seq)}`;
185
+ }
186
+ function isValidFitid(fitid) {
187
+ return typeof fitid === "string" && fitid.length > 0 && fitid.length <= FITID_MAX_LENGTH && /^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(fitid);
188
+ }
189
+ function assignFitids(rows, opts = {}) {
190
+ const used = new Set(opts.reserved ?? []);
191
+ const results = new Array(rows.length);
192
+ const preserved = new Array(rows.length).fill(false);
193
+ if (!opts.regenerate) {
194
+ for (let i = 0; i < rows.length; i++) {
195
+ const f = rows[i].fitid;
196
+ if (isValidFitid(f) && !used.has(f)) {
197
+ used.add(f);
198
+ preserved[i] = true;
199
+ }
200
+ }
201
+ }
202
+ const counters = /* @__PURE__ */ new Map();
203
+ for (let i = 0; i < rows.length; i++) {
204
+ if (preserved[i]) {
205
+ results[i] = { fitid: rows[i].fitid, fitid_strategy: "preserved" };
206
+ continue;
207
+ }
208
+ const payload = canonicalPayload(rows[i]);
209
+ const dateCompact = payload.split("|")[1].replace(/-/g, "");
210
+ let n = counters.get(payload) ?? 0;
211
+ let id;
212
+ do {
213
+ n++;
214
+ id = idFor(payload, n, dateCompact);
215
+ } while (used.has(id));
216
+ counters.set(payload, n);
217
+ used.add(id);
218
+ results[i] = { fitid: id, fitid_strategy: "generated" };
219
+ }
220
+ return results;
221
+ }
222
+
223
+ // src/api-worker/receipts.ts
224
+ function canonicalJson(value) {
225
+ if (value === null) return "null";
226
+ switch (typeof value) {
227
+ case "string":
228
+ return JSON.stringify(value);
229
+ case "number":
230
+ if (!Number.isFinite(value)) throw new TypeError("Non-finite number in canonical JSON");
231
+ return JSON.stringify(value === 0 ? 0 : value);
232
+ case "boolean":
233
+ return value ? "true" : "false";
234
+ case "object": {
235
+ if (Array.isArray(value)) return `[${value.map((v) => v === void 0 ? "null" : canonicalJson(v)).join(",")}]`;
236
+ const obj2 = value;
237
+ const parts = [];
238
+ for (const k of Object.keys(obj2).sort()) {
239
+ if (obj2[k] === void 0) continue;
240
+ parts.push(`${JSON.stringify(k)}:${canonicalJson(obj2[k])}`);
241
+ }
242
+ return `{${parts.join(",")}}`;
243
+ }
244
+ default:
245
+ throw new TypeError(`Unsupported type in canonical JSON: ${typeof value}`);
246
+ }
247
+ }
248
+ function digestSha256(value) {
249
+ if (typeof value === "string" || value instanceof Uint8Array) return sha256Hex(value);
250
+ return sha256Hex(canonicalJson(value));
251
+ }
252
+ function bytesToB64(bytes) {
253
+ let s = "";
254
+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
255
+ return btoa(s);
256
+ }
257
+ function b64ToBytes(b64) {
258
+ const norm = b64.replace(/-/g, "+").replace(/_/g, "/").replace(/\s+/g, "");
259
+ const s = atob(norm + "=".repeat((4 - norm.length % 4) % 4));
260
+ const out = new Uint8Array(s.length);
261
+ for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
262
+ return out;
263
+ }
264
+ function toBase64Url(bytes) {
265
+ return bytesToB64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
266
+ }
267
+ function fromBase64Url(s) {
268
+ return b64ToBytes(s);
269
+ }
270
+ var PKCS8_ED25519_PREFIX = new Uint8Array([48, 46, 2, 1, 0, 48, 5, 6, 3, 43, 101, 112, 4, 34, 4, 32]);
271
+ var SPKI_ED25519_PREFIX = new Uint8Array([48, 42, 48, 5, 6, 3, 43, 101, 112, 3, 33, 0]);
272
+ function concat(a, b) {
273
+ const o = new Uint8Array(a.length + b.length);
274
+ o.set(a);
275
+ o.set(b, a.length);
276
+ return o;
277
+ }
278
+ function stripPem(s) {
279
+ return s.replace(/-----(BEGIN|END)[^-]+-----/g, "").replace(/\s+/g, "");
280
+ }
281
+ var ED = { name: "Ed25519" };
282
+ async function importPrivate(raw) {
283
+ const t = raw.trim();
284
+ if (t.startsWith("{")) {
285
+ const jwk = JSON.parse(t);
286
+ return crypto.subtle.importKey("jwk", { ...jwk, key_ops: ["sign"], ext: true }, ED, true, ["sign"]);
287
+ }
288
+ const bytes = b64ToBytes(stripPem(t));
289
+ const pkcs8 = bytes.length === 32 ? concat(PKCS8_ED25519_PREFIX, bytes) : bytes;
290
+ return crypto.subtle.importKey("pkcs8", pkcs8, ED, true, ["sign"]);
291
+ }
292
+ async function importPublic(raw) {
293
+ const t = raw.trim();
294
+ if (t.startsWith("{")) {
295
+ const jwk = JSON.parse(t);
296
+ const { d: _d, ...pub } = jwk;
297
+ return crypto.subtle.importKey("jwk", { ...pub, key_ops: ["verify"], ext: true }, ED, true, ["verify"]);
298
+ }
299
+ const bytes = b64ToBytes(stripPem(t));
300
+ const spki = bytes.length === 32 ? concat(SPKI_ED25519_PREFIX, bytes) : bytes;
301
+ return crypto.subtle.importKey("spki", spki, ED, true, ["verify"]);
302
+ }
303
+ async function publicFromPrivate(priv) {
304
+ const jwk = await crypto.subtle.exportKey("jwk", priv);
305
+ return crypto.subtle.importKey("jwk", { kty: jwk.kty, crv: jwk.crv, x: jwk.x, ext: true }, ED, true, ["verify"]);
306
+ }
307
+ var keyCache = /* @__PURE__ */ new Map();
308
+ var DEV_SEED = sha256Bytes32("exactrows-receipt-v1-dev-ephemeral-key");
309
+ function sha256Bytes32(s) {
310
+ const hex = sha256Hex(s);
311
+ const out = new Uint8Array(32);
312
+ for (let i = 0; i < 32; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
313
+ return out;
314
+ }
315
+ function loadReceiptKeys(env = {}) {
316
+ const priv = env.EXACTROWS_RECEIPT_ED25519_PRIVATE_KEY?.trim() || "";
317
+ const pub = env.EXACTROWS_RECEIPT_ED25519_PUBLIC_KEY?.trim() || "";
318
+ const cacheKey = `${priv}\0${pub}`;
319
+ let p = keyCache.get(cacheKey);
320
+ if (!p) {
321
+ p = (async () => {
322
+ if (!priv) {
323
+ const privateKey2 = await importPrivate(bytesToB64(DEV_SEED));
324
+ return { privateKey: privateKey2, publicKey: await publicFromPrivate(privateKey2), ephemeral: true };
325
+ }
326
+ const privateKey = await importPrivate(priv);
327
+ const publicKey = pub ? await importPublic(pub) : await publicFromPrivate(privateKey);
328
+ return { privateKey, publicKey, ephemeral: false };
329
+ })();
330
+ p.catch(() => keyCache.delete(cacheKey));
331
+ keyCache.set(cacheKey, p);
332
+ }
333
+ return p;
334
+ }
335
+ async function signReceiptPayload(unsigned, env = {}) {
336
+ const { privateKey } = await loadReceiptKeys(env);
337
+ const sig = await crypto.subtle.sign(ED, privateKey, new TextEncoder().encode(canonicalJson(unsigned)));
338
+ return toBase64Url(new Uint8Array(sig));
339
+ }
340
+ async function verifyReceipt(receipt, env = {}) {
341
+ try {
342
+ const { ed25519Signature, ...unsigned } = receipt;
343
+ if (typeof ed25519Signature !== "string" || !ed25519Signature) return false;
344
+ const { publicKey } = await loadReceiptKeys(env);
345
+ return await crypto.subtle.verify(
346
+ ED,
347
+ publicKey,
348
+ fromBase64Url(ed25519Signature),
349
+ new TextEncoder().encode(canonicalJson(unsigned))
350
+ );
351
+ } catch {
352
+ return false;
353
+ }
354
+ }
355
+ function newReceiptId() {
356
+ const bytes = crypto.getRandomValues(new Uint8Array(24));
357
+ const alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
358
+ let s = "rcpt_";
359
+ for (let i = 0; i < bytes.length; i++) s += alpha[bytes[i] % alpha.length];
360
+ return s;
361
+ }
362
+ var DEFAULT_ENGINE_VERSION = "3.1.0";
363
+ var EMPTY_MATH = {
364
+ currency: "CAD",
365
+ openingCents: 0,
366
+ creditsCents: 0,
367
+ debitsCents: 0,
368
+ closingCents: 0,
369
+ deltaCents: 0,
370
+ balanced: true,
371
+ transactionCount: 0
372
+ };
373
+ async function buildReceipt(input, env = {}) {
374
+ const unsigned = {
375
+ receiptVersion: "ExactRows-Receipt-v1",
376
+ receiptId: input.receiptId ?? newReceiptId(),
377
+ timestampUtc: input.timestampUtc ?? (/* @__PURE__ */ new Date()).toISOString(),
378
+ engineVersion: input.engineVersion ?? DEFAULT_ENGINE_VERSION,
379
+ endpoint: input.endpoint,
380
+ clientId: input.clientId ?? null,
381
+ issuerDisplayName: input.issuerDisplayName ?? null,
382
+ retentionMode: input.retentionMode ?? "none",
383
+ inputSha256: input.inputSha256 ?? digestSha256(input.input ?? ""),
384
+ outputSha256: input.outputSha256 ?? digestSha256(input.output ?? ""),
385
+ reconciliationMath: input.reconciliationMath ?? EMPTY_MATH,
386
+ repairsApplied: input.repairsApplied ?? [],
387
+ ...input.rowConfidenceSummary !== void 0 ? { rowConfidenceSummary: input.rowConfidenceSummary } : {}
388
+ };
389
+ const ed25519Signature = await signReceiptPayload(unsigned, env);
390
+ return { ...unsigned, ed25519Signature };
391
+ }
392
+
393
+ // src/data/banks.ts
394
+ var PRIORITY_BANKS = [
395
+ {
396
+ slug: "rbc",
397
+ name: "RBC Royal Bank",
398
+ shortName: "RBC",
399
+ region: "CA",
400
+ category: "Big-6",
401
+ intuitBid: "00003",
402
+ supportsChecking: true,
403
+ supportsCreditCard: true,
404
+ notes: "Chequing, Business Deposit, and RBC Avion/Visa statements.",
405
+ statementQuirks: "RBC statements often wrap e-Transfer and cheque memos across 2\u20133 lines and roll statement years across Dec\u2013Jan boundaries. ExactRows normalizes multi-line descriptions and detects year transitions automatically."
406
+ },
407
+ {
408
+ slug: "td",
409
+ name: "TD Canada Trust",
410
+ shortName: "TD",
411
+ region: "CA",
412
+ category: "Big-6",
413
+ intuitBid: "00004",
414
+ supportsChecking: true,
415
+ supportsCreditCard: true,
416
+ notes: "Everyday Chequing, Business Chequing, and TD Aeroplan/Cash Back Visa.",
417
+ statementQuirks: "TD chequing PDFs use separate Withdrawal and Deposit columns, while TD Visa statements invert charge signs relative to chequing. Use the 1-click Flip Signs toggle if your credit-card import expects negative charges."
418
+ },
419
+ {
420
+ slug: "bmo",
421
+ name: "BMO Bank of Montreal",
422
+ shortName: "BMO",
423
+ region: "CA",
424
+ category: "Big-6",
425
+ intuitBid: "00001",
426
+ supportsChecking: true,
427
+ supportsCreditCard: true,
428
+ notes: "Personal/Business Banking and BMO Mastercard PDFs.",
429
+ statementQuirks: "BMO Mastercard PDFs display both Transaction Date and Posting Date alongside bilingual French/English headers. ExactRows anchors posting dates and strips trailing legal disclosure pages automatically."
430
+ },
431
+ {
432
+ slug: "scotiabank",
433
+ name: "Scotiabank",
434
+ shortName: "Scotiabank",
435
+ region: "CA",
436
+ category: "Big-6",
437
+ intuitBid: "00002",
438
+ supportsChecking: true,
439
+ supportsCreditCard: true,
440
+ notes: "Chequing, Momentum Visa, and Scene+ card statements.",
441
+ statementQuirks: "Scotiabank Momentum and Scene+ PDFs place summary reward boxes near transaction rows. ExactRows filters summary/interest boilerplate and reconciles Opening + Credits \u2212 Debits = Closing in exact cents."
442
+ },
443
+ {
444
+ slug: "cibc",
445
+ name: "CIBC",
446
+ shortName: "CIBC",
447
+ region: "CA",
448
+ category: "Big-6",
449
+ intuitBid: "00010",
450
+ supportsChecking: true,
451
+ supportsCreditCard: true,
452
+ notes: "Smart Account, Business Operating, and CIBC Dividend/Aventura Visa.",
453
+ statementQuirks: "CIBC Business Operating and Dividend Visa PDFs frequently append 2\u20134 pages of CDIC and cardholder notices. ExactRows skips those trailing disclosure pages automatically before counting credits or rows."
454
+ },
455
+ {
456
+ slug: "national-bank",
457
+ name: "National Bank of Canada",
458
+ shortName: "National Bank",
459
+ region: "CA",
460
+ category: "Big-6",
461
+ intuitBid: "00006",
462
+ supportsChecking: true,
463
+ supportsCreditCard: true,
464
+ notes: "Personal, Business, and World Elite Mastercard statements.",
465
+ statementQuirks: "National Bank (Banque Nationale) statements appear in both English and French date formats with space-separated thousand delimiters. ExactRows parses both layouts deterministically in browser WASM."
466
+ },
467
+ {
468
+ slug: "desjardins",
469
+ name: "Desjardins",
470
+ shortName: "Desjardins",
471
+ region: "CA",
472
+ category: "Digital / Credit Union",
473
+ intuitBid: "00815",
474
+ supportsChecking: true,
475
+ supportsCreditCard: true,
476
+ notes: "French & English Acc\xE8sD chequing and Visa Desjardins PDFs.",
477
+ statementQuirks: "Acc\xE8sD and Visa Desjardins PDFs commonly use French month abbreviations (janv., f\xE9vr., d\xE9c.) and comma decimals (1 234,56 $). ExactRows normalizes French dates and decimal commas to standard accounting numbers."
478
+ },
479
+ {
480
+ slug: "tangerine",
481
+ name: "Tangerine Bank",
482
+ shortName: "Tangerine",
483
+ region: "CA",
484
+ category: "Digital / Credit Union",
485
+ intuitBid: "00614",
486
+ supportsChecking: true,
487
+ supportsCreditCard: true,
488
+ notes: "Chequing, Savings, and Money-Back Mastercard statements.",
489
+ statementQuirks: "Tangerine Savings and Money-Back Mastercard PDFs group interest earned and cash-back rewards into summary headers. ExactRows captures interest/reward line items and checks running balances per row."
490
+ },
491
+ {
492
+ slug: "eq-bank",
493
+ name: "EQ Bank",
494
+ shortName: "EQ Bank",
495
+ region: "CA",
496
+ category: "Digital / Credit Union",
497
+ intuitBid: "00623",
498
+ supportsChecking: true,
499
+ supportsCreditCard: false,
500
+ notes: "Personal, Joint, and EQ Bank Business/Notice Savings PDFs.",
501
+ statementQuirks: "EQ Bank Personal and Business Savings statements omit cheque numbers and carry multi-line Interac e-Transfer recipient strings. ExactRows extracts clean payee names and lets you refine rules per client profile."
502
+ },
503
+ {
504
+ slug: "simplii",
505
+ name: "Simplii Financial",
506
+ shortName: "Simplii",
507
+ region: "CA",
508
+ category: "Digital / Credit Union",
509
+ intuitBid: "00615",
510
+ supportsChecking: true,
511
+ supportsCreditCard: true,
512
+ notes: "No-Fee Chequing and Cash Back Visa statements.",
513
+ statementQuirks: "Simplii Financial PDFs share CIBC-style multi-column withdrawal/deposit tables and trailing CDIC pages. ExactRows ignores disclosure pages and verifies Opening and Closing totals to the cent."
514
+ },
515
+ {
516
+ slug: "coast-capital",
517
+ name: "Coast Capital Savings",
518
+ shortName: "Coast Capital",
519
+ region: "CA",
520
+ category: "Digital / Credit Union",
521
+ intuitBid: "00809",
522
+ supportsChecking: true,
523
+ supportsCreditCard: true,
524
+ notes: "BC Credit Union personal and small business statements.",
525
+ statementQuirks: "Coast Capital member statements often bundle multiple sub-accounts (chequing, savings, equity shares) inside one PDF. ExactRows isolates transaction tables cleanly and surfaces any balance discrepancy immediately."
526
+ },
527
+ {
528
+ slug: "amex-ca",
529
+ name: "American Express Canada",
530
+ shortName: "Amex Canada",
531
+ region: "CA",
532
+ category: "Digital / Credit Union",
533
+ intuitBid: "03101",
534
+ supportsChecking: false,
535
+ supportsCreditCard: true,
536
+ notes: "Cobalt, Platinum, Business Edge, and Aeroplan Reserve PDFs.",
537
+ statementQuirks: "Amex Canada statements append foreign-currency conversion lines under international charges and show payments as credits. ExactRows keeps currency conversion memos attached to the parent charge."
538
+ },
539
+ {
540
+ slug: "chase",
541
+ name: "Chase",
542
+ shortName: "Chase",
543
+ region: "US",
544
+ category: "US Major",
545
+ intuitBid: "10898",
546
+ supportsChecking: true,
547
+ supportsCreditCard: true,
548
+ notes: "Total Checking, Ink Business, and Sapphire statements.",
549
+ statementQuirks: "Chase Total Checking and Ink Business PDFs separate Deposits/Additions, ATM/Debit Withdrawals, and Electronic Withdrawals into distinct sections. ExactRows merges all sections chronologically and generates deterministic FITID keys."
550
+ },
551
+ {
552
+ slug: "bank-of-america",
553
+ name: "Bank of America",
554
+ shortName: "BofA",
555
+ region: "US",
556
+ category: "US Major",
557
+ intuitBid: "05959",
558
+ supportsChecking: true,
559
+ supportsCreditCard: true,
560
+ notes: "Advantage Banking, Business Fundamentals, and Customized Cash.",
561
+ statementQuirks: "Bank of America statements place Daily Ledger Balances and Service Fee summaries alongside transaction sections. ExactRows excludes ledger balance tables so only real posted transactions export."
562
+ },
563
+ {
564
+ slug: "wells-fargo",
565
+ name: "Wells Fargo",
566
+ shortName: "Wells Fargo",
567
+ region: "US",
568
+ category: "US Major",
569
+ intuitBid: "03000",
570
+ supportsChecking: true,
571
+ supportsCreditCard: true,
572
+ notes: "Everyday Checking, Initiate Business, and Active Cash PDFs.",
573
+ statementQuirks: "Wells Fargo Initiate Business PDFs include monthly service-fee waiver trackers and multi-line ACH originators. ExactRows consolidates ACH descriptions and validates Opening + Credits \u2212 Debits = Closing."
574
+ },
575
+ {
576
+ slug: "citi",
577
+ name: "Citibank",
578
+ shortName: "Citi",
579
+ region: "US",
580
+ category: "US Major",
581
+ intuitBid: "24909",
582
+ supportsChecking: true,
583
+ supportsCreditCard: true,
584
+ notes: "Citi Checking and Double Cash / Custom Cash statements.",
585
+ statementQuirks: "Citibank credit card PDFs print Sale Date and Post Date side-by-side plus interest-charge calculation tables. ExactRows filters interest-rate disclosure grids and preserves exact transaction signs."
586
+ },
587
+ {
588
+ slug: "capital-one",
589
+ name: "Capital One",
590
+ shortName: "Capital One",
591
+ region: "US",
592
+ category: "US Major",
593
+ intuitBid: "10008",
594
+ supportsChecking: true,
595
+ supportsCreditCard: true,
596
+ notes: "360 Checking, Spark Business, and Venture card statements.",
597
+ statementQuirks: "Capital One Spark Business PDFs group spend by employee cardholder sub-sections. ExactRows extracts every cardholder section into one chronological stream verified against the statement total."
598
+ },
599
+ {
600
+ slug: "amex-us",
601
+ name: "American Express US",
602
+ shortName: "Amex US",
603
+ region: "US",
604
+ category: "US Major",
605
+ intuitBid: "03101",
606
+ supportsChecking: true,
607
+ supportsCreditCard: true,
608
+ notes: "Business Checking, Blue Business Plus, and Gold/Platinum PDFs.",
609
+ statementQuirks: "Amex US statements split Pay Over Time vs. New Charges summaries across multiple pages. ExactRows aggregates every posted charge and credit into one balanced export with 1-click sign-flip support."
610
+ },
611
+ {
612
+ slug: "stripe",
613
+ name: "Stripe Balance & Payouts",
614
+ shortName: "Stripe",
615
+ region: "Global",
616
+ category: "Payment Platform",
617
+ intuitBid: "99001",
618
+ supportsChecking: true,
619
+ supportsCreditCard: false,
620
+ notes: "Monthly Stripe payout & balance reconciliation PDFs.",
621
+ statementQuirks: "Stripe Balance Summary PDFs mix gross volume, processing fees, refunds, and bank payouts. ExactRows isolates settled balance movements cleanly for QuickBooks clearing-account reconciliation."
622
+ },
623
+ {
624
+ slug: "paypal",
625
+ name: "PayPal Statements",
626
+ shortName: "PayPal",
627
+ region: "Global",
628
+ category: "Payment Platform",
629
+ intuitBid: "99002",
630
+ supportsChecking: true,
631
+ supportsCreditCard: false,
632
+ notes: "Monthly PayPal Business & Personal activity PDFs.",
633
+ statementQuirks: "PayPal monthly PDFs report Gross, Fee, and Net columns plus multi-currency holds. ExactRows parses activity rows cleanly and warns if currency-conversion rows create a net-balance offset."
634
+ }
635
+ ];
636
+
637
+ // src/lib/parser/reconcile.ts
638
+ var DATE_TOKEN_RE_SRC = "(?:\\b\\d{4}[-/]\\d{2}[-/]\\d{2}\\b|\\b(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec|janv|fev|fevr|mars|avr|mai|juin|juil|juill|aou|aout|sept|oct|nov|dec|ene|abr|ago|set|dic)[a-z.]*\\s*\\d{1,2}\\b|\\b\\d{1,2}(?:er)?(?:\\s+de\\s+|[\\s-]+)(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec|janv|fev|fevr|mars|avr|mai|juin|juil|juill|aou|aout|sept|ene|abr|ago|set|dic)[a-z.]*(?:(?:\\s+de\\s+|[\\s-]+)\\d{2,4})?\\b|\\b\\d{1,2}[/-]\\d{1,2}(?:[/-]\\d{2,4})?\\b)";
639
+ var MONEY_TOKEN_RE_SRC = "(?:[-\\u2013\\u2014\\u2212]?\\$?\\s*(?:\\d{1,3}(?:[ \\u00a0\\u202f,.]\\d{3})*|\\d+)?(?:[.,]\\d{2}|[.,]\\d(?=\\s*(?:CR|DR|[CD]\\b)))(?:\\s*\\$|\\s*(?:CR|DR|CAD|USD|MXN|[-\\u2013\\u2014\\u2212])|\\s+[CD](?=\\s|$))?)";
640
+ var DATE_OR_MONEY_LINE_RE = new RegExp(
641
+ `(?:${DATE_TOKEN_RE_SRC}.*?${MONEY_TOKEN_RE_SRC}|${MONEY_TOKEN_RE_SRC}.*?${DATE_TOKEN_RE_SRC})`,
642
+ "i"
643
+ );
644
+ function toCents(amount) {
645
+ if (!Number.isFinite(amount)) {
646
+ throw new TypeError(`Invalid currency amount: ${amount}`);
647
+ }
648
+ return Math.round(amount * 100);
649
+ }
650
+ function formatCents(cents) {
651
+ return (cents / 100).toFixed(2);
652
+ }
653
+ function flipTransactionSigns(transactions) {
654
+ return transactions.map((tx) => ({
655
+ ...tx,
656
+ amount: tx.amount === 0 ? 0 : -tx.amount
657
+ }));
658
+ }
659
+ function reconcileStatement(transactions, openingBalance, closingBalance) {
660
+ const openingCents = toCents(openingBalance);
661
+ const closingCents = toCents(closingBalance);
662
+ let totalCreditsCents = 0;
663
+ let totalDebitsCents = 0;
664
+ let runningCents = openingCents;
665
+ const mismatchedRowIndices = [];
666
+ for (let index = 0; index < transactions.length; index++) {
667
+ const tx = transactions[index];
668
+ const amountCents = toCents(tx.amount);
669
+ if (amountCents >= 0) {
670
+ totalCreditsCents += amountCents;
671
+ } else {
672
+ totalDebitsCents += Math.abs(amountCents);
673
+ }
674
+ runningCents += amountCents;
675
+ if (tx.balance !== void 0) {
676
+ const rowBalanceCents = toCents(tx.balance);
677
+ if (rowBalanceCents !== runningCents) {
678
+ mismatchedRowIndices.push(index);
679
+ runningCents = rowBalanceCents;
680
+ }
681
+ }
682
+ }
683
+ const expectedClosingCents = openingCents + totalCreditsCents - totalDebitsCents;
684
+ const discrepancyCents = closingCents - expectedClosingCents;
685
+ return {
686
+ isBalanced: discrepancyCents === 0 && mismatchedRowIndices.length === 0,
687
+ openingCents,
688
+ closingCents,
689
+ expectedClosingCents,
690
+ discrepancyCents,
691
+ totalCreditsCents,
692
+ totalDebitsCents,
693
+ transactionCount: transactions.length,
694
+ mismatchedRowIndices
695
+ };
696
+ }
697
+
698
+ // src/lib/parser/qbo-validator.ts
699
+ var MAX_QBO_INPUT_BYTES = 15 * 1024 * 1024;
700
+ var UNESCAPED_AMP_RE = /&(?!(?:amp|lt|gt|quot|apos|#\d+|#x[0-9a-fA-F]+);)/;
701
+ var GLOBAL_UNESCAPED_AMP_RE = /&(?!(?:amp|lt|gt|quot|apos|#\d+|#x[0-9a-fA-F]+);)/g;
702
+ function extractTagValue(line, tagName) {
703
+ const trimmed = line.trim();
704
+ const prefix = `<${tagName}>`;
705
+ if (!trimmed.toUpperCase().startsWith(prefix.toUpperCase())) return null;
706
+ let value = trimmed.slice(prefix.length);
707
+ const closeTag = `</${tagName}>`;
708
+ const closeIdx = value.toUpperCase().indexOf(closeTag.toUpperCase());
709
+ if (closeIdx >= 0) {
710
+ value = value.slice(0, closeIdx);
711
+ }
712
+ return value;
713
+ }
714
+ function isValidCalendarYmd(yearStr, monthStr, dayStr) {
715
+ const year = Number(yearStr);
716
+ const month = Number(monthStr);
717
+ const day = Number(dayStr);
718
+ if (!Number.isInteger(year) || year < 1970 || year > 2100) return false;
719
+ if (!Number.isInteger(month) || month < 1 || month > 12) return false;
720
+ if (!Number.isInteger(day) || day < 1 || day > 31) return false;
721
+ const dt = new Date(Date.UTC(year, month - 1, day));
722
+ return dt.getUTCFullYear() === year && dt.getUTCMonth() === month - 1 && dt.getUTCDate() === day;
723
+ }
724
+ function truncateEntitySafe(value, maxLen) {
725
+ if (value.length <= maxLen) return value;
726
+ let cut = value.slice(0, maxLen);
727
+ const lastAmp = cut.lastIndexOf("&");
728
+ if (lastAmp >= 0 && !cut.slice(lastAmp).includes(";")) {
729
+ cut = cut.slice(0, lastAmp);
730
+ }
731
+ return cut.trimEnd();
732
+ }
733
+ function validateQboOrOfx(raw, filename) {
734
+ const issues = [];
735
+ const pushIssue = (severity, code, message, line) => {
736
+ issues.push({
737
+ id: `${code}-${issues.length + 1}`,
738
+ severity,
739
+ code,
740
+ line,
741
+ message
742
+ });
743
+ };
744
+ const byteLen = new TextEncoder().encode(raw).byteLength;
745
+ if (byteLen > MAX_QBO_INPUT_BYTES) {
746
+ pushIssue("error", "TOO_LARGE", `File exceeds 15 MiB limit (${byteLen} bytes).`);
747
+ return {
748
+ isValid: false,
749
+ format: "unknown",
750
+ currency: null,
751
+ intuitBid: null,
752
+ recognizedBank: null,
753
+ transactionCount: 0,
754
+ creditsCents: 0,
755
+ debitsCents: 0,
756
+ netCents: 0,
757
+ ledgerBalance: null,
758
+ dateStart: null,
759
+ dateEnd: null,
760
+ issues
761
+ };
762
+ }
763
+ const normalized = raw.replace(/\r\n?/g, "\n");
764
+ if (!normalized.trim()) {
765
+ pushIssue("error", "EMPTY", "Input QBO/OFX content is empty.");
766
+ return {
767
+ isValid: false,
768
+ format: "unknown",
769
+ currency: null,
770
+ intuitBid: null,
771
+ recognizedBank: null,
772
+ transactionCount: 0,
773
+ creditsCents: 0,
774
+ debitsCents: 0,
775
+ netCents: 0,
776
+ ledgerBalance: null,
777
+ dateStart: null,
778
+ dateEnd: null,
779
+ issues
780
+ };
781
+ }
782
+ const isXmlOfx = /<\?OFX\b/i.test(normalized) || /<\?xml\b/i.test(normalized);
783
+ const hasSgmlHeader = /^OFXHEADER:\s*100/m.test(normalized) && /VERSION:\s*10[23]/m.test(normalized);
784
+ if (!isXmlOfx && !hasSgmlHeader) {
785
+ pushIssue(
786
+ "error",
787
+ "HEADER_MISSING",
788
+ "Missing OFXHEADER:100 / VERSION:102 SGML preamble or <?OFX?> XML header required by QuickBooks.",
789
+ 1
790
+ );
791
+ }
792
+ if (!/<OFX>/i.test(normalized) || !/<\/OFX>/i.test(normalized)) {
793
+ pushIssue("error", "OFX_ENVELOPE", "Missing opening <OFX> or closing </OFX> root tag.");
794
+ }
795
+ if (!/<BANKTRANLIST>/i.test(normalized)) {
796
+ pushIssue("warning", "OFX_ENVELOPE", "Missing <BANKTRANLIST> transaction list container.");
797
+ }
798
+ if (!/<LEDGERBAL>/i.test(normalized)) {
799
+ pushIssue("warning", "OFX_ENVELOPE", "Missing <LEDGERBAL> ledger balance footer block.");
800
+ }
801
+ let currency = null;
802
+ let intuitBid = null;
803
+ let ledgerBalance = null;
804
+ let transactionCount = 0;
805
+ let creditsCents = 0;
806
+ let debitsCents = 0;
807
+ let minDate = null;
808
+ let maxDate = null;
809
+ const seenFitids = /* @__PURE__ */ new Map();
810
+ const lines = normalized.split("\n");
811
+ for (let idx = 0; idx < lines.length; idx += 1) {
812
+ const lineNum = idx + 1;
813
+ const segments = lines[idx].split(/(?=<\/?[A-Z][A-Z0-9._]*>)/i);
814
+ for (const line of segments) {
815
+ if (!line.trim()) continue;
816
+ const upper = line.trim().toUpperCase();
817
+ if (upper.startsWith("<STMTTRN>")) {
818
+ transactionCount += 1;
819
+ continue;
820
+ }
821
+ const curVal = extractTagValue(line, "CURDEF");
822
+ if (curVal !== null) currency = curVal.trim().toUpperCase();
823
+ const bidVal = extractTagValue(line, "INTU.BID");
824
+ if (bidVal !== null) intuitBid = bidVal.trim();
825
+ const balVal = extractTagValue(line, "BALAMT");
826
+ if (balVal !== null) {
827
+ ledgerBalance = balVal.trim();
828
+ if (!/^-?\d+(?:\.\d+)?$/.test(ledgerBalance)) {
829
+ pushIssue("error", "BAD_AMOUNT", `Invalid <BALAMT> "${ledgerBalance}".`, lineNum);
830
+ }
831
+ }
832
+ const nameVal = extractTagValue(line, "NAME");
833
+ if (nameVal !== null) {
834
+ if (UNESCAPED_AMP_RE.test(nameVal) || /[<>]/.test(nameVal)) {
835
+ pushIssue(
836
+ "error",
837
+ "OL-222",
838
+ `Unescaped XML/SGML character (&, <, or >) in <NAME> triggers QuickBooks Error OL-222 ("${nameVal.trim()}").`,
839
+ lineNum
840
+ );
841
+ }
842
+ if (nameVal.trim().length > 32) {
843
+ pushIssue(
844
+ "warning",
845
+ "LONG_NAME",
846
+ `<NAME> exceeds QuickBooks Web Connect 32-character limit (${nameVal.trim().length} chars).`,
847
+ lineNum
848
+ );
849
+ }
850
+ }
851
+ const memoVal = extractTagValue(line, "MEMO");
852
+ if (memoVal !== null && (UNESCAPED_AMP_RE.test(memoVal) || /[<>]/.test(memoVal))) {
853
+ pushIssue(
854
+ "error",
855
+ "OL-222",
856
+ `Unescaped XML/SGML character (&, <, or >) in <MEMO> triggers QuickBooks Error OL-222.`,
857
+ lineNum
858
+ );
859
+ }
860
+ const fitidVal = extractTagValue(line, "FITID");
861
+ if (fitidVal !== null) {
862
+ const cleanFitid = fitidVal.trim();
863
+ if (!cleanFitid) {
864
+ pushIssue("error", "DUP_FITID", "Empty <FITID> tag found.", lineNum);
865
+ } else if (seenFitids.has(cleanFitid)) {
866
+ pushIssue(
867
+ "error",
868
+ "DUP_FITID",
869
+ `Duplicate <FITID> "${cleanFitid}" (first seen at line ${seenFitids.get(cleanFitid)}); QuickBooks skips duplicate FITIDs.`,
870
+ lineNum
871
+ );
872
+ } else {
873
+ seenFitids.set(cleanFitid, lineNum);
874
+ }
875
+ }
876
+ for (const dateTag of ["DTSTART", "DTEND", "DTASOF"]) {
877
+ const dVal = extractTagValue(line, dateTag);
878
+ if (dVal !== null) {
879
+ const m = dVal.trim().match(/^(\d{4})(\d{2})(\d{2})/);
880
+ if (!m || !isValidCalendarYmd(m[1], m[2], m[3])) {
881
+ pushIssue("error", "BAD_DATE", `Invalid calendar date in <${dateTag}> "${dVal.trim()}".`, lineNum);
882
+ }
883
+ }
884
+ }
885
+ const dtPostedVal = extractTagValue(line, "DTPOSTED");
886
+ if (dtPostedVal !== null) {
887
+ const m = dtPostedVal.trim().match(/^(\d{4})(\d{2})(\d{2})/);
888
+ if (!m || !isValidCalendarYmd(m[1], m[2], m[3])) {
889
+ pushIssue("error", "BAD_DATE", `Invalid or malformed <DTPOSTED> "${dtPostedVal.trim()}".`, lineNum);
890
+ } else {
891
+ const iso = `${m[1]}-${m[2]}-${m[3]}`;
892
+ if (!minDate || iso < minDate) minDate = iso;
893
+ if (!maxDate || iso > maxDate) maxDate = iso;
894
+ }
895
+ }
896
+ const trnAmtVal = extractTagValue(line, "TRNAMT");
897
+ if (trnAmtVal !== null) {
898
+ const cleanedAmt = trnAmtVal.trim();
899
+ if (!/^-?\d+(?:\.\d{1,2})?$/.test(cleanedAmt)) {
900
+ pushIssue("error", "BAD_AMOUNT", `Invalid <TRNAMT> "${cleanedAmt}".`, lineNum);
901
+ } else {
902
+ const cents = toCents(Number(cleanedAmt));
903
+ if (cents >= 0) creditsCents += cents;
904
+ else debitsCents += Math.abs(cents);
905
+ }
906
+ }
907
+ }
908
+ }
909
+ const lowerName = (filename ?? "").toLowerCase();
910
+ const format = isXmlOfx ? "ofx-xml" : lowerName.endsWith(".qbo") || intuitBid !== null ? "qbo" : hasSgmlHeader || /<FI>/i.test(normalized) ? "ofx" : "unknown";
911
+ const matchedBank = intuitBid ? PRIORITY_BANKS.find((b) => b.intuitBid === intuitBid.padStart(5, "0")) ?? null : null;
912
+ if (format === "qbo") {
913
+ if (!intuitBid || !/^\d{4,6}$/.test(intuitBid) || /^0+$/.test(intuitBid)) {
914
+ pushIssue(
915
+ "error",
916
+ "OL-332",
917
+ "Missing or invalid <INTU.BID> Intuit Bank ID in .qbo file (causes QuickBooks OL-301 / OL-332)."
918
+ );
919
+ }
920
+ } else if (intuitBid === null && format === "ofx") {
921
+ pushIssue(
922
+ "info",
923
+ "OL-301",
924
+ "Standard OFX 1.02 file omits <INTU.BID> (valid for Sage / Xero / Wave; QuickBooks Web Connect prefers .qbo with <INTU.BID>)."
925
+ );
926
+ }
927
+ const hasErrors = issues.some((i) => i.severity === "error");
928
+ return {
929
+ isValid: !hasErrors && byteLen > 0,
930
+ format,
931
+ currency,
932
+ intuitBid,
933
+ recognizedBank: matchedBank?.name ?? null,
934
+ transactionCount,
935
+ creditsCents,
936
+ debitsCents,
937
+ netCents: creditsCents - debitsCents,
938
+ ledgerBalance,
939
+ dateStart: minDate,
940
+ dateEnd: maxDate,
941
+ issues
942
+ };
943
+ }
944
+ function repairQboContent(raw) {
945
+ const byteLen = new TextEncoder().encode(raw).byteLength;
946
+ if (byteLen > MAX_QBO_INPUT_BYTES) {
947
+ throw new RangeError(`QBO/OFX content exceeds 15 MiB repair limit (${byteLen} bytes).`);
948
+ }
949
+ const fixes = [];
950
+ const lines = raw.replace(/\r\n?/g, "\n").split("\n");
951
+ const usedFitids = /* @__PURE__ */ new Set();
952
+ for (const line of lines) {
953
+ for (const seg of line.split(/(?=<\/?[A-Z][A-Z0-9._]*>)/i)) {
954
+ if (!seg) continue;
955
+ const v = extractTagValue(seg, "FITID");
956
+ if (v !== null && v.trim()) {
957
+ usedFitids.add(v.trim());
958
+ }
959
+ }
960
+ }
961
+ const seenFitids = /* @__PURE__ */ new Set();
962
+ let ampFixCount = 0;
963
+ let fitidFixCount = 0;
964
+ let nameTrimCount = 0;
965
+ const repairSegment = (segment) => {
966
+ const cleanedSeg = segment.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "");
967
+ for (const tag of ["NAME", "MEMO"]) {
968
+ const val = extractTagValue(cleanedSeg, tag);
969
+ if (val !== null) {
970
+ let nextVal = val;
971
+ if (UNESCAPED_AMP_RE.test(nextVal) || /[<>]/.test(nextVal)) {
972
+ nextVal = nextVal.replace(GLOBAL_UNESCAPED_AMP_RE, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
973
+ ampFixCount += 1;
974
+ }
975
+ if (tag === "NAME" && nextVal.trim().length > 32) {
976
+ nextVal = truncateEntitySafe(nextVal.trim(), 32);
977
+ nameTrimCount += 1;
978
+ }
979
+ const closeTag = `</${tag}>`;
980
+ const hasClose = cleanedSeg.toUpperCase().includes(closeTag.toUpperCase());
981
+ const indent = cleanedSeg.match(/^\s*/)?.[0] ?? "";
982
+ return hasClose ? `${indent}<${tag}>${nextVal}${closeTag}` : `${indent}<${tag}>${nextVal}`;
983
+ }
984
+ }
985
+ const fitidVal = extractTagValue(cleanedSeg, "FITID");
986
+ if (fitidVal !== null) {
987
+ const base = fitidVal.trim();
988
+ if (base && !seenFitids.has(base)) {
989
+ seenFitids.add(base);
990
+ usedFitids.add(base);
991
+ return cleanedSeg;
992
+ }
993
+ fitidFixCount += 1;
994
+ const indent = cleanedSeg.match(/^\s*/)?.[0] ?? "";
995
+ const hasClose = cleanedSeg.toUpperCase().includes("</FITID>");
996
+ const seed = base || "FITID";
997
+ let n = 2;
998
+ let updated = "";
999
+ do {
1000
+ const suffix = `-dup${n}`;
1001
+ const cappedBase = seed.slice(0, Math.max(1, 255 - suffix.length));
1002
+ updated = `${cappedBase}${suffix}`;
1003
+ n += 1;
1004
+ } while (usedFitids.has(updated));
1005
+ seenFitids.add(updated);
1006
+ usedFitids.add(updated);
1007
+ return hasClose ? `${indent}<FITID>${updated}</FITID>` : `${indent}<FITID>${updated}`;
1008
+ }
1009
+ return cleanedSeg;
1010
+ };
1011
+ const fixedLines = lines.map((line) => {
1012
+ const segments = line.split(/(?=<\/?[A-Z][A-Z0-9._]*>)/i);
1013
+ return segments.map((seg) => seg ? repairSegment(seg) : seg).join("");
1014
+ });
1015
+ if (ampFixCount > 0) {
1016
+ fixes.push(`Escaped ${ampFixCount} bare "&", "<", or ">" character(s) (fixes OL-222).`);
1017
+ }
1018
+ if (fitidFixCount > 0) {
1019
+ fixes.push(`Disambiguated ${fitidFixCount} duplicate <FITID> tag(s).`);
1020
+ }
1021
+ if (nameTrimCount > 0) {
1022
+ fixes.push(`Trimmed ${nameTrimCount} <NAME> field(s) safely to <=32 chars.`);
1023
+ }
1024
+ const repaired = `${fixedLines.join("\n").replace(/\n+$/, "")}
1025
+ `;
1026
+ return { repaired, fixesApplied: fixes };
1027
+ }
1028
+
1029
+ // src/lib/parser/exporters.ts
1030
+ function escapeCsvCell(value) {
1031
+ const isPlainNumber = /^-?\d+(?:\.\d+)?$/.test(value);
1032
+ const strippedLeading = value.replace(/^[\s\u0000-\u001f\u007f\uFEFF\u200B-\u200D\u2060]+/, "");
1033
+ const startsFormula = /^[=+\-@]/.test(strippedLeading) || /^[\t\r\n]/.test(value);
1034
+ const sanitized = !isPlainNumber && startsFormula ? `'${value}` : value;
1035
+ if (/[",\r\n]/.test(sanitized)) {
1036
+ return `"${sanitized.replace(/"/g, '""')}"`;
1037
+ }
1038
+ return sanitized;
1039
+ }
1040
+ function buildCsv(headers, rows) {
1041
+ const lines = [
1042
+ headers.map(escapeCsvCell).join(","),
1043
+ ...rows.map((row) => row.map(escapeCsvCell).join(","))
1044
+ ];
1045
+ return `${lines.join("\r\n")}\r
1046
+ `;
1047
+ }
1048
+ function escapeOfxText(value, maxLength) {
1049
+ const escaped = value.normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[\u2014\u2013]/g, "-").replace(/[^\x20-\x7e]/g, " ").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\s+/g, " ").trim();
1050
+ if (escaped.length <= maxLength) return escaped;
1051
+ let cut = escaped.slice(0, maxLength);
1052
+ const lastAmp = cut.lastIndexOf("&");
1053
+ if (lastAmp >= 0 && !cut.slice(lastAmp).includes(";")) {
1054
+ cut = cut.slice(0, lastAmp);
1055
+ }
1056
+ return cut.trimEnd();
1057
+ }
1058
+ function toOfxDate(isoDate) {
1059
+ const trimmed = isoDate.trim();
1060
+ const match = trimmed.match(/^(\d{4})-(\d{2})-(\d{2})$/);
1061
+ if (!match) {
1062
+ throw new RangeError(`Expected YYYY-MM-DD date for OFX/QBO export, got "${isoDate}"`);
1063
+ }
1064
+ const year = Number(match[1]);
1065
+ const month = Number(match[2]);
1066
+ const day = Number(match[3]);
1067
+ const dt = new Date(Date.UTC(year, month - 1, day));
1068
+ if (dt.getUTCFullYear() !== year || dt.getUTCMonth() !== month - 1 || dt.getUTCDate() !== day) {
1069
+ throw new RangeError(`Invalid calendar date for OFX/QBO export: "${isoDate}"`);
1070
+ }
1071
+ return `${match[1]}${match[2]}${match[3]}120000[0:GMT]`;
1072
+ }
1073
+ function normalizeFitIdDescription(desc) {
1074
+ return desc.trim().replace(/\s+/g, " ").toUpperCase();
1075
+ }
1076
+ function deterministicFitId(tx, occurrenceIndex) {
1077
+ const cents = toCents(tx.amount);
1078
+ const normalizedDesc = normalizeFitIdDescription(tx.description || "");
1079
+ const seed = `${tx.date}|${cents}|${normalizedDesc}|${occurrenceIndex}`;
1080
+ let hash = 2166136261;
1081
+ for (let i = 0; i < seed.length; i++) {
1082
+ hash ^= seed.charCodeAt(i);
1083
+ hash = Math.imul(hash, 16777619);
1084
+ }
1085
+ const cleanDate = tx.date.replace(/[^0-9]/g, "") || "00000000";
1086
+ return `${cleanDate}-${(hash >>> 0).toString(16).padStart(8, "0")}-${occurrenceIndex + 1}`;
1087
+ }
1088
+ function buildStmtTrns(transactions) {
1089
+ const occurrenceCounter = /* @__PURE__ */ new Map();
1090
+ return transactions.map((tx) => {
1091
+ const cents = toCents(tx.amount);
1092
+ const occKey = `${tx.date}|${normalizeFitIdDescription(tx.description || "")}|${cents}`;
1093
+ const occIdx = occurrenceCounter.get(occKey) ?? 0;
1094
+ occurrenceCounter.set(occKey, occIdx + 1);
1095
+ const trnType = cents >= 0 ? "CREDIT" : "DEBIT";
1096
+ const cleanName = escapeOfxText(tx.cleanPayee?.trim() || tx.description || "Transaction", 32);
1097
+ const cleanMemo = escapeOfxText(tx.description || "", 255);
1098
+ const fitId = deterministicFitId(tx, occIdx);
1099
+ return [
1100
+ "<STMTTRN>",
1101
+ `<TRNTYPE>${trnType}`,
1102
+ `<DTPOSTED>${toOfxDate(tx.date)}`,
1103
+ `<TRNAMT>${formatCents(cents)}`,
1104
+ `<FITID>${fitId}`,
1105
+ `<NAME>${cleanName}`,
1106
+ cleanMemo ? `<MEMO>${cleanMemo}` : null,
1107
+ tx.checkNumber ? `<CHECKNUM>${escapeOfxText(tx.checkNumber, 12)}` : null,
1108
+ "</STMTTRN>"
1109
+ ].filter(Boolean).join("\n");
1110
+ }).join("\n");
1111
+ }
1112
+ function toQuickBooksQbo(transactions, meta, endingBalance) {
1113
+ const currency = escapeOfxText((meta.currency ?? "CAD").toUpperCase(), 10);
1114
+ const intuitBid = escapeOfxText(meta.intuitBid ?? "00003", 16);
1115
+ const accountId = escapeOfxText(meta.accountId ?? "000000000", 22);
1116
+ const accountType = escapeOfxText(meta.accountType ?? "CHECKING", 20);
1117
+ const isCreditCard = meta.accountType === "CREDITCARD";
1118
+ const dates = transactions.map((tx) => tx.date).sort();
1119
+ const startDate = meta.startDate ?? dates[0] ?? "2026-01-01";
1120
+ const endDate = meta.endDate ?? dates[dates.length - 1] ?? startDate;
1121
+ const ledgerBalance = endingBalance !== void 0 ? formatCents(toCents(endingBalance)) : formatCents(
1122
+ transactions.reduce((sum, tx) => sum + toCents(tx.amount), 0)
1123
+ );
1124
+ const stmtTrns = buildStmtTrns(transactions);
1125
+ const msgSetOpen = isCreditCard ? "<CREDITCARDMSGSRSV1>\n<CCSTMTTRNRS>" : "<BANKMSGSRSV1>\n<STMTTRNRS>";
1126
+ const msgSetClose = isCreditCard ? "</CCSTMTTRNRS>\n</CREDITCARDMSGSRSV1>" : "</STMTTRNRS>\n</BANKMSGSRSV1>";
1127
+ const stmRsOpen = isCreditCard ? "<CCSTMTRS>" : "<STMTRS>";
1128
+ const stmRsClose = isCreditCard ? "</CCSTMTRS>" : "</STMTRS>";
1129
+ const acctBlock = isCreditCard ? `<CCACCTFROM>
1130
+ <ACCTID>${accountId}
1131
+ </CCACCTFROM>` : `<BANKACCTFROM>
1132
+ <BANKID>${intuitBid}
1133
+ <ACCTID>${accountId}
1134
+ <ACCTTYPE>${accountType}
1135
+ </BANKACCTFROM>`;
1136
+ return [
1137
+ "OFXHEADER:100",
1138
+ "DATA:OFXSGML",
1139
+ "VERSION:102",
1140
+ "SECURITY:NONE",
1141
+ "ENCODING:USASCII",
1142
+ "CHARSET:1252",
1143
+ "COMPRESSION:NONE",
1144
+ "OLDFILEUID:NONE",
1145
+ "NEWFILEUID:NONE",
1146
+ "",
1147
+ "<OFX>",
1148
+ "<SIGNONMSGSRSV1>",
1149
+ "<SONRS>",
1150
+ "<STATUS>",
1151
+ "<CODE>0",
1152
+ "<SEVERITY>INFO",
1153
+ "</STATUS>",
1154
+ `<DTSERVER>${toOfxDate(endDate)}`,
1155
+ "<LANGUAGE>ENG",
1156
+ "<INTU.BID>" + intuitBid,
1157
+ "</SONRS>",
1158
+ "</SIGNONMSGSRSV1>",
1159
+ msgSetOpen,
1160
+ "<TRNUID>1001",
1161
+ "<STATUS>",
1162
+ "<CODE>0",
1163
+ "<SEVERITY>INFO",
1164
+ "</STATUS>",
1165
+ stmRsOpen,
1166
+ `<CURDEF>${currency}`,
1167
+ acctBlock,
1168
+ "<BANKTRANLIST>",
1169
+ `<DTSTART>${toOfxDate(startDate)}`,
1170
+ `<DTEND>${toOfxDate(endDate)}`,
1171
+ stmtTrns,
1172
+ "</BANKTRANLIST>",
1173
+ "<LEDGERBAL>",
1174
+ `<BALAMT>${ledgerBalance}`,
1175
+ `<DTASOF>${toOfxDate(endDate)}`,
1176
+ "</LEDGERBAL>",
1177
+ stmRsClose,
1178
+ msgSetClose,
1179
+ "</OFX>",
1180
+ ""
1181
+ ].join("\n");
1182
+ }
1183
+ function toStandardOfx(transactions, meta, endingBalance) {
1184
+ const currency = escapeOfxText((meta.currency ?? "CAD").toUpperCase(), 10);
1185
+ const bankOrg = escapeOfxText(
1186
+ meta.bankName?.trim() ? meta.bankName : "Bank Statement",
1187
+ 32
1188
+ );
1189
+ const routingId = escapeOfxText(meta.intuitBid ?? "00000", 22);
1190
+ const accountId = escapeOfxText(meta.accountId ?? "000000000", 22);
1191
+ const accountType = escapeOfxText(meta.accountType ?? "CHECKING", 20);
1192
+ const isCreditCard = meta.accountType === "CREDITCARD";
1193
+ const dates = transactions.map((tx) => tx.date).sort();
1194
+ const startDate = meta.startDate ?? dates[0] ?? "2026-01-01";
1195
+ const endDate = meta.endDate ?? dates[dates.length - 1] ?? startDate;
1196
+ const ledgerBalance = endingBalance !== void 0 ? formatCents(toCents(endingBalance)) : formatCents(
1197
+ transactions.reduce((sum, tx) => sum + toCents(tx.amount), 0)
1198
+ );
1199
+ const stmtTrns = buildStmtTrns(transactions);
1200
+ const msgSetOpen = isCreditCard ? "<CREDITCARDMSGSRSV1>\n<CCSTMTTRNRS>" : "<BANKMSGSRSV1>\n<STMTTRNRS>";
1201
+ const msgSetClose = isCreditCard ? "</CCSTMTTRNRS>\n</CREDITCARDMSGSRSV1>" : "</STMTTRNRS>\n</BANKMSGSRSV1>";
1202
+ const stmRsOpen = isCreditCard ? "<CCSTMTRS>" : "<STMTRS>";
1203
+ const stmRsClose = isCreditCard ? "</CCSTMTRS>" : "</STMTRS>";
1204
+ const acctBlock = isCreditCard ? `<CCACCTFROM>
1205
+ <ACCTID>${accountId}
1206
+ </CCACCTFROM>` : `<BANKACCTFROM>
1207
+ <BANKID>${routingId}
1208
+ <ACCTID>${accountId}
1209
+ <ACCTTYPE>${accountType}
1210
+ </BANKACCTFROM>`;
1211
+ return [
1212
+ "OFXHEADER:100",
1213
+ "DATA:OFXSGML",
1214
+ "VERSION:102",
1215
+ "SECURITY:NONE",
1216
+ "ENCODING:USASCII",
1217
+ "CHARSET:1252",
1218
+ "COMPRESSION:NONE",
1219
+ "OLDFILEUID:NONE",
1220
+ "NEWFILEUID:NONE",
1221
+ "",
1222
+ "<OFX>",
1223
+ "<SIGNONMSGSRSV1>",
1224
+ "<SONRS>",
1225
+ "<STATUS>",
1226
+ "<CODE>0",
1227
+ "<SEVERITY>INFO",
1228
+ "</STATUS>",
1229
+ `<DTSERVER>${toOfxDate(endDate)}`,
1230
+ "<LANGUAGE>ENG",
1231
+ "<FI>",
1232
+ `<ORG>${bankOrg}`,
1233
+ "</FI>",
1234
+ "</SONRS>",
1235
+ "</SIGNONMSGSRSV1>",
1236
+ msgSetOpen,
1237
+ "<TRNUID>1001",
1238
+ "<STATUS>",
1239
+ "<CODE>0",
1240
+ "<SEVERITY>INFO",
1241
+ "</STATUS>",
1242
+ stmRsOpen,
1243
+ `<CURDEF>${currency}`,
1244
+ acctBlock,
1245
+ "<BANKTRANLIST>",
1246
+ `<DTSTART>${toOfxDate(startDate)}`,
1247
+ `<DTEND>${toOfxDate(endDate)}`,
1248
+ stmtTrns,
1249
+ "</BANKTRANLIST>",
1250
+ "<LEDGERBAL>",
1251
+ `<BALAMT>${ledgerBalance}`,
1252
+ `<DTASOF>${toOfxDate(endDate)}`,
1253
+ "</LEDGERBAL>",
1254
+ stmRsClose,
1255
+ msgSetClose,
1256
+ "</OFX>",
1257
+ ""
1258
+ ].join("\n");
1259
+ }
1260
+ function toXeroCsv(transactions) {
1261
+ return buildCsv(
1262
+ ["*Date", "*Amount", "Payee", "Description", "Reference", "Check Number"],
1263
+ transactions.map((tx) => [
1264
+ tx.date,
1265
+ formatCents(toCents(tx.amount)),
1266
+ tx.cleanPayee?.trim() || tx.description,
1267
+ tx.description,
1268
+ tx.reference ?? "",
1269
+ tx.checkNumber ?? ""
1270
+ ])
1271
+ );
1272
+ }
1273
+ function toWaveCsv(transactions) {
1274
+ return buildCsv(
1275
+ ["Date", "Description", "Amount"],
1276
+ transactions.map((tx) => [
1277
+ tx.date,
1278
+ tx.description,
1279
+ formatCents(toCents(tx.amount))
1280
+ ])
1281
+ );
1282
+ }
1283
+
1284
+ // src/api-worker/auth.ts
1285
+ var MAX_BODY_BYTES = 10 * 1024 * 1024;
1286
+ var encoder = new TextEncoder();
1287
+ var POLAR_REVALIDATE_MS = 60 * 60 * 1e3;
1288
+ var IDEMPOTENCY_MAX_CACHED_BYTES = 5 * 1024 * 1024;
1289
+
1290
+ // src/api-worker/billback.ts
1291
+ var CLIENT_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
1292
+ var USAGE_TTL_SECONDS = 400 * 86400;
1293
+
1294
+ // src/api-worker/routes/qbo.ts
1295
+ var MAX_BODY_BYTES2 = 10 * 1024 * 1024;
1296
+ var ENGINE_VERSION = "3.1.0";
1297
+ function apiJson(body, status = 200, headers = {}) {
1298
+ return new Response(JSON.stringify(body), {
1299
+ status,
1300
+ headers: { "content-type": "application/json; charset=utf-8", ...headers }
1301
+ });
1302
+ }
1303
+ function apiError(status, code, message, localizedMessage, extra = {}) {
1304
+ return apiJson(
1305
+ {
1306
+ ok: false,
1307
+ error: {
1308
+ code,
1309
+ message,
1310
+ localizedMessage: localizedMessage ?? message,
1311
+ retryable: status >= 500 || status === 429,
1312
+ ...extra
1313
+ },
1314
+ receipt: null
1315
+ },
1316
+ status
1317
+ );
1318
+ }
1319
+ function receiptHeaders(receipt, ctx) {
1320
+ return {
1321
+ ...receipt ? { "x-exactrows-receipt-id": receipt.receiptId } : {},
1322
+ "x-exactrows-engine-version": ctx.engineVersion ?? ENGINE_VERSION,
1323
+ "x-exactrows-retention": "none",
1324
+ "cache-control": "no-store"
1325
+ };
1326
+ }
1327
+ function pickLang(body, ctx, url) {
1328
+ const candidates = [body?.lang, url.searchParams.get("lang"), ctx.lang];
1329
+ for (const c of candidates) if (c === "fr" || c === "en") return c;
1330
+ return "en";
1331
+ }
1332
+ async function readJsonBody(request) {
1333
+ const declared = Number(request.headers.get("content-length") ?? "0");
1334
+ const tooLarge = () => ({
1335
+ ok: false,
1336
+ response: apiError(413, "PAYLOAD_TOO_LARGE", "Request body exceeds the 10 MiB limit.", "Le corps de la requ\xEAte d\xE9passe la limite de 10 Mio.")
1337
+ });
1338
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES2) return tooLarge();
1339
+ let text;
1340
+ try {
1341
+ text = await request.text();
1342
+ } catch {
1343
+ return { ok: false, response: apiError(400, "INVALID_JSON", "Request body must be valid JSON.", "Le corps doit \xEAtre du JSON valide.") };
1344
+ }
1345
+ if (text.length > MAX_BODY_BYTES2 || new TextEncoder().encode(text).byteLength > MAX_BODY_BYTES2) return tooLarge();
1346
+ let parsed;
1347
+ try {
1348
+ parsed = JSON.parse(text);
1349
+ } catch {
1350
+ return { ok: false, response: apiError(400, "INVALID_JSON", "Request body must be valid JSON.", "Le corps doit \xEAtre du JSON valide.") };
1351
+ }
1352
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1353
+ return { ok: false, response: apiError(400, "INVALID_JSON", "Request body must be a JSON object.", "Le corps doit \xEAtre un objet JSON.") };
1354
+ }
1355
+ const body = parsed;
1356
+ if (body.clientId !== void 0 && (typeof body.clientId !== "string" || !CLIENT_ID_PATTERN.test(body.clientId))) {
1357
+ return { ok: false, response: apiError(400, "INVALID_CLIENT_ID", "clientId must be 1-64 chars of A-Z a-z 0-9 - _.") };
1358
+ }
1359
+ return { ok: true, body };
1360
+ }
1361
+ async function issueReceipt(env, ctx, endpoint, input, output, math, repairs = []) {
1362
+ return buildReceipt(
1363
+ {
1364
+ endpoint,
1365
+ engineVersion: ctx.engineVersion ?? ENGINE_VERSION,
1366
+ clientId: ctx.clientId ?? null,
1367
+ issuerDisplayName: ctx.issuerDisplayName ?? null,
1368
+ retentionMode: "none",
1369
+ inputSha256: digestSha256(input),
1370
+ outputSha256: digestSha256(output),
1371
+ reconciliationMath: math,
1372
+ repairsApplied: repairs
1373
+ },
1374
+ env ?? {}
1375
+ );
1376
+ }
1377
+ function mathFromTransactions(currency, openingCents, closingCents, amounts) {
1378
+ let credits = 0;
1379
+ let debits = 0;
1380
+ for (const a of amounts) {
1381
+ if (a >= 0) credits += a;
1382
+ else debits += -a;
1383
+ }
1384
+ const expected = openingCents + credits - debits;
1385
+ const closing = closingCents ?? expected;
1386
+ const delta = closing - expected;
1387
+ return {
1388
+ currency,
1389
+ openingCents,
1390
+ creditsCents: credits,
1391
+ debitsCents: debits,
1392
+ closingCents: closing,
1393
+ deltaCents: delta,
1394
+ balanced: delta === 0,
1395
+ transactionCount: amounts.length
1396
+ };
1397
+ }
1398
+ var MAX_TRANSACTIONS = 1e5;
1399
+ function isCalendarDate(s) {
1400
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
1401
+ if (!m) return false;
1402
+ const d = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3]));
1403
+ return d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3];
1404
+ }
1405
+ function parseApiTransactions(raw) {
1406
+ if (!Array.isArray(raw)) {
1407
+ return { ok: false, response: apiError(400, "INVALID_TRANSACTIONS", "transactions must be an array.", "transactions doit \xEAtre un tableau.") };
1408
+ }
1409
+ if (raw.length > MAX_TRANSACTIONS) {
1410
+ return { ok: false, response: apiError(413, "TOO_MANY_TRANSACTIONS", `At most ${MAX_TRANSACTIONS} transactions per request.`) };
1411
+ }
1412
+ const txs = [];
1413
+ for (let i = 0; i < raw.length; i++) {
1414
+ const t = raw[i];
1415
+ const bad = (why) => ({ ok: false, response: apiError(400, "INVALID_TRANSACTION", `transactions[${i}]: ${why}`, `transactions[${i}] : champ invalide.`, { index: i }) });
1416
+ if (!t || typeof t !== "object") return bad("must be an object");
1417
+ if (typeof t.date !== "string" || !isCalendarDate(t.date)) return bad("date must be a valid YYYY-MM-DD");
1418
+ if (typeof t.amountCents !== "number" || !Number.isSafeInteger(t.amountCents)) return bad("amountCents must be an integer");
1419
+ if (t.description !== void 0 && typeof t.description !== "string") return bad("description must be a string");
1420
+ let amount = t.amountCents;
1421
+ if (t.type === "debit" && amount > 0) amount = -amount;
1422
+ else if (t.type === "credit" && amount < 0) amount = -amount;
1423
+ txs.push({
1424
+ ...typeof t.id === "string" && t.id ? { id: t.id } : {},
1425
+ date: t.date,
1426
+ description: typeof t.description === "string" ? t.description : "",
1427
+ amountCents: amount
1428
+ });
1429
+ }
1430
+ return { ok: true, txs };
1431
+ }
1432
+ var toParsed = (t) => ({ date: t.date, description: t.description, amount: t.amountCents / 100 });
1433
+ var MIME = {
1434
+ qbo: "application/vnd.intu.qbo",
1435
+ ofx: "application/x-ofx",
1436
+ iif: "text/plain; charset=utf-8"
1437
+ };
1438
+ function iifDate(iso) {
1439
+ return `${iso.slice(5, 7)}/${iso.slice(8, 10)}/${iso.slice(0, 4)}`;
1440
+ }
1441
+ function iifText(s) {
1442
+ return s.replace(/[\t\r\n]+/g, " ").trim();
1443
+ }
1444
+ function centsToMajor(c) {
1445
+ const sign = c < 0 ? "-" : "";
1446
+ const a = Math.abs(c);
1447
+ return `${sign}${Math.floor(a / 100)}.${String(a % 100).padStart(2, "0")}`;
1448
+ }
1449
+ function generateContent(spec, txs) {
1450
+ const accountId = spec.accountIdMasked ?? "000000000";
1451
+ const rows = txs.map((t) => ({
1452
+ accountId,
1453
+ date: t.date,
1454
+ amountCents: t.amountCents,
1455
+ description: t.description,
1456
+ fitid: t.id ?? null
1457
+ }));
1458
+ const fitids = assignFitids(rows).map((r) => r.fitid);
1459
+ const sorted = txs.map((t) => t.date).sort();
1460
+ if (spec.format === "iif") {
1461
+ const lines = [
1462
+ "!TRNS TRNSTYPE DATE ACCNT AMOUNT DOCNUM MEMO",
1463
+ "!SPL TRNSTYPE DATE ACCNT AMOUNT DOCNUM MEMO",
1464
+ "!ENDTRNS"
1465
+ ];
1466
+ txs.forEach((t, i) => {
1467
+ const type = t.amountCents >= 0 ? "DEPOSIT" : "CHECK";
1468
+ lines.push(
1469
+ `TRNS ${type} ${iifDate(t.date)} ${iifText(spec.bankProfile ?? "Bank")} ${centsToMajor(t.amountCents)} ${fitids[i]} ${iifText(t.description)}`,
1470
+ `SPL ${type} ${iifDate(t.date)} Uncategorized ${centsToMajor(-t.amountCents)} ${fitids[i]} ${iifText(t.description)}`,
1471
+ "ENDTRNS"
1472
+ );
1473
+ });
1474
+ return { content: `${lines.join("\r\n")}\r
1475
+ `, fitids };
1476
+ }
1477
+ const net = txs.reduce((s, t) => s + t.amountCents, 0);
1478
+ const meta = {
1479
+ bankName: spec.bankProfile ?? "Bank Statement",
1480
+ intuitBid: spec.intuBid,
1481
+ accountId,
1482
+ accountType: ["CHECKING", "SAVINGS", "CREDITCARD"].find((x) => x === spec.accountType) ?? "CHECKING",
1483
+ currency: spec.currency,
1484
+ startDate: sorted[0],
1485
+ endDate: sorted[sorted.length - 1]
1486
+ };
1487
+ const ending = (spec.closingCents ?? spec.openingCents + net) / 100;
1488
+ const raw = (spec.format === "qbo" ? toQuickBooksQbo : toStandardOfx)(txs.map(toParsed), meta, ending);
1489
+ let idx = 0;
1490
+ const content = raw.replace(/<FITID>[^\r\n<]*/g, () => `<FITID>${fitids[idx++] ?? ""}`);
1491
+ return { content, fitids };
1492
+ }
1493
+ function tagVal(block, tag) {
1494
+ const m = new RegExp(`<${tag}>([^<\\r\\n]*)`, "i").exec(block);
1495
+ return m ? m[1].trim() : null;
1496
+ }
1497
+ function parseStmtTrns(text) {
1498
+ const out = [];
1499
+ const parts = text.split(/<STMTTRN>/i).slice(1);
1500
+ for (const part of parts) {
1501
+ const end = part.search(/<\/STMTTRN>|<\/BANKTRANLIST>|<\/CCSTMTRS>|<LEDGERBAL>/i);
1502
+ const block = end >= 0 ? part.slice(0, end) : part;
1503
+ const dt = (tagVal(block, "DTPOSTED") ?? "").replace(/[^0-9]/g, "").slice(0, 8);
1504
+ const amt = Number((tagVal(block, "TRNAMT") ?? "").replace(",", "."));
1505
+ out.push({
1506
+ fitid: tagVal(block, "FITID"),
1507
+ date: dt.length === 8 ? `${dt.slice(0, 4)}-${dt.slice(4, 6)}-${dt.slice(6, 8)}` : "1970-01-01",
1508
+ amountCents: Number.isFinite(amt) ? Math.round(amt * 100) : 0,
1509
+ name: tagVal(block, "NAME") ?? "",
1510
+ memo: tagVal(block, "MEMO") ?? ""
1511
+ });
1512
+ }
1513
+ return out;
1514
+ }
1515
+ var XXE_RE = /<!\s*(DOCTYPE|ENTITY)\b|\b(SYSTEM|PUBLIC)\s+["']/i;
1516
+ function decodeQboInput(body, lang) {
1517
+ let text;
1518
+ if (typeof body.qboBase64 === "string" && typeof body.qboText !== "string") {
1519
+ let bytes;
1520
+ try {
1521
+ const bin = atob(body.qboBase64.replace(/\s+/g, ""));
1522
+ bytes = new Uint8Array(bin.length);
1523
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
1524
+ } catch {
1525
+ return { ok: false, response: apiError(400, "INVALID_BASE64", "qboBase64 is not valid base64.", "qboBase64 n\u2019est pas du base64 valide.") };
1526
+ }
1527
+ if (bytes.byteLength > MAX_BODY_BYTES2) {
1528
+ return { ok: false, response: apiError(413, "PAYLOAD_TOO_LARGE", "QBO payload exceeds 10 MiB.", "Le fichier QBO d\xE9passe 10 Mio.") };
1529
+ }
1530
+ let sliceStart = 0;
1531
+ if (bytes.length >= 3 && bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191) {
1532
+ sliceStart = 3;
1533
+ }
1534
+ const head = new TextDecoder("latin1").decode(bytes.subarray(sliceStart, sliceStart + 600));
1535
+ let useCp1252 = /CHARSET:\s*1252/i.test(head);
1536
+ let utf8 = null;
1537
+ if (!useCp1252) {
1538
+ try {
1539
+ utf8 = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(sliceStart));
1540
+ } catch {
1541
+ useCp1252 = true;
1542
+ }
1543
+ }
1544
+ text = utf8 ?? new TextDecoder("windows-1252").decode(bytes.subarray(sliceStart));
1545
+ } else if (typeof body.qboText === "string") {
1546
+ text = body.qboText;
1547
+ } else {
1548
+ return {
1549
+ ok: false,
1550
+ response: apiError(400, "MISSING_QBO_TEXT", "qboText (string) is required.", lang === "fr" ? "qboText (cha\xEEne) est requis." : void 0)
1551
+ };
1552
+ }
1553
+ if (text.charCodeAt(0) === 65279 || text.startsWith("\uFEFF")) {
1554
+ text = text.replace(/^\uFEFF+/, "");
1555
+ }
1556
+ text = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
1557
+ if (new TextEncoder().encode(text).byteLength > MAX_BODY_BYTES2) {
1558
+ return { ok: false, response: apiError(413, "PAYLOAD_TOO_LARGE", "QBO payload exceeds 10 MiB.", "Le fichier QBO d\xE9passe 10 Mio.") };
1559
+ }
1560
+ if (XXE_RE.test(text)) {
1561
+ return {
1562
+ ok: false,
1563
+ response: apiError(
1564
+ 400,
1565
+ "XXE_REJECTED",
1566
+ "DOCTYPE and ENTITY declarations are not allowed in OFX/QBO input.",
1567
+ "Les d\xE9clarations DOCTYPE et ENTITY ne sont pas permises dans les fichiers OFX/QBO."
1568
+ )
1569
+ };
1570
+ }
1571
+ return { ok: true, text };
1572
+ }
1573
+ var FR_ISSUES = {
1574
+ EMPTY: "Le fichier est vide.",
1575
+ TOO_LARGE: "Le fichier d\xE9passe la taille maximale.",
1576
+ HEADER_MISSING: "L\u2019en-t\xEAte OFX est manquant.",
1577
+ OFX_ENVELOPE: "L\u2019enveloppe OFX est incompl\xE8te.",
1578
+ "OL-222": "Caract\xE8re \xAB & \xBB non \xE9chapp\xE9 dans NAME/MEMO (erreur QuickBooks OL-222).",
1579
+ "OL-301": "INTU.BID manquant ou invalide (erreur QuickBooks OL-301).",
1580
+ "OL-332": "INTU.BID non reconnu (erreur QuickBooks OL-332).",
1581
+ DUP_FITID: "FITID en double d\xE9tect\xE9.",
1582
+ LONG_NAME: "Le champ NAME d\xE9passe 32 caract\xE8res.",
1583
+ BAD_DATE: "Date invalide.",
1584
+ BAD_AMOUNT: "Montant invalide."
1585
+ };
1586
+ var FR_REPAIRS = {
1587
+ "OL-222": "Caract\xE8res \xAB & \xBB, \xAB < \xBB ou \xAB > \xBB \xE9chapp\xE9s (corrige OL-222).",
1588
+ DUP_FITID: "Balises FITID en double d\xE9sambigu\xEFs\xE9es.",
1589
+ LONG_NAME: "Champs NAME raccourcis \xE0 32 caract\xE8res.",
1590
+ FITID_V1_REBUILD: "FITID reconstruits selon la sp\xE9cification ExactRows FITID v1.",
1591
+ SIGN_FLIP: "Signes des montants invers\xE9s.",
1592
+ INTU_BID_SET: "INTU.BID d\xE9fini.",
1593
+ ACCT_TYPE_SET: "ACCTTYPE d\xE9fini."
1594
+ };
1595
+ async function validate(request, env, ctx, url) {
1596
+ const parsed = await readJsonBody(request);
1597
+ if (!parsed.ok) return parsed.response;
1598
+ const lang = pickLang(parsed.body, ctx, url);
1599
+ const input = decodeQboInput(parsed.body, lang);
1600
+ if (!input.ok) return input.response;
1601
+ const report = validateQboOrOfx(input.text);
1602
+ const errorCodes = [...new Set(report.issues.filter((i) => i.severity === "error").map((i) => i.code))];
1603
+ const issues = report.issues.map((i) => ({
1604
+ severity: i.severity,
1605
+ code: i.code,
1606
+ ...i.line !== void 0 ? { line: i.line } : {},
1607
+ message: lang === "fr" ? FR_ISSUES[i.code] ?? i.message : i.message
1608
+ }));
1609
+ const net = report.netCents;
1610
+ const math = {
1611
+ currency: report.currency ?? "CAD",
1612
+ openingCents: 0,
1613
+ creditsCents: report.creditsCents,
1614
+ debitsCents: report.debitsCents,
1615
+ closingCents: net,
1616
+ deltaCents: 0,
1617
+ balanced: true,
1618
+ transactionCount: report.transactionCount
1619
+ };
1620
+ const result = {
1621
+ valid: report.isValid,
1622
+ format: report.format === "ofx-xml" || /^\s*<\?xml/i.test(input.text) ? "ofx_xml" : "qbo_sgml",
1623
+ intuBid: report.intuitBid,
1624
+ errorCodes,
1625
+ issues,
1626
+ transactionCount: report.transactionCount
1627
+ };
1628
+ const receipt = await issueReceipt(env, ctx, "/v1/qbo/validate", input.text, result, math);
1629
+ return apiJson({ ok: true, ...result, receipt }, 200, receiptHeaders(receipt, ctx));
1630
+ }
1631
+ function lineDiff(a, b) {
1632
+ const x = a.replace(/\r\n?/g, "\n").split("\n");
1633
+ const y = b.replace(/\r\n?/g, "\n").split("\n");
1634
+ const out = ["--- original", "+++ repaired"];
1635
+ const n = Math.max(x.length, y.length);
1636
+ for (let i = 0; i < n; i++) {
1637
+ if (x[i] === y[i]) continue;
1638
+ out.push(`@@ line ${i + 1} @@`);
1639
+ if (x[i] !== void 0) out.push(`-${x[i]}`);
1640
+ if (y[i] !== void 0) out.push(`+${y[i]}`);
1641
+ }
1642
+ return out.join("\n");
1643
+ }
1644
+ async function repair(request, env, ctx, url) {
1645
+ const parsed = await readJsonBody(request);
1646
+ if (!parsed.ok) return parsed.response;
1647
+ const lang = pickLang(parsed.body, ctx, url);
1648
+ const input = decodeQboInput(parsed.body, lang);
1649
+ if (!input.ok) return input.response;
1650
+ const opts = parsed.body.options && typeof parsed.body.options === "object" ? parsed.body.options : {};
1651
+ const original = input.text;
1652
+ const originalSha256 = sha256Hex(original);
1653
+ const before = validateQboOrOfx(original);
1654
+ const beforeCodes = new Set(before.issues.filter((i) => i.severity === "error").map((i) => i.code));
1655
+ const repairs = [];
1656
+ const describe = (code, en) => lang === "fr" ? FR_REPAIRS[code] ?? en : en;
1657
+ let working = original.replace(/\r\n?/g, "\n");
1658
+ if (typeof opts.intuBid === "string" && /^[A-Za-z0-9._-]{1,16}$/.test(opts.intuBid)) {
1659
+ let n = 0;
1660
+ working = working.replace(/<INTU\.BID>[^\r\n<]*/gi, () => {
1661
+ n++;
1662
+ return `<INTU.BID>${opts.intuBid}`;
1663
+ });
1664
+ if (n > 0) repairs.push({ code: "INTU_BID_SET", rule: "intu-bid-override", after: String(opts.intuBid), description: describe("INTU_BID_SET", "Set INTU.BID."), affectedCount: n });
1665
+ }
1666
+ if (typeof opts.acctType === "string" && /^(CHECKING|SAVINGS|CREDITCARD|MONEYMRKT|CREDITLINE)$/i.test(opts.acctType)) {
1667
+ let n = 0;
1668
+ working = working.replace(/<ACCTTYPE>[^\r\n<]*/gi, () => {
1669
+ n++;
1670
+ return `<ACCTTYPE>${String(opts.acctType).toUpperCase()}`;
1671
+ });
1672
+ if (n > 0) repairs.push({ code: "ACCT_TYPE_SET", rule: "acct-type-override", after: String(opts.acctType).toUpperCase(), description: describe("ACCT_TYPE_SET", "Set ACCTTYPE."), affectedCount: n });
1673
+ }
1674
+ if (opts.flipSigns === true) {
1675
+ let n = 0;
1676
+ working = working.replace(/<TRNAMT>\s*([-+]?[0-9.,]+)/gi, (_m, v) => {
1677
+ const num = Number(v.replace(",", "."));
1678
+ if (!Number.isFinite(num) || num === 0) return `<TRNAMT>${v}`;
1679
+ n++;
1680
+ const cents = Math.round(-num * 100);
1681
+ return `<TRNAMT>${centsToMajor(cents)}`;
1682
+ });
1683
+ if (n > 0) repairs.push({ code: "SIGN_FLIP", rule: "flip-signs", description: describe("SIGN_FLIP", "Flipped transaction amount signs."), affectedCount: n });
1684
+ }
1685
+ const trns = parseStmtTrns(working);
1686
+ const acctId = tagVal(working, "ACCTID") ?? "";
1687
+ const withFitid = trns.filter((t) => t.fitid !== null);
1688
+ if (withFitid.length > 0) {
1689
+ const results = assignFitids(
1690
+ withFitid.map((t) => ({ accountId: acctId, date: t.date, amountCents: t.amountCents, description: t.memo || t.name, fitid: t.fitid })),
1691
+ { regenerate: opts.regenerateFitids === true }
1692
+ );
1693
+ let i = 0;
1694
+ let changed = 0;
1695
+ working = working.replace(/<FITID>([^\r\n<]*)/gi, (m, old) => {
1696
+ const r = results[i++];
1697
+ if (!r) return m;
1698
+ if (r.fitid !== old.trim()) changed++;
1699
+ return `<FITID>${r.fitid}`;
1700
+ });
1701
+ if (changed > 0) {
1702
+ repairs.push({
1703
+ code: "FITID_V1_REBUILD",
1704
+ rule: "fitid-v1",
1705
+ description: describe("FITID_V1_REBUILD", "Rebuilt FITIDs using ExactRows FITID v1."),
1706
+ affectedCount: changed
1707
+ });
1708
+ }
1709
+ }
1710
+ const fixed = repairQboContent(working);
1711
+ const ruleFor = (s) => /OL-222/.test(s) ? ["OL-222", "escape-bare-ampersand"] : /FITID/.test(s) ? ["DUP_FITID", "disambiguate-fitid"] : ["LONG_NAME", "trim-name-32"];
1712
+ for (const f of fixed.fixesApplied) {
1713
+ const [code, rule] = ruleFor(f);
1714
+ repairs.push({ code, rule, description: describe(code, f), affectedCount: Math.max(1, Number(/\d+/.exec(f)?.[0] ?? 1)) });
1715
+ }
1716
+ const repaired = fixed.repaired;
1717
+ const after = validateQboOrOfx(repaired);
1718
+ const afterCodes = new Set(after.issues.filter((i) => i.severity === "error").map((i) => i.code));
1719
+ const errorCodesResolved = [...beforeCodes].filter((c) => !afterCodes.has(c));
1720
+ const transactions = parseStmtTrns(repaired).map((t) => ({
1721
+ ...t.fitid ? { id: t.fitid } : {},
1722
+ date: t.date,
1723
+ description: t.memo || t.name,
1724
+ amountCents: t.amountCents
1725
+ }));
1726
+ const math = mathFromTransactions(
1727
+ after.currency ?? "CAD",
1728
+ 0,
1729
+ null,
1730
+ transactions.map((t) => t.amountCents)
1731
+ );
1732
+ const result = {
1733
+ repairedQbo: repaired,
1734
+ errorCodesResolved,
1735
+ originalSha256,
1736
+ ...opts.returnOriginalDiff === true ? { diffPatch: lineDiff(original, repaired) } : {},
1737
+ repairsApplied: repairs,
1738
+ transactions,
1739
+ valid: after.isValid
1740
+ };
1741
+ const receipt = await issueReceipt(env, ctx, "/v1/qbo/repair", original, repaired, math, repairs);
1742
+ return apiJson({ ok: true, ...result, receipt }, 200, receiptHeaders(receipt, ctx));
1743
+ }
1744
+ function readSpec(body) {
1745
+ const format = body.format;
1746
+ if (format !== "qbo" && format !== "ofx" && format !== "iif") {
1747
+ return { ok: false, response: apiError(400, "INVALID_FORMAT", "format must be one of qbo, ofx, iif.") };
1748
+ }
1749
+ const currency = typeof body.currency === "string" ? body.currency.toUpperCase() : "";
1750
+ if (!/^[A-Z]{3}$/.test(currency)) {
1751
+ return { ok: false, response: apiError(400, "INVALID_CURRENCY", "currency must be a 3-letter code.") };
1752
+ }
1753
+ const intOrNull = (v) => typeof v === "number" && Number.isSafeInteger(v) ? v : null;
1754
+ if (body.openingCents !== void 0 && intOrNull(body.openingCents) === null || body.closingCents !== void 0 && intOrNull(body.closingCents) === null) {
1755
+ return { ok: false, response: apiError(400, "INVALID_BALANCE", "openingCents and closingCents must be integers.") };
1756
+ }
1757
+ const str = (v, max) => typeof v === "string" ? v.slice(0, max) : void 0;
1758
+ return {
1759
+ ok: true,
1760
+ spec: {
1761
+ format,
1762
+ bankProfile: str(body.bankProfile, 64),
1763
+ intuBid: str(body.intuBid, 16),
1764
+ accountIdMasked: str(body.accountIdMasked, 22),
1765
+ accountType: str(body.accountType, 20),
1766
+ currency,
1767
+ openingCents: intOrNull(body.openingCents) ?? 0,
1768
+ closingCents: intOrNull(body.closingCents)
1769
+ }
1770
+ };
1771
+ }
1772
+ async function generate(request, env, ctx) {
1773
+ const parsed = await readJsonBody(request);
1774
+ if (!parsed.ok) return parsed.response;
1775
+ const spec = readSpec(parsed.body);
1776
+ if (!spec.ok) return spec.response;
1777
+ const txs = parseApiTransactions(parsed.body.transactions);
1778
+ if (!txs.ok) return txs.response;
1779
+ const { content, fitids } = generateContent(spec.spec, txs.txs);
1780
+ const first = txs.txs.map((t) => t.date).sort()[0]?.replace(/-/g, "") ?? "empty";
1781
+ const filename = `exactrows-${first}-${sha256Hex(content).slice(0, 8)}.${spec.spec.format}`;
1782
+ const math = mathFromTransactions(spec.spec.currency, spec.spec.openingCents, spec.spec.closingCents, txs.txs.map((t) => t.amountCents));
1783
+ const receipt = await issueReceipt(env, ctx, "/v1/qbo/generate", parsed.body, content, math);
1784
+ return apiJson(
1785
+ { ok: true, content, filename, mimeType: MIME[spec.spec.format], generatedFitids: fitids, receipt },
1786
+ 200,
1787
+ receiptHeaders(receipt, ctx)
1788
+ );
1789
+ }
1790
+ async function diffDedupe(request, env, ctx) {
1791
+ const parsed = await readJsonBody(request);
1792
+ if (!parsed.ok) return parsed.response;
1793
+ const body = parsed.body;
1794
+ const txs = parseApiTransactions(body.transactions);
1795
+ if (!txs.ok) return txs.response;
1796
+ const prior = /* @__PURE__ */ new Set();
1797
+ if (body.priorFitids !== void 0) {
1798
+ if (!Array.isArray(body.priorFitids) || body.priorFitids.some((f) => typeof f !== "string")) {
1799
+ return apiError(400, "INVALID_PRIOR_FITIDS", "priorFitids must be an array of strings.");
1800
+ }
1801
+ for (const f of body.priorFitids) prior.add(f);
1802
+ }
1803
+ const start = body.cutoffStart;
1804
+ const end = body.cutoffEnd;
1805
+ for (const [k, v] of [["cutoffStart", start], ["cutoffEnd", end]]) {
1806
+ if (v !== void 0 && (typeof v !== "string" || !isCalendarDate(v))) {
1807
+ return apiError(400, "INVALID_CUTOFF", `${k} must be YYYY-MM-DD.`);
1808
+ }
1809
+ }
1810
+ const accountId = typeof body.accountIdMasked === "string" ? body.accountIdMasked : "000000000";
1811
+ const seenIds = /* @__PURE__ */ new Set();
1812
+ const repeated = txs.txs.map((t) => {
1813
+ if (!t.id) return false;
1814
+ if (seenIds.has(t.id)) return true;
1815
+ seenIds.add(t.id);
1816
+ return false;
1817
+ });
1818
+ const assigned = assignFitids(
1819
+ txs.txs.map((t, i) => ({
1820
+ accountId,
1821
+ date: t.date,
1822
+ amountCents: t.amountCents,
1823
+ description: t.description,
1824
+ fitid: repeated[i] ? null : t.id ?? null
1825
+ }))
1826
+ );
1827
+ const retained = [];
1828
+ const retainedFitids = [];
1829
+ const droppedReasons = [];
1830
+ const batchSeen = /* @__PURE__ */ new Set();
1831
+ txs.txs.forEach((t, i) => {
1832
+ const fitid = repeated[i] ? t.id : assigned[i].fitid;
1833
+ if (typeof start === "string" && t.date < start || typeof end === "string" && t.date > end) {
1834
+ droppedReasons.push({ index: i, fitid, reason: "outside_seam" });
1835
+ } else if (repeated[i] || prior.has(fitid) || batchSeen.has(fitid)) {
1836
+ droppedReasons.push({ index: i, fitid, reason: "duplicate_fitid" });
1837
+ } else {
1838
+ batchSeen.add(fitid);
1839
+ retained.push(t);
1840
+ retainedFitids.push(fitid);
1841
+ }
1842
+ });
1843
+ const retainedNetCents = retained.reduce((s, t) => s + t.amountCents, 0);
1844
+ const retainedTransactions = retained.map((t, i) => ({ id: retainedFitids[i], date: t.date, description: t.description, amountCents: t.amountCents }));
1845
+ let merged;
1846
+ if (body.format === "qbo" || body.format === "ofx" || body.format === "iif") {
1847
+ const spec = readSpec({ ...body, format: body.format, currency: body.currency ?? "CAD" });
1848
+ if (!spec.ok) return spec.response;
1849
+ const gen = generateContent(spec.spec, retainedTransactions);
1850
+ merged = { content: gen.content, filename: `exactrows-merged-${sha256Hex(gen.content).slice(0, 8)}.${spec.spec.format}`, mimeType: MIME[spec.spec.format] };
1851
+ }
1852
+ const currency = typeof body.currency === "string" && /^[A-Za-z]{3}$/.test(body.currency) ? body.currency.toUpperCase() : "CAD";
1853
+ const math = mathFromTransactions(currency, 0, null, retained.map((t) => t.amountCents));
1854
+ const result = { retainedTransactions, droppedCount: droppedReasons.length, droppedReasons, retainedNetCents, ...merged ? { merged } : {} };
1855
+ const repairs = droppedReasons.length ? [{ code: "DEDUPE", rule: "diff-dedupe", description: "Dropped duplicate or out-of-seam rows.", affectedCount: droppedReasons.length }] : [];
1856
+ const receipt = await issueReceipt(env, ctx, "/v1/qbo/diff-dedupe", body, result, math, repairs);
1857
+ return apiJson({ ok: true, ...result, receipt }, 200, receiptHeaders(receipt, ctx));
1858
+ }
1859
+ async function handleQbo(request, env, ctx = {}) {
1860
+ const url = ctx.url ?? new URL(request.url);
1861
+ const path = (ctx.path ?? url.pathname).replace(/\/+$/, "");
1862
+ const routes = {
1863
+ "/v1/qbo/validate": () => validate(request, env, ctx, url),
1864
+ "/v1/qbo/repair": () => repair(request, env, ctx, url),
1865
+ "/v1/qbo/generate": () => generate(request, env, ctx),
1866
+ "/v1/qbo/diff-dedupe": () => diffDedupe(request, env, ctx)
1867
+ };
1868
+ const route = routes[path];
1869
+ if (!route) return null;
1870
+ if (request.method !== "POST") {
1871
+ return new Response(
1872
+ JSON.stringify({ ok: false, error: { code: "METHOD_NOT_ALLOWED", message: "Use POST.", retryable: false }, receipt: null }),
1873
+ { status: 405, headers: { "content-type": "application/json", allow: "POST" } }
1874
+ );
1875
+ }
1876
+ try {
1877
+ return await route();
1878
+ } catch (e) {
1879
+ if (e instanceof RangeError) return apiError(413, "PAYLOAD_TOO_LARGE", "Payload exceeds processing limits.");
1880
+ if (e instanceof SyntaxError || e?.name === "SyntaxError") {
1881
+ return apiError(400, "INVALID_JSON", "Request body must be valid JSON.");
1882
+ }
1883
+ return apiError(500, "INTERNAL_ERROR", "Unexpected processing error.");
1884
+ }
1885
+ }
1886
+
1887
+ // src/api-worker/routes/reconcile.ts
1888
+ async function handleReconcile(request, env, ctx = {}) {
1889
+ const url = ctx.url ?? new URL(request.url);
1890
+ const path = (ctx.path ?? url.pathname).replace(/\/+$/, "");
1891
+ if (path !== "/v1/reconcile/verify" && path !== "/v1/ledger/reconcile") return null;
1892
+ if (request.method !== "POST") {
1893
+ return new Response(
1894
+ JSON.stringify({ ok: false, error: { code: "METHOD_NOT_ALLOWED", message: "Use POST.", retryable: false }, receipt: null }),
1895
+ { status: 405, headers: { "content-type": "application/json", allow: "POST" } }
1896
+ );
1897
+ }
1898
+ const parsed = await readJsonBody(request);
1899
+ if (!parsed.ok) return parsed.response;
1900
+ const body = parsed.body;
1901
+ const lang = pickLang(body, ctx, url);
1902
+ const { openingCents, closingCents } = body;
1903
+ if (typeof openingCents !== "number" || !Number.isSafeInteger(openingCents) || typeof closingCents !== "number" || !Number.isSafeInteger(closingCents)) {
1904
+ return apiError(
1905
+ 400,
1906
+ "INVALID_BALANCE",
1907
+ "openingCents and closingCents must be integers.",
1908
+ lang === "fr" ? "openingCents et closingCents doivent \xEAtre des entiers." : void 0
1909
+ );
1910
+ }
1911
+ const txs = parseApiTransactions(body.transactions);
1912
+ if (!txs.ok) return txs.response;
1913
+ const currency = typeof body.currency === "string" && /^[A-Za-z]{3}$/.test(body.currency) ? body.currency.toUpperCase() : "CAD";
1914
+ const parsedTxs = txs.txs.map((t) => ({ date: t.date, description: t.description, amount: t.amountCents / 100 }));
1915
+ const r = reconcileStatement(parsedTxs, openingCents / 100, closingCents / 100);
1916
+ const flipped = reconcileStatement(flipTransactionSigns(parsedTxs), openingCents / 100, closingCents / 100);
1917
+ const signFlipFixesSuggested = !r.isBalanced && r.discrepancyCents !== 0 && flipped.discrepancyCents === 0 ? txs.txs.map((_, i) => i) : [];
1918
+ const seen = /* @__PURE__ */ new Map();
1919
+ const candidateAnomalies = [];
1920
+ txs.txs.forEach((t, i) => {
1921
+ const key = `${t.date}|${t.description.trim().toUpperCase()}|${t.amountCents}`;
1922
+ const first = seen.get(key);
1923
+ if (first !== void 0) candidateAnomalies.push({ type: "possible_duplicate", index: i, firstIndex: first });
1924
+ else seen.set(key, i);
1925
+ });
1926
+ const deltaCents = r.discrepancyCents;
1927
+ const math = {
1928
+ currency,
1929
+ openingCents: r.openingCents,
1930
+ creditsCents: r.totalCreditsCents,
1931
+ debitsCents: r.totalDebitsCents,
1932
+ closingCents: r.closingCents,
1933
+ deltaCents,
1934
+ balanced: deltaCents === 0,
1935
+ transactionCount: r.transactionCount
1936
+ };
1937
+ const balanced = deltaCents === 0;
1938
+ const result = {
1939
+ balanced,
1940
+ deltaCents,
1941
+ creditsCents: r.totalCreditsCents,
1942
+ debitsCents: r.totalDebitsCents,
1943
+ expectedClosingCents: r.expectedClosingCents,
1944
+ signFlipFixesSuggested,
1945
+ candidateAnomalies,
1946
+ proof: `${r.openingCents} + ${r.totalCreditsCents} - ${r.totalDebitsCents} = ${r.expectedClosingCents}; closing ${r.closingCents}; delta ${deltaCents}`,
1947
+ summary: lang === "fr" ? balanced ? "\xC9quilibr\xE9 : solde d\u2019ouverture + cr\xE9dits - d\xE9bits = solde de fermeture." : `Non \xE9quilibr\xE9 : \xE9cart de ${deltaCents} cents.` : balanced ? "Balanced: opening + credits - debits = closing." : `Unbalanced: off by ${deltaCents} cents.`
1948
+ };
1949
+ const endpoint = path === "/v1/ledger/reconcile" ? "/v1/ledger/reconcile" : "/v1/reconcile/verify";
1950
+ const receipt = await issueReceipt(env, ctx, endpoint, body, result, math);
1951
+ return apiJson({ ok: true, ...result, receipt }, 200, receiptHeaders(receipt, ctx));
1952
+ }
1953
+
1954
+ // src/lib/vault/custom-csv-templates.ts
1955
+ var CSV_COLUMN_ROLES = [
1956
+ "date",
1957
+ "description",
1958
+ "amount",
1959
+ "debit",
1960
+ "credit",
1961
+ "balance",
1962
+ "category",
1963
+ "note",
1964
+ "externalId",
1965
+ "ignore"
1966
+ ];
1967
+ var VALID_ROLE_SET = new Set(CSV_COLUMN_ROLES);
1968
+ function normalizeCurrency(raw, fallback = "CAD") {
1969
+ if (typeof raw === "string") {
1970
+ const upper = raw.trim().toUpperCase();
1971
+ if (upper === "USD") return "USD";
1972
+ if (upper === "CAD") return "CAD";
1973
+ }
1974
+ return fallback;
1975
+ }
1976
+ function parseStrictIsoDateMs(dateStr) {
1977
+ const match = dateStr.trim().match(/^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/);
1978
+ if (!match) return null;
1979
+ const y = Number(match[1]);
1980
+ const m = Number(match[2]);
1981
+ const d = Number(match[3]);
1982
+ const dt = new Date(Date.UTC(y, m - 1, d));
1983
+ if (dt.getUTCFullYear() !== y || dt.getUTCMonth() !== m - 1 || dt.getUTCDate() !== d) {
1984
+ return null;
1985
+ }
1986
+ return dt.getTime();
1987
+ }
1988
+ function buildValidatedIsoDate(year, month, day) {
1989
+ if (year < 1900 || year > 2100 || month < 1 || month > 12 || day < 1 || day > 31) {
1990
+ return null;
1991
+ }
1992
+ const candidate = `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
1993
+ return parseStrictIsoDateMs(candidate) !== null ? candidate : null;
1994
+ }
1995
+ function parseCsvDateWithFormat(raw, dateFormat) {
1996
+ const trimmed = raw.trim();
1997
+ if (!trimmed) return null;
1998
+ const isoMatch = /^(\d{4})[-/](\d{1,2})[-/](\d{1,2})(?:[T\s].*)?$/.exec(trimmed);
1999
+ const slashMatch = /^(\d{1,2})[/-](\d{1,2})[/-](\d{4})(?:\s.*)?$/.exec(trimmed);
2000
+ if (dateFormat === "YYYY-MM-DD") {
2001
+ if (!isoMatch) return null;
2002
+ return buildValidatedIsoDate(Number(isoMatch[1]), Number(isoMatch[2]), Number(isoMatch[3]));
2003
+ }
2004
+ if (dateFormat === "MM/DD/YYYY") {
2005
+ if (!slashMatch) return null;
2006
+ return buildValidatedIsoDate(Number(slashMatch[3]), Number(slashMatch[1]), Number(slashMatch[2]));
2007
+ }
2008
+ if (dateFormat === "DD/MM/YYYY") {
2009
+ if (!slashMatch) return null;
2010
+ return buildValidatedIsoDate(Number(slashMatch[3]), Number(slashMatch[2]), Number(slashMatch[1]));
2011
+ }
2012
+ if (isoMatch) {
2013
+ return buildValidatedIsoDate(Number(isoMatch[1]), Number(isoMatch[2]), Number(isoMatch[3]));
2014
+ }
2015
+ if (slashMatch) {
2016
+ const first = Number(slashMatch[1]);
2017
+ const second = Number(slashMatch[2]);
2018
+ const year = Number(slashMatch[3]);
2019
+ const [month, day] = first > 12 ? [second, first] : [first, second];
2020
+ return buildValidatedIsoDate(year, month, day);
2021
+ }
2022
+ return null;
2023
+ }
2024
+ function detectCsvDelimiter(csvText) {
2025
+ const cleaned = csvText.charCodeAt(0) === 65279 ? csvText.slice(1) : csvText;
2026
+ const candidates = [",", ";", " "];
2027
+ const rowCounts = [];
2028
+ let inQuotes = false;
2029
+ let hasRowChars = false;
2030
+ let counts = { ",": 0, ";": 0, " ": 0 };
2031
+ for (let i = 0; i < cleaned.length && rowCounts.length < 12; i++) {
2032
+ const ch = cleaned[i];
2033
+ if (inQuotes) {
2034
+ hasRowChars = true;
2035
+ if (ch === '"') {
2036
+ if (cleaned[i + 1] === '"') {
2037
+ i += 1;
2038
+ } else {
2039
+ inQuotes = false;
2040
+ }
2041
+ }
2042
+ continue;
2043
+ }
2044
+ if (ch === '"') {
2045
+ inQuotes = true;
2046
+ hasRowChars = true;
2047
+ } else if (ch === "\r" || ch === "\n") {
2048
+ if (ch === "\r" && cleaned[i + 1] === "\n") {
2049
+ i += 1;
2050
+ }
2051
+ if (hasRowChars) {
2052
+ rowCounts.push(counts);
2053
+ counts = { ",": 0, ";": 0, " ": 0 };
2054
+ hasRowChars = false;
2055
+ }
2056
+ } else {
2057
+ if (ch.trim().length > 0) hasRowChars = true;
2058
+ if (ch === "," || ch === ";" || ch === " ") {
2059
+ counts[ch] += 1;
2060
+ }
2061
+ }
2062
+ }
2063
+ if (hasRowChars && rowCounts.length < 12) {
2064
+ rowCounts.push(counts);
2065
+ }
2066
+ let bestDelim = ",";
2067
+ let bestScore = -1;
2068
+ for (const delim of candidates) {
2069
+ const nonZero = rowCounts.map((r) => r[delim]).filter((c) => c > 0);
2070
+ if (nonZero.length === 0) continue;
2071
+ const freq = /* @__PURE__ */ new Map();
2072
+ for (const c of nonZero) {
2073
+ freq.set(c, (freq.get(c) ?? 0) + 1);
2074
+ }
2075
+ let modalCount = 0;
2076
+ let modalFreq = 0;
2077
+ for (const [c, f] of freq.entries()) {
2078
+ if (f > modalFreq || f === modalFreq && c > modalCount) {
2079
+ modalCount = c;
2080
+ modalFreq = f;
2081
+ }
2082
+ }
2083
+ const score = modalFreq * 100 + modalCount * 10 + nonZero.length;
2084
+ if (score > bestScore) {
2085
+ bestScore = score;
2086
+ bestDelim = delim;
2087
+ }
2088
+ }
2089
+ return bestDelim;
2090
+ }
2091
+ function parseRawCsvTable(csvText) {
2092
+ const cleaned = csvText.charCodeAt(0) === 65279 ? csvText.slice(1) : csvText;
2093
+ const delimiter = detectCsvDelimiter(cleaned);
2094
+ const rows = [];
2095
+ let currentRow = [];
2096
+ let currentField = "";
2097
+ let inQuotes = false;
2098
+ for (let i = 0; i < cleaned.length; i++) {
2099
+ const ch = cleaned[i];
2100
+ if (inQuotes) {
2101
+ if (ch === '"') {
2102
+ if (cleaned[i + 1] === '"') {
2103
+ currentField += '"';
2104
+ i += 1;
2105
+ } else {
2106
+ inQuotes = false;
2107
+ }
2108
+ } else {
2109
+ currentField += ch;
2110
+ }
2111
+ continue;
2112
+ }
2113
+ if (ch === '"') {
2114
+ inQuotes = true;
2115
+ } else if (ch === delimiter) {
2116
+ currentRow.push(currentField);
2117
+ currentField = "";
2118
+ } else if (ch === "\r") {
2119
+ if (cleaned[i + 1] === "\n") {
2120
+ i += 1;
2121
+ }
2122
+ currentRow.push(currentField);
2123
+ rows.push(currentRow);
2124
+ currentRow = [];
2125
+ currentField = "";
2126
+ } else if (ch === "\n") {
2127
+ currentRow.push(currentField);
2128
+ rows.push(currentRow);
2129
+ currentRow = [];
2130
+ currentField = "";
2131
+ } else {
2132
+ currentField += ch;
2133
+ }
2134
+ }
2135
+ if (currentField.length > 0 || currentRow.length > 0) {
2136
+ currentRow.push(currentField);
2137
+ rows.push(currentRow);
2138
+ }
2139
+ return rows.filter((row) => row.some((cell) => cell.trim().length > 0));
2140
+ }
2141
+ function normalizeHeaderToken(raw) {
2142
+ return raw.normalize("NFD").replace(/[\u0300-\u036f]/g, "").trim().toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
2143
+ }
2144
+ var STRIPE_CSV_PRESET = {
2145
+ id: "preset-stripe-balance",
2146
+ name: "Stripe Balance / Payout CSV",
2147
+ currency: "USD",
2148
+ headerRowIndex: 0,
2149
+ dateFormat: "YYYY-MM-DD",
2150
+ flipSign: false,
2151
+ columns: {
2152
+ 0: "externalId",
2153
+ 1: "date",
2154
+ 2: "description",
2155
+ 3: "amount",
2156
+ 4: "category"
2157
+ },
2158
+ updatedAt: "2026-01-01T00:00:00.000Z"
2159
+ };
2160
+ var PAYPAL_CSV_PRESET = {
2161
+ id: "preset-paypal-activity",
2162
+ name: "PayPal Activity CSV",
2163
+ currency: "USD",
2164
+ headerRowIndex: 0,
2165
+ dateFormat: "MM/DD/YYYY",
2166
+ flipSign: false,
2167
+ columns: {
2168
+ 0: "date",
2169
+ 1: "ignore",
2170
+ 2: "description",
2171
+ 3: "category",
2172
+ 4: "ignore",
2173
+ 5: "ignore",
2174
+ 6: "ignore",
2175
+ 7: "amount",
2176
+ 8: "externalId",
2177
+ 9: "balance"
2178
+ },
2179
+ updatedAt: "2026-01-01T00:00:00.000Z"
2180
+ };
2181
+ function detectBuiltInFintechCsvPreset(headers) {
2182
+ const tokens = new Set(headers.map(normalizeHeaderToken).filter(Boolean));
2183
+ if (tokens.size === 0) return null;
2184
+ const isStripe = tokens.has("reporting category") || tokens.has("balance transaction id") || tokens.has("created utc") && tokens.has("net") && (tokens.has("gross") || tokens.has("fee") || tokens.has("available on utc") || tokens.has("source id") || tokens.has("transfer"));
2185
+ if (isStripe) return STRIPE_CSV_PRESET;
2186
+ const isPayPal = tokens.has("reference txn id") || tokens.has("transaction id") && tokens.has("balance impact") || tokens.has("gross") && tokens.has("fee") && tokens.has("net") && tokens.has("transaction id") && (tokens.has("name") || tokens.has("type") || tokens.has("status"));
2187
+ if (isPayPal) return PAYPAL_CSV_PRESET;
2188
+ return null;
2189
+ }
2190
+ function parseCsvAmountCents(raw) {
2191
+ let s = raw.trim();
2192
+ if (!s) return null;
2193
+ let negative = false;
2194
+ if (s.startsWith("(") && s.endsWith(")")) {
2195
+ negative = true;
2196
+ s = s.slice(1, -1).trim();
2197
+ }
2198
+ if (s.startsWith("-")) {
2199
+ negative = !negative;
2200
+ s = s.slice(1).trim();
2201
+ } else if (s.startsWith("+")) {
2202
+ s = s.slice(1).trim();
2203
+ }
2204
+ if (s.endsWith("-") && !s.startsWith("-")) {
2205
+ negative = !negative;
2206
+ s = s.slice(0, -1).trim();
2207
+ }
2208
+ s = s.replace(/(?:CAD|USD|\$|€|£)/gi, "").replace(/[\s\u00a0\u202f]/g, "");
2209
+ if (s.includes(",") && s.includes(".")) {
2210
+ const lastComma = s.lastIndexOf(",");
2211
+ const lastDot = s.lastIndexOf(".");
2212
+ if (lastComma > lastDot) {
2213
+ const after = s.slice(lastComma + 1);
2214
+ if (/^\d{1,2}$/.test(after)) {
2215
+ s = `${s.slice(0, lastComma).replace(/[.,]/g, "")}.${after}`;
2216
+ } else {
2217
+ s = s.replace(/[.,]/g, "");
2218
+ }
2219
+ } else {
2220
+ s = s.replace(/,/g, "");
2221
+ }
2222
+ } else if (s.includes(",")) {
2223
+ const lastComma = s.lastIndexOf(",");
2224
+ const after = s.slice(lastComma + 1);
2225
+ if (/^\d{1,2}$/.test(after)) {
2226
+ s = `${s.slice(0, lastComma).replace(/,/g, "")}.${after}`;
2227
+ } else {
2228
+ s = s.replace(/,/g, "");
2229
+ }
2230
+ }
2231
+ s = s.replace(/[^0-9.]/g, "");
2232
+ if (!s || !/^\d+(?:\.\d{1,2})?$/.test(s)) return null;
2233
+ const num = Number(s);
2234
+ if (!Number.isFinite(num)) return null;
2235
+ const cents = Math.round(num * 100);
2236
+ if (!Number.isSafeInteger(cents) || cents > 1e10) return null;
2237
+ if (cents === 0) return 0;
2238
+ return negative ? -cents : cents;
2239
+ }
2240
+ function sanitizeImportedTextCell(raw, maxLength) {
2241
+ const cleaned = raw.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, " ").replace(/<\/?script\b[^>]*>/gi, " ").replace(/[\u0000-\u001F\u007F\uFEFF\u200B-\u200D\u2060]/g, " ").replace(/\s+/g, " ").trim().slice(0, maxLength);
2242
+ if (!cleaned) return "";
2243
+ const isPlainNumber = /^-?\d+(?:\.\d+)?$/.test(cleaned);
2244
+ const startsFormula = /^[=+\-@]/.test(cleaned);
2245
+ if (!isPlainNumber && startsFormula) {
2246
+ return `'${cleaned}`.slice(0, maxLength);
2247
+ }
2248
+ return cleaned;
2249
+ }
2250
+ function applyCustomCsvTemplate(csvText, template) {
2251
+ const table = parseRawCsvTable(csvText);
2252
+ const headerIdx = Math.max(0, Math.floor(template.headerRowIndex || 0));
2253
+ if (table.length <= headerIdx + 1) {
2254
+ return {
2255
+ rows: [],
2256
+ skippedRowCount: 0,
2257
+ inflowCents: 0,
2258
+ outflowCents: 0,
2259
+ netCents: 0,
2260
+ finalRunningBalanceCents: null
2261
+ };
2262
+ }
2263
+ const findCol2 = (targetRole) => {
2264
+ for (const [colKey, role] of Object.entries(template.columns)) {
2265
+ if (role === targetRole) {
2266
+ const idx = Number(colKey);
2267
+ if (Number.isInteger(idx) && idx >= 0) return idx;
2268
+ }
2269
+ }
2270
+ return -1;
2271
+ };
2272
+ const dateIdx = findCol2("date");
2273
+ const descIdx = findCol2("description");
2274
+ const amountIdx = findCol2("amount");
2275
+ const debitIdx = findCol2("debit");
2276
+ const creditIdx = findCol2("credit");
2277
+ const balanceIdx = findCol2("balance");
2278
+ const categoryIdx = findCol2("category");
2279
+ const noteIdx = findCol2("note");
2280
+ const externalIdIdx = findCol2("externalId");
2281
+ const dataRowCount = table.length - (headerIdx + 1);
2282
+ if (dateIdx === -1 || amountIdx === -1 && debitIdx === -1 && creditIdx === -1) {
2283
+ return {
2284
+ rows: [],
2285
+ skippedRowCount: dataRowCount,
2286
+ inflowCents: 0,
2287
+ outflowCents: 0,
2288
+ netCents: 0,
2289
+ finalRunningBalanceCents: null
2290
+ };
2291
+ }
2292
+ const currency = normalizeCurrency(template.currency, "CAD");
2293
+ const rows = [];
2294
+ let skippedRowCount = 0;
2295
+ let inflowCents = 0;
2296
+ let outflowCents = 0;
2297
+ let finalRunningBalanceCents = null;
2298
+ for (let r = headerIdx + 1; r < table.length; r++) {
2299
+ const row = table[r];
2300
+ const date = parseCsvDateWithFormat(row[dateIdx] ?? "", template.dateFormat);
2301
+ if (!date) {
2302
+ skippedRowCount += 1;
2303
+ continue;
2304
+ }
2305
+ let amountCents = null;
2306
+ if (amountIdx !== -1) {
2307
+ amountCents = parseCsvAmountCents(row[amountIdx] ?? "");
2308
+ }
2309
+ if ((amountCents === null || amountCents === 0) && (debitIdx !== -1 || creditIdx !== -1)) {
2310
+ const debitVal = debitIdx !== -1 ? parseCsvAmountCents(row[debitIdx] ?? "") : null;
2311
+ const creditVal = creditIdx !== -1 ? parseCsvAmountCents(row[creditIdx] ?? "") : null;
2312
+ const net = (creditVal !== null ? Math.abs(creditVal) : 0) - (debitVal !== null ? Math.abs(debitVal) : 0);
2313
+ if (net !== 0) amountCents = net;
2314
+ }
2315
+ if (amountCents === null || amountCents === 0) {
2316
+ skippedRowCount += 1;
2317
+ continue;
2318
+ }
2319
+ if (template.flipSign) {
2320
+ amountCents = -amountCents;
2321
+ }
2322
+ if (amountCents > 0) {
2323
+ inflowCents += amountCents;
2324
+ } else {
2325
+ outflowCents += Math.abs(amountCents);
2326
+ }
2327
+ let balanceCents;
2328
+ if (balanceIdx !== -1) {
2329
+ const parsedBal = parseCsvAmountCents(row[balanceIdx] ?? "");
2330
+ if (parsedBal !== null) {
2331
+ balanceCents = parsedBal;
2332
+ finalRunningBalanceCents = parsedBal;
2333
+ }
2334
+ }
2335
+ const primaryDesc = descIdx !== -1 ? sanitizeImportedTextCell(row[descIdx] ?? "", 300) : "";
2336
+ const category = categoryIdx !== -1 ? sanitizeImportedTextCell(row[categoryIdx] ?? "", 120) : "";
2337
+ const note = noteIdx !== -1 && noteIdx !== descIdx ? sanitizeImportedTextCell(row[noteIdx] ?? "", 200) : "";
2338
+ const externalId = externalIdIdx !== -1 ? sanitizeImportedTextCell(row[externalIdIdx] ?? "", 120) : "";
2339
+ const description = primaryDesc || category || "CSV Transaction";
2340
+ rows.push({
2341
+ date,
2342
+ description,
2343
+ amountCents,
2344
+ currency,
2345
+ ...balanceCents !== void 0 ? {
2346
+ balanceCents,
2347
+ balance: Number((balanceCents / 100).toFixed(2))
2348
+ } : {},
2349
+ ...category ? { category } : {},
2350
+ ...note ? { note } : {},
2351
+ ...externalId ? { externalId } : {}
2352
+ });
2353
+ }
2354
+ return {
2355
+ rows,
2356
+ skippedRowCount,
2357
+ inflowCents,
2358
+ outflowCents,
2359
+ netCents: inflowCents - outflowCents,
2360
+ finalRunningBalanceCents
2361
+ };
2362
+ }
2363
+
2364
+ // src/api-worker/routes/csv.ts
2365
+ var DATE_FORMATS = ["auto", "YYYY-MM-DD", "MM/DD/YYYY", "DD/MM/YYYY"];
2366
+ var PRESET_ALIASES = {
2367
+ xero: { date: ["date"], description: ["description", "payee", "reference"], amount: ["amount"], debit: [], credit: [] },
2368
+ qbo_csv: { date: ["date"], description: ["description", "memo"], amount: ["amount"], debit: ["debit", "debit amount"], credit: ["credit", "credit amount"] },
2369
+ wave: { date: ["transaction date", "date"], description: ["transaction description", "description"], amount: ["amount (one column)", "amount"], debit: ["debit amount (two columns)", "debit"], credit: ["credit amount (two columns)", "credit"] },
2370
+ sage50: {
2371
+ date: ["date"],
2372
+ description: ["comment", "source", "description"],
2373
+ amount: ["amount"],
2374
+ debit: ["debit", "debits", "debit amount", "debit amount (cad)", "debit amount (usd)"],
2375
+ credit: ["credit", "credits", "credit amount", "credit amount (cad)", "credit amount (usd)"]
2376
+ },
2377
+ freshbooks: { date: ["date"], description: ["description", "vendor"], amount: ["amount"], debit: [], credit: [] },
2378
+ zoho: { date: ["transaction date", "date"], description: ["description", "transaction details", "payee"], amount: ["amount"], debit: ["withdrawals", "debit"], credit: ["deposits", "credit"] },
2379
+ wise: {
2380
+ date: ["date", "created on"],
2381
+ description: ["description", "payment reference", "payee name", "merchant name", "payer name"],
2382
+ amount: ["amount", "source amount", "target amount"],
2383
+ debit: ["debit", "debit amount"],
2384
+ credit: ["credit", "credit amount"]
2385
+ },
2386
+ paypal: {
2387
+ date: ["date", "time"],
2388
+ description: ["description", "name", "item title", "memo"],
2389
+ amount: ["gross", "net", "amount"],
2390
+ debit: [],
2391
+ credit: []
2392
+ }
2393
+ };
2394
+ var GENERIC = {
2395
+ date: ["date", "transaction date", "posted date", "posting date", "created on"],
2396
+ description: ["description", "transaction description", "details", "memo", "payee", "name", "item title", "payment reference", "merchant name"],
2397
+ amount: ["amount", "amount (one column)", "gross", "source amount", "target amount", "net"],
2398
+ debit: ["debit", "withdrawals", "debit amount", "debit amount (cad)", "debit amount (usd)", "debits"],
2399
+ credit: ["credit", "deposits", "credit amount", "credit amount (cad)", "credit amount (usd)", "credits"]
2400
+ };
2401
+ function parseAmountToCents(raw, decimalSep = ".", thousandsSep = ",") {
2402
+ let s = raw.trim();
2403
+ if (!s) return null;
2404
+ let neg = false;
2405
+ if (/^\(.*\)$/.test(s)) {
2406
+ neg = true;
2407
+ s = s.slice(1, -1);
2408
+ }
2409
+ if (/-\s*$/.test(s)) {
2410
+ neg = true;
2411
+ s = s.replace(/-\s*$/, "");
2412
+ }
2413
+ s = s.replace(/[A-Za-z$€£¥\s\u00a0]/g, "");
2414
+ if (s.startsWith("-")) {
2415
+ neg = !neg;
2416
+ s = s.slice(1);
2417
+ } else if (s.startsWith("+")) {
2418
+ s = s.slice(1);
2419
+ }
2420
+ if (thousandsSep) s = s.split(thousandsSep).join("");
2421
+ if (decimalSep !== ".") s = s.split(decimalSep).join(".");
2422
+ if (!/^\d*\.?\d*$/.test(s) || s === "" || s === ".") return null;
2423
+ const [whole = "0", frac = ""] = s.split(".");
2424
+ const cents = Number(whole || "0") * 100 + Number((frac + "00").slice(0, 2)) + (frac.length > 2 && Number(frac[2]) >= 5 ? 1 : 0);
2425
+ if (!Number.isSafeInteger(cents)) return null;
2426
+ return neg ? -cents : cents;
2427
+ }
2428
+ function findCol(headers, names) {
2429
+ for (const n of names) {
2430
+ const i = headers.indexOf(n);
2431
+ if (i >= 0) return i;
2432
+ }
2433
+ return -1;
2434
+ }
2435
+ function mapByAliases(table, aliases, dateFormat, flip) {
2436
+ const headers = (table[0] ?? []).map((h) => h.replace(/\*/g, "").trim().toLowerCase());
2437
+ const dateIdx = findCol(headers, aliases.date);
2438
+ const descIdx = findCol(headers, aliases.description);
2439
+ const amtIdx = findCol(headers, aliases.amount);
2440
+ const debIdx = findCol(headers, aliases.debit);
2441
+ const creIdx = findCol(headers, aliases.credit);
2442
+ if (dateIdx < 0 || amtIdx < 0 && debIdx < 0 && creIdx < 0) return null;
2443
+ const rows = [];
2444
+ let skipped = 0;
2445
+ for (let r = 1; r < table.length; r++) {
2446
+ const row = table[r];
2447
+ if (row.every((c) => !c.trim())) continue;
2448
+ const date = parseCsvDateWithFormat(row[dateIdx] ?? "", dateFormat);
2449
+ let cents = null;
2450
+ if (amtIdx >= 0) cents = parseAmountToCents(row[amtIdx] ?? "");
2451
+ if (cents === null && (debIdx >= 0 || creIdx >= 0)) {
2452
+ const d = debIdx >= 0 ? parseAmountToCents(row[debIdx] ?? "") : null;
2453
+ const c = creIdx >= 0 ? parseAmountToCents(row[creIdx] ?? "") : null;
2454
+ if (d !== null || c !== null) cents = (c ?? 0) - Math.abs(d ?? 0);
2455
+ }
2456
+ if (!date || cents === null) {
2457
+ skipped++;
2458
+ continue;
2459
+ }
2460
+ rows.push({ date, description: (descIdx >= 0 ? row[descIdx] : "")?.trim() ?? "", amountCents: flip ? -cents : cents });
2461
+ }
2462
+ return { rows, skippedRowCount: skipped };
2463
+ }
2464
+ function validateSchema(raw) {
2465
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { ok: false, why: "customSchema must be an object." };
2466
+ const s = raw;
2467
+ const colOk = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0 && v < 1e3;
2468
+ if (!colOk(s.dateColumn)) return { ok: false, why: "dateColumn must be a non-negative integer." };
2469
+ if (!Array.isArray(s.descriptionColumns) || !s.descriptionColumns.every(colOk)) return { ok: false, why: "descriptionColumns must be an array of column indexes." };
2470
+ if (s.amountMode !== "single_signed" && s.amountMode !== "split_debit_credit") return { ok: false, why: "amountMode must be single_signed or split_debit_credit." };
2471
+ if (s.amountMode === "single_signed" && !colOk(s.amountColumn)) return { ok: false, why: "amountColumn is required for single_signed." };
2472
+ if (s.amountMode === "split_debit_credit" && !colOk(s.debitColumn) && !colOk(s.creditColumn)) return { ok: false, why: "debitColumn or creditColumn is required for split_debit_credit." };
2473
+ const dateFormat = s.dateFormat ?? "auto";
2474
+ if (!DATE_FORMATS.includes(dateFormat)) return { ok: false, why: "dateFormat is not supported." };
2475
+ const skip = s.skipHeaderRows === void 0 ? 1 : s.skipHeaderRows;
2476
+ if (typeof skip !== "number" || !Number.isInteger(skip) || skip < 0 || skip > 1e3) return { ok: false, why: "skipHeaderRows must be an integer 0..1000." };
2477
+ const dec = typeof s.decimalSeparator === "string" && s.decimalSeparator ? s.decimalSeparator : ".";
2478
+ const th = typeof s.thousandsSeparator === "string" ? s.thousandsSeparator : ",";
2479
+ if (dec.length !== 1 || th.length > 1 || dec === th) return { ok: false, why: "decimalSeparator/thousandsSeparator are invalid." };
2480
+ return {
2481
+ ok: true,
2482
+ schema: {
2483
+ encoding: typeof s.encoding === "string" ? s.encoding : void 0,
2484
+ delimiter: typeof s.delimiter === "string" ? s.delimiter : void 0,
2485
+ skipHeaderRows: skip,
2486
+ dateColumn: s.dateColumn,
2487
+ dateFormat,
2488
+ descriptionColumns: s.descriptionColumns,
2489
+ amountMode: s.amountMode,
2490
+ amountColumn: colOk(s.amountColumn) ? s.amountColumn : void 0,
2491
+ debitColumn: colOk(s.debitColumn) ? s.debitColumn : void 0,
2492
+ creditColumn: colOk(s.creditColumn) ? s.creditColumn : void 0,
2493
+ decimalSeparator: dec,
2494
+ thousandsSeparator: th
2495
+ }
2496
+ };
2497
+ }
2498
+ function applySchema(table, sc) {
2499
+ const rows = [];
2500
+ let skipped = 0;
2501
+ for (let r = sc.skipHeaderRows; r < table.length; r++) {
2502
+ const row = table[r];
2503
+ if (row.every((c) => !c.trim())) continue;
2504
+ const date = parseCsvDateWithFormat(row[sc.dateColumn] ?? "", sc.dateFormat);
2505
+ let cents;
2506
+ if (sc.amountMode === "single_signed") {
2507
+ cents = parseAmountToCents(row[sc.amountColumn] ?? "", sc.decimalSeparator, sc.thousandsSeparator);
2508
+ } else {
2509
+ const d = sc.debitColumn !== void 0 ? parseAmountToCents(row[sc.debitColumn] ?? "", sc.decimalSeparator, sc.thousandsSeparator) : null;
2510
+ const c = sc.creditColumn !== void 0 ? parseAmountToCents(row[sc.creditColumn] ?? "", sc.decimalSeparator, sc.thousandsSeparator) : null;
2511
+ cents = d === null && c === null ? null : Math.abs(c ?? 0) - Math.abs(d ?? 0);
2512
+ }
2513
+ if (!date || cents === null) {
2514
+ skipped++;
2515
+ continue;
2516
+ }
2517
+ const description = sc.descriptionColumns.map((i) => (row[i] ?? "").trim()).filter(Boolean).join(" ");
2518
+ rows.push({ date, description, amountCents: cents });
2519
+ }
2520
+ return { rows, skippedRowCount: skipped };
2521
+ }
2522
+ function csvCell(v) {
2523
+ const safe = /^[=+\-@]/.test(v) ? `'${v}` : v;
2524
+ return /[",\r\n]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe;
2525
+ }
2526
+ function major(c) {
2527
+ return `${c < 0 ? "-" : ""}${Math.floor(Math.abs(c) / 100)}.${String(Math.abs(c) % 100).padStart(2, "0")}`;
2528
+ }
2529
+ function render(target, rows) {
2530
+ const parsed = rows.map((r) => ({ date: r.date, description: r.description, amount: r.amountCents / 100 }));
2531
+ let content;
2532
+ switch (target) {
2533
+ case "xero_csv":
2534
+ content = toXeroCsv(parsed);
2535
+ break;
2536
+ case "wave_csv":
2537
+ content = toWaveCsv(parsed);
2538
+ break;
2539
+ case "qbo_csv":
2540
+ content = ["Date,Description,Credit,Debit", ...rows.map((r) => [r.date, csvCell(r.description), r.amountCents > 0 ? major(r.amountCents) : "", r.amountCents < 0 ? major(-r.amountCents) : ""].join(","))].join("\r\n") + "\r\n";
2541
+ break;
2542
+ case "sage50_csv":
2543
+ content = ["Date,Reference,Description,Amount", ...rows.map((r, i) => [r.date, String(i + 1), csvCell(r.description), major(r.amountCents)].join(","))].join("\r\n") + "\r\n";
2544
+ break;
2545
+ default:
2546
+ return null;
2547
+ }
2548
+ return { content, filename: `exactrows-normalized-${sha256Hex(content).slice(0, 8)}.csv`, mimeType: "text/csv; charset=utf-8" };
2549
+ }
2550
+ function decodeBase64(b64) {
2551
+ try {
2552
+ const bin = atob(b64.replace(/\s+/g, ""));
2553
+ const out = new Uint8Array(bin.length);
2554
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
2555
+ return out;
2556
+ } catch {
2557
+ return null;
2558
+ }
2559
+ }
2560
+ var ENCODINGS = /* @__PURE__ */ new Set(["utf-8", "utf8", "windows-1252", "cp1252", "iso-8859-1", "latin1", "utf-16le"]);
2561
+ async function handleCsv(request, env, ctx = {}) {
2562
+ const url = ctx.url ?? new URL(request.url);
2563
+ const path = (ctx.path ?? url.pathname).replace(/\/+$/, "");
2564
+ if (path !== "/v1/csv/normalize") return null;
2565
+ if (request.method !== "POST") {
2566
+ return new Response(
2567
+ JSON.stringify({ ok: false, error: { code: "METHOD_NOT_ALLOWED", message: "Use POST.", retryable: false }, receipt: null }),
2568
+ { status: 405, headers: { "content-type": "application/json", allow: "POST" } }
2569
+ );
2570
+ }
2571
+ const parsed = await readJsonBody(request);
2572
+ if (!parsed.ok) return parsed.response;
2573
+ const body = parsed.body;
2574
+ const lang = pickLang(body, ctx, url);
2575
+ if (typeof body.csvBase64 !== "string") {
2576
+ return apiError(400, "MISSING_CSV", "csvBase64 (string) is required.", lang === "fr" ? "csvBase64 (cha\xEEne) est requis." : void 0);
2577
+ }
2578
+ const bytes = decodeBase64(body.csvBase64);
2579
+ if (!bytes) return apiError(400, "INVALID_BASE64", "csvBase64 is not valid base64.");
2580
+ if (bytes.byteLength > MAX_BODY_BYTES2) return apiError(413, "PAYLOAD_TOO_LARGE", "CSV exceeds 10 MiB.");
2581
+ const target = typeof body.targetFormat === "string" ? body.targetFormat : "json";
2582
+ if (!["json", "qbo_csv", "xero_csv", "wave_csv", "sage50_csv"].includes(target)) {
2583
+ return apiError(400, "INVALID_TARGET_FORMAT", "targetFormat must be json, qbo_csv, xero_csv, wave_csv or sage50_csv.");
2584
+ }
2585
+ const preset = typeof body.preset === "string" ? body.preset : void 0;
2586
+ const known = ["xero", "qbo_csv", "wave", "sage50", "freshbooks", "zoho", "stripe", "paypal", "wise", "custom_schema_v1"];
2587
+ if (preset !== void 0 && !known.includes(preset)) {
2588
+ return apiError(400, "UNKNOWN_PRESET", `preset must be one of ${known.join(", ")}.`);
2589
+ }
2590
+ let schema = null;
2591
+ if (preset === "custom_schema_v1" || preset === void 0 && body.customSchema !== void 0) {
2592
+ const v = validateSchema(body.customSchema);
2593
+ if (!v.ok) return apiError(400, "INVALID_CUSTOM_SCHEMA", v.why, lang === "fr" ? "customSchema invalide." : void 0);
2594
+ schema = v.schema;
2595
+ }
2596
+ const encoding = (schema?.encoding ?? (typeof body.encoding === "string" ? body.encoding : "utf-8")).toLowerCase();
2597
+ if (!ENCODINGS.has(encoding)) return apiError(400, "UNSUPPORTED_ENCODING", "Unsupported encoding.");
2598
+ let text = new TextDecoder(encoding === "utf8" ? "utf-8" : encoding === "cp1252" ? "windows-1252" : encoding === "latin1" ? "iso-8859-1" : encoding).decode(bytes);
2599
+ if (text.charCodeAt(0) === 65279) text = text.slice(1);
2600
+ const table = parseRawCsvTable(text);
2601
+ let result = null;
2602
+ let usedPreset = preset ?? "auto";
2603
+ if (schema) {
2604
+ result = applySchema(table, schema);
2605
+ } else if (preset === "stripe" || preset === "paypal") {
2606
+ let handled = false;
2607
+ try {
2608
+ const r = applyCustomCsvTemplate(text, preset === "stripe" ? STRIPE_CSV_PRESET : PAYPAL_CSV_PRESET);
2609
+ if (r && r.rows.length > 0) {
2610
+ result = { rows: r.rows.map((x) => ({ date: x.date, description: x.description, amountCents: x.amountCents })), skippedRowCount: r.skippedRowCount };
2611
+ handled = true;
2612
+ }
2613
+ } catch {
2614
+ handled = false;
2615
+ }
2616
+ if (!handled && preset === "paypal") {
2617
+ result = mapByAliases(table, PRESET_ALIASES.paypal, "auto", false);
2618
+ }
2619
+ } else if (preset) {
2620
+ result = mapByAliases(table, PRESET_ALIASES[preset], "auto", false);
2621
+ } else {
2622
+ const detected = detectBuiltInFintechCsvPreset(table[0] ?? []);
2623
+ if (detected) {
2624
+ usedPreset = detected === STRIPE_CSV_PRESET ? "stripe" : "paypal";
2625
+ const r = applyCustomCsvTemplate(text, detected);
2626
+ result = { rows: r.rows.map((x) => ({ date: x.date, description: x.description, amountCents: x.amountCents })), skippedRowCount: r.skippedRowCount };
2627
+ } else {
2628
+ result = mapByAliases(table, GENERIC, "auto", false);
2629
+ }
2630
+ }
2631
+ if (!result) {
2632
+ return apiError(
2633
+ 422,
2634
+ "CSV_MAPPING_FAILED",
2635
+ "Could not map date and amount columns; supply a preset or customSchema.",
2636
+ lang === "fr" ? "Impossible de rep\xE9rer les colonnes de date et de montant; fournissez un pr\xE9r\xE9glage ou un customSchema." : void 0
2637
+ );
2638
+ }
2639
+ const rows = result.rows;
2640
+ const amounts = rows.map((r) => r.amountCents);
2641
+ const currency = typeof body.currency === "string" && /^[A-Za-z]{3}$/.test(body.currency) ? body.currency.toUpperCase() : "CAD";
2642
+ const math = mathFromTransactions(currency, 0, null, amounts);
2643
+ const rendered = target === "json" ? null : render(target, rows);
2644
+ const out = {
2645
+ preset: usedPreset,
2646
+ transactionCount: rows.length,
2647
+ skippedRowCount: result.skippedRowCount,
2648
+ inflowCents: math.creditsCents,
2649
+ outflowCents: math.debitsCents,
2650
+ netCents: math.creditsCents - math.debitsCents,
2651
+ rows,
2652
+ ...rendered ?? {}
2653
+ };
2654
+ const receipt = await issueReceipt(env, ctx, "/v1/csv/normalize", bytes, out, math);
2655
+ return apiJson({ ok: true, ...out, receipt }, 200, receiptHeaders(receipt, ctx));
2656
+ }
2657
+
2658
+ // packages/exactrows-mcp/src/local-engine.ts
2659
+ var TOOL_ROUTES = {
2660
+ exactrows_qbo_validate: "/v1/qbo/validate",
2661
+ exactrows_qbo_repair: "/v1/qbo/repair",
2662
+ exactrows_qbo_generate: "/v1/qbo/generate",
2663
+ exactrows_qbo_diff_dedupe: "/v1/qbo/diff-dedupe",
2664
+ exactrows_reconcile_verify: "/v1/reconcile/verify",
2665
+ exactrows_csv_normalize: "/v1/csv/normalize"
2666
+ };
2667
+ var TOOL_NAMES = [...Object.keys(TOOL_ROUTES), "exactrows_verify_receipt"];
2668
+ async function runLocalTool(name, args, env = {}) {
2669
+ if (name === "exactrows_verify_receipt") {
2670
+ const receipt = args.receipt ?? args;
2671
+ let valid = false;
2672
+ try {
2673
+ valid = await verifyReceipt(receipt, env);
2674
+ } catch {
2675
+ valid = false;
2676
+ }
2677
+ return { ok: true, valid };
2678
+ }
2679
+ const path = TOOL_ROUTES[name];
2680
+ if (!path) throw new Error(`Unknown tool: ${name}`);
2681
+ const request = new Request(`http://local.exactrows.invalid${path}`, {
2682
+ method: "POST",
2683
+ headers: { "content-type": "application/json" },
2684
+ body: JSON.stringify(args ?? {})
2685
+ });
2686
+ const ctx = { path };
2687
+ const res = await handleQbo(request.clone(), env, ctx) ?? await handleReconcile(request.clone(), env, ctx) ?? await handleCsv(request, env, ctx);
2688
+ if (!res) throw new Error(`No local handler for ${path}`);
2689
+ return res.json();
2690
+ }
2691
+
2692
+ // packages/exactrows-mcp/src/license-grace.ts
2693
+ var DAY_MS = 864e5;
2694
+ var ACTIVE_OFFLINE_DAYS = 7;
2695
+ var GRACE_DAYS = 30;
2696
+ var CLOCK_SKEW_MS = 5 * 60 * 1e3;
2697
+ function b64ToBytes2(s) {
2698
+ const n = s.replace(/-/g, "+").replace(/_/g, "/");
2699
+ const bin = atob(n + "=".repeat((4 - n.length % 4) % 4));
2700
+ const out = new Uint8Array(bin.length);
2701
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
2702
+ return out;
2703
+ }
2704
+ var SPKI_PREFIX = new Uint8Array([48, 42, 48, 5, 6, 3, 43, 101, 112, 3, 33, 0]);
2705
+ async function importPublic2(key) {
2706
+ let bytes = b64ToBytes2(key.replace(/-----(BEGIN|END)[^-]+-----/g, "").replace(/\s+/g, ""));
2707
+ if (bytes.length === 32) {
2708
+ const o = new Uint8Array(44);
2709
+ o.set(SPKI_PREFIX);
2710
+ o.set(bytes, 12);
2711
+ bytes = o;
2712
+ }
2713
+ return crypto.subtle.importKey("spki", bytes, { name: "Ed25519" }, false, ["verify"]);
2714
+ }
2715
+ async function verifyLicenseToken(token, publicKey, opts = {}) {
2716
+ const bad = (reason) => ({ status: "invalid", ok: false, daysOffline: 0, graceDaysRemaining: 0, reason });
2717
+ const parts = (token ?? "").trim().split(".");
2718
+ if (parts.length !== 2 || !parts[0] || !parts[1]) return bad("malformed_token");
2719
+ let payload;
2720
+ try {
2721
+ const key = await importPublic2(publicKey);
2722
+ const valid = await crypto.subtle.verify(
2723
+ { name: "Ed25519" },
2724
+ key,
2725
+ b64ToBytes2(parts[1]),
2726
+ new TextEncoder().encode(parts[0])
2727
+ );
2728
+ if (!valid) return bad("signature_mismatch");
2729
+ payload = JSON.parse(new TextDecoder().decode(b64ToBytes2(parts[0])));
2730
+ } catch {
2731
+ return bad("signature_mismatch");
2732
+ }
2733
+ const now = opts.now ?? Date.now();
2734
+ if (typeof now !== "number" || Number.isNaN(now) || now < 0) {
2735
+ return bad("invalid_time");
2736
+ }
2737
+ if (!payload || typeof payload !== "object" || !payload.issuedAt || typeof payload.issuedAt !== "string") {
2738
+ return bad("invalid_issued_at");
2739
+ }
2740
+ const issuedTime = Date.parse(payload.issuedAt);
2741
+ if (Number.isNaN(issuedTime) || issuedTime < 0) {
2742
+ return bad("invalid_issued_at");
2743
+ }
2744
+ if (issuedTime > now + CLOCK_SKEW_MS) {
2745
+ return bad("issued_in_future");
2746
+ }
2747
+ if (payload.expiresAt !== void 0) {
2748
+ if (typeof payload.expiresAt !== "string") return bad("invalid_expires_at");
2749
+ const expTime = Date.parse(payload.expiresAt);
2750
+ if (Number.isNaN(expTime) || expTime < 0) {
2751
+ return bad("invalid_expires_at");
2752
+ }
2753
+ if (expTime < issuedTime) {
2754
+ return bad("expires_before_issued");
2755
+ }
2756
+ if (expTime < now) {
2757
+ return { status: "expired", ok: false, payload, daysOffline: 0, graceDaysRemaining: 0, reason: "license_expired" };
2758
+ }
2759
+ }
2760
+ if (opts.lastOnlineAt == null) {
2761
+ return { status: "active", ok: true, payload, daysOffline: 0, graceDaysRemaining: GRACE_DAYS };
2762
+ }
2763
+ if (typeof opts.lastOnlineAt !== "number" || Number.isNaN(opts.lastOnlineAt) || opts.lastOnlineAt < 0) {
2764
+ return bad("invalid_last_online");
2765
+ }
2766
+ if (opts.lastOnlineAt > now + CLOCK_SKEW_MS) {
2767
+ return bad("last_online_in_future");
2768
+ }
2769
+ const effectiveLastOnline = Math.min(opts.lastOnlineAt, now);
2770
+ const daysOffline = Math.max(0, Math.floor((now - effectiveLastOnline) / DAY_MS));
2771
+ const remaining = Math.max(0, GRACE_DAYS - daysOffline);
2772
+ if (daysOffline > GRACE_DAYS) {
2773
+ return { status: "expired", ok: false, payload, daysOffline, graceDaysRemaining: 0, reason: "grace_window_exceeded" };
2774
+ }
2775
+ if (daysOffline > ACTIVE_OFFLINE_DAYS) {
2776
+ return {
2777
+ status: "grace",
2778
+ ok: true,
2779
+ payload,
2780
+ daysOffline,
2781
+ graceDaysRemaining: remaining,
2782
+ warning: `Offline for ${daysOffline} days; reconnect within ${remaining} days to keep the license active.`
2783
+ };
2784
+ }
2785
+ return { status: "active", ok: true, payload, daysOffline, graceDaysRemaining: remaining };
2786
+ }
2787
+
2788
+ // packages/exactrows-mcp/src/server.ts
2789
+ var PROTOCOL_VERSION = "2025-03-26";
2790
+ var SERVER_INFO = { name: "@exactrows/mcp", version: "0.2.0" };
2791
+ var obj = (properties = {}) => ({ type: "object", properties, additionalProperties: true });
2792
+ var DESCS = {
2793
+ exactrows_qbo_validate: "Validate a .QBO/.OFX file (qboText or qboBase64).",
2794
+ exactrows_qbo_repair: "Repair a .QBO/.OFX file with FITID v1 rebuild; returns signed receipt.",
2795
+ exactrows_qbo_generate: "Generate deterministic .qbo/.ofx from transactions.",
2796
+ exactrows_qbo_diff_dedupe: "Detect overlap/duplicates across statements.",
2797
+ exactrows_reconcile_verify: "Verify Opening + Credits - Debits = Closing in integer cents.",
2798
+ exactrows_csv_normalize: "Normalize a CSV (csvBase64) via preset or custom schema.",
2799
+ exactrows_verify_receipt: "Verify an ExactRows-Receipt-v1 Ed25519 signature."
2800
+ };
2801
+ var INPUTS = {
2802
+ exactrows_qbo_validate: obj({ qboText: { type: "string" }, qboBase64: { type: "string" }, lang: { type: "string" } }),
2803
+ exactrows_qbo_repair: obj({ qboText: { type: "string" }, qboBase64: { type: "string" }, options: { type: "object" } }),
2804
+ exactrows_qbo_generate: obj({ format: { type: "string" }, currency: { type: "string" }, transactions: { type: "array" } }),
2805
+ exactrows_qbo_diff_dedupe: obj({ transactions: { type: "array" } }),
2806
+ exactrows_reconcile_verify: obj({ openingCents: { type: "integer" }, closingCents: { type: "integer" }, transactions: { type: "array" } }),
2807
+ exactrows_csv_normalize: obj({ csvBase64: { type: "string" }, preset: { type: "string" }, targetFormat: { type: "string" } }),
2808
+ exactrows_verify_receipt: obj({ receipt: { type: "object" } })
2809
+ };
2810
+ var TOOLS = [...Object.keys(TOOL_ROUTES), "exactrows_verify_receipt"].map((name) => ({
2811
+ name,
2812
+ description: DESCS[name],
2813
+ inputSchema: INPUTS[name]
2814
+ }));
2815
+ var rpcErr = (id, code, message) => ({
2816
+ jsonrpc: "2.0",
2817
+ id: id === void 0 ? null : id,
2818
+ error: { code, message }
2819
+ });
2820
+ async function callTool(name, args, opts) {
2821
+ if (opts.localWasm) {
2822
+ const lic = await verifyLicenseToken(opts.licenseToken ?? "", opts.licensePublicKey ?? "", { now: opts.now, lastOnlineAt: opts.lastOnlineAt });
2823
+ if (!lic.ok) throw Object.assign(new Error(`License rejected: ${lic.reason}`), { licenseStatus: lic.status });
2824
+ const result = await runLocalTool(name, args, opts.env ?? {});
2825
+ return lic.warning && result && typeof result === "object" ? { ...result, licenseWarning: lic.warning } : result;
2826
+ }
2827
+ const route = name === "exactrows_verify_receipt" ? "/v1/receipts/verify" : TOOL_ROUTES[name];
2828
+ const res = await fetch(`${opts.apiBase ?? "https://api.exactrows.com"}${route}`, {
2829
+ method: "POST",
2830
+ headers: { "content-type": "application/json", authorization: `Bearer ${opts.apiKey ?? ""}` },
2831
+ body: JSON.stringify(args)
2832
+ });
2833
+ return res.json();
2834
+ }
2835
+ async function handleRpc(msg, opts = {}) {
2836
+ if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0" || typeof msg.method !== "string") {
2837
+ return rpcErr(msg && typeof msg === "object" ? msg.id : null, -32600, "Invalid Request");
2838
+ }
2839
+ const isNotification = msg.id === void 0;
2840
+ switch (msg.method) {
2841
+ case "initialize":
2842
+ return {
2843
+ jsonrpc: "2.0",
2844
+ id: msg.id === void 0 ? null : msg.id,
2845
+ result: { protocolVersion: PROTOCOL_VERSION, capabilities: { tools: { listChanged: false } }, serverInfo: SERVER_INFO }
2846
+ };
2847
+ case "ping":
2848
+ return { jsonrpc: "2.0", id: msg.id === void 0 ? null : msg.id, result: {} };
2849
+ case "tools/list":
2850
+ return { jsonrpc: "2.0", id: msg.id === void 0 ? null : msg.id, result: { tools: TOOLS } };
2851
+ case "tools/call": {
2852
+ if (!msg.params || typeof msg.params !== "object" || Array.isArray(msg.params)) {
2853
+ return rpcErr(msg.id, -32602, "Invalid params: params object required");
2854
+ }
2855
+ const name = msg.params?.name;
2856
+ if (typeof name !== "string" || !name) {
2857
+ return rpcErr(msg.id, -32602, "Invalid params: tool name required");
2858
+ }
2859
+ if (!TOOLS.some((t) => t.name === name)) {
2860
+ return rpcErr(msg.id, -32601, `Unknown tool: ${name}`);
2861
+ }
2862
+ if (msg.params.arguments !== void 0 && (typeof msg.params.arguments !== "object" || msg.params.arguments === null || Array.isArray(msg.params.arguments))) {
2863
+ return rpcErr(msg.id, -32602, "Invalid params: arguments must be an object");
2864
+ }
2865
+ try {
2866
+ const out = await callTool(name, msg.params?.arguments ?? {}, opts);
2867
+ const isError = !out || typeof out !== "object" || out.ok === false;
2868
+ return {
2869
+ jsonrpc: "2.0",
2870
+ id: msg.id === void 0 ? null : msg.id,
2871
+ result: { content: [{ type: "text", text: JSON.stringify(out) }], structuredContent: out, isError }
2872
+ };
2873
+ } catch (e) {
2874
+ return {
2875
+ jsonrpc: "2.0",
2876
+ id: msg.id === void 0 ? null : msg.id,
2877
+ result: { content: [{ type: "text", text: e.message }], isError: true }
2878
+ };
2879
+ }
2880
+ }
2881
+ default:
2882
+ if (isNotification || msg.method.startsWith("notifications/")) return null;
2883
+ return rpcErr(msg.id, -32601, `Method not found: ${msg.method}`);
2884
+ }
2885
+ }
2886
+ async function handleRpcPayload(payload, opts = {}) {
2887
+ if (Array.isArray(payload)) {
2888
+ const out = (await Promise.all(payload.map((m) => handleRpc(m, opts)))).filter((r) => r !== null);
2889
+ return out.length ? out : null;
2890
+ }
2891
+ return handleRpc(payload, opts);
2892
+ }
2893
+ var CORS_HEADERS = {
2894
+ "access-control-allow-origin": "*",
2895
+ "access-control-allow-methods": "POST, GET, OPTIONS",
2896
+ "access-control-allow-headers": "Content-Type, Mcp-Session-Id, Authorization",
2897
+ "access-control-expose-headers": "Mcp-Session-Id"
2898
+ };
2899
+ function createHttpServer(opts = {}) {
2900
+ return createServer((req, res) => {
2901
+ const rawSessionId = req.headers["mcp-session-id"];
2902
+ const sessionId = typeof rawSessionId === "string" && rawSessionId.trim() ? rawSessionId.trim() : typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : void 0;
2903
+ const send = (status, body) => {
2904
+ res.writeHead(status, {
2905
+ ...CORS_HEADERS,
2906
+ ...sessionId ? { "mcp-session-id": sessionId } : {},
2907
+ "content-type": "application/json",
2908
+ "cache-control": "no-store"
2909
+ });
2910
+ res.end(body === void 0 ? "" : JSON.stringify(body));
2911
+ };
2912
+ if (req.method === "OPTIONS") {
2913
+ res.writeHead(204, {
2914
+ ...CORS_HEADERS,
2915
+ ...sessionId ? { "mcp-session-id": sessionId } : {},
2916
+ "cache-control": "no-store"
2917
+ });
2918
+ res.end();
2919
+ return;
2920
+ }
2921
+ const path = (req.url ?? "").split("?")[0];
2922
+ if (path !== "/mcp") return send(404, { error: "not_found" });
2923
+ if (req.method !== "POST") {
2924
+ res.setHeader("allow", "POST, OPTIONS");
2925
+ return send(405, { error: "method_not_allowed" });
2926
+ }
2927
+ const chunks = [];
2928
+ let size = 0;
2929
+ req.on("data", (c) => {
2930
+ size += c.length;
2931
+ if (size > 10 * 1024 * 1024) req.destroy();
2932
+ else chunks.push(c);
2933
+ });
2934
+ req.on("end", async () => {
2935
+ let payload;
2936
+ try {
2937
+ payload = JSON.parse(Buffer.concat(chunks).toString("utf8"));
2938
+ } catch {
2939
+ return send(400, rpcErr(null, -32700, "Parse error"));
2940
+ }
2941
+ const out = await handleRpcPayload(payload, opts);
2942
+ if (out === null) return send(202);
2943
+ send(200, out);
2944
+ });
2945
+ });
2946
+ }
2947
+ async function runStdio(opts = {}, input = process.stdin, output = process.stdout) {
2948
+ let buffer = "";
2949
+ const pending = [];
2950
+ const processBuffer = () => {
2951
+ while (buffer.length > 0) {
2952
+ const trimmed = buffer.trimStart();
2953
+ if (!trimmed) {
2954
+ buffer = "";
2955
+ break;
2956
+ }
2957
+ buffer = trimmed;
2958
+ if (buffer.startsWith("{") || buffer.startsWith("[")) {
2959
+ let depth = 0;
2960
+ let inString = false;
2961
+ let escape = false;
2962
+ let endIdx = -1;
2963
+ for (let i = 0; i < buffer.length; i++) {
2964
+ const ch = buffer[i];
2965
+ if (inString) {
2966
+ if (escape) {
2967
+ escape = false;
2968
+ } else if (ch === "\\") {
2969
+ escape = true;
2970
+ } else if (ch === '"') {
2971
+ inString = false;
2972
+ }
2973
+ } else {
2974
+ if (ch === '"') {
2975
+ inString = true;
2976
+ } else if (ch === "{" || ch === "[") {
2977
+ depth++;
2978
+ } else if (ch === "}" || ch === "]") {
2979
+ depth--;
2980
+ if (depth === 0) {
2981
+ endIdx = i;
2982
+ break;
2983
+ }
2984
+ }
2985
+ }
2986
+ }
2987
+ if (endIdx === -1) {
2988
+ break;
2989
+ }
2990
+ const candidate = buffer.slice(0, endIdx + 1);
2991
+ buffer = buffer.slice(endIdx + 1);
2992
+ pending.push(
2993
+ (async () => {
2994
+ let out;
2995
+ try {
2996
+ out = await handleRpcPayload(JSON.parse(candidate), opts);
2997
+ } catch {
2998
+ out = rpcErr(null, -32700, "Parse error");
2999
+ }
3000
+ if (out !== null) output.write(JSON.stringify(out) + "\n");
3001
+ })()
3002
+ );
3003
+ } else {
3004
+ const nlIdx = buffer.indexOf("\n");
3005
+ if (nlIdx === -1) {
3006
+ break;
3007
+ }
3008
+ const line = buffer.slice(0, nlIdx).trim();
3009
+ buffer = buffer.slice(nlIdx + 1);
3010
+ if (line) {
3011
+ pending.push(
3012
+ (async () => {
3013
+ let out;
3014
+ try {
3015
+ out = await handleRpcPayload(JSON.parse(line), opts);
3016
+ } catch {
3017
+ out = rpcErr(null, -32700, "Parse error");
3018
+ }
3019
+ if (out !== null) output.write(JSON.stringify(out) + "\n");
3020
+ })()
3021
+ );
3022
+ }
3023
+ }
3024
+ }
3025
+ };
3026
+ await new Promise((resolve) => {
3027
+ let closed = false;
3028
+ const onEnd = () => {
3029
+ if (closed) return;
3030
+ closed = true;
3031
+ if (buffer.trim()) {
3032
+ const candidate = buffer.trim();
3033
+ buffer = "";
3034
+ pending.push(
3035
+ (async () => {
3036
+ let out;
3037
+ try {
3038
+ out = await handleRpcPayload(JSON.parse(candidate), opts);
3039
+ } catch {
3040
+ out = rpcErr(null, -32700, "Parse error");
3041
+ }
3042
+ if (out !== null) output.write(JSON.stringify(out) + "\n");
3043
+ })()
3044
+ );
3045
+ }
3046
+ resolve();
3047
+ };
3048
+ input.on("data", (chunk) => {
3049
+ buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
3050
+ processBuffer();
3051
+ });
3052
+ input.on("end", onEnd);
3053
+ input.on("close", onEnd);
3054
+ });
3055
+ await Promise.all(pending);
3056
+ }
3057
+ export {
3058
+ PROTOCOL_VERSION,
3059
+ SERVER_INFO,
3060
+ TOOLS,
3061
+ createHttpServer,
3062
+ handleRpc,
3063
+ handleRpcPayload,
3064
+ runStdio
3065
+ };