@crewhaus/tool-ledger 0.7.0 → 0.8.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.
- package/LICENSE +201 -0
- package/NOTICE +9 -0
- package/README.md +4 -1
- package/dist/index.js +102 -37
- package/dist/lib/invoice.js +17 -1
- package/dist/paths.d.ts +21 -2
- package/dist/paths.js +72 -13
- package/package.json +14 -9
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
CrewHaus Factory
|
|
2
|
+
Copyright 2026 Max Meier
|
|
3
|
+
|
|
4
|
+
This product includes software developed by Max Meier
|
|
5
|
+
(operating as StudioMax — https://studiomax.io) and contributors.
|
|
6
|
+
|
|
7
|
+
The CrewHaus name and logo are trademarks of Max Meier. See
|
|
8
|
+
https://github.com/crewhaus/factory/blob/main/TRADEMARK.md for the
|
|
9
|
+
use-of-marks policy.
|
package/README.md
CHANGED
|
@@ -123,7 +123,10 @@ unmatched.
|
|
|
123
123
|
Rows on both sides use `@crewhaus/tool-money`'s `Transaction` — the shape
|
|
124
124
|
`StatementParse` produces — imported rather than re-declared. A side with
|
|
125
125
|
`kind: "statement"` is read through tool-money's own parser, so a file whose
|
|
126
|
-
dates could be day-first or month-first is refused there too.
|
|
126
|
+
dates could be day-first or month-first is refused there too. A statement row
|
|
127
|
+
that parser could not read is in neither the matched nor the unmatched lists,
|
|
128
|
+
so it is named in `unreadableStatementRows` (a count per side and the first
|
|
129
|
+
fifty, with reasons) rather than silently missing.
|
|
127
130
|
|
|
128
131
|
## Aging refuses rather than answering partially
|
|
129
132
|
|
package/dist/index.js
CHANGED
|
@@ -29,10 +29,9 @@
|
|
|
29
29
|
* `_setClock`, so a test can fix `postedAt` — which is inside the hash chain,
|
|
30
30
|
* so a wall-clock read would make the same posting hash differently twice.
|
|
31
31
|
*/
|
|
32
|
-
import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
33
|
-
import { dirname, join } from "node:path";
|
|
34
32
|
import { buildTool } from "@crewhaus/tool-builder";
|
|
35
33
|
import { parseStatement } from "@crewhaus/tool-money";
|
|
34
|
+
import { joinRel, openForReadSync, writeFileSafe } from "@crewhaus/tool-safety/fs";
|
|
36
35
|
import { z } from "zod";
|
|
37
36
|
import { LedgerError, assertInstant, assertIsoDate, canonicalJson, exponentFor, json, parseMinorUnits, sha256Hex, } from "./lib/amount";
|
|
38
37
|
import { ACCOUNT_TYPES, DEFAULT_BUSY_TIMEOUT_MS, inImmediateTransaction, openDb, readMeta, writeMeta, } from "./lib/db";
|
|
@@ -40,7 +39,7 @@ import { BUILTIN_TEMPLATES, DOCUMENT_KINDS, OUTPUT_FORMATS, allocateDocument, as
|
|
|
40
39
|
import { POST_LIMITS, ensureAccounts, postBatch } from "./lib/post";
|
|
41
40
|
import { FORMATS, VIEWS, renderRows, runQuery } from "./lib/query";
|
|
42
41
|
import { RECONCILE_LIMITS, reconcile } from "./lib/reconcile";
|
|
43
|
-
import { resolveSafe } from "./paths";
|
|
42
|
+
import { resolveSafe, workspaceRoot } from "./paths";
|
|
44
43
|
// ---------------------------------------------------------------------------
|
|
45
44
|
// the one seam
|
|
46
45
|
// ---------------------------------------------------------------------------
|
|
@@ -183,6 +182,7 @@ const entrySchema = z
|
|
|
183
182
|
.strict();
|
|
184
183
|
export const ledgerPost = buildTool({
|
|
185
184
|
name: "LedgerPost",
|
|
185
|
+
operativeArgs: [{ field: "dbPath", kind: "path", default: DEFAULT_DB_PATH }],
|
|
186
186
|
description: "Append balanced double-entry journal entries to a local, hash-chained SQLite ledger, refusing anything that would corrupt it. Use it instead of having a model track what has been booked: debits must equal credits or the entry is rejected with the difference named, a (source system, id) pair can only post once, a closed period stays closed, and the rows, the chain's new head and the idempotency claim all commit in ONE transaction — so a crash mid-batch leaves the book exactly as it was rather than a ledger that verifies while its duplicate suppression has forgotten the entry. Amounts are decimal strings or integer minor units, never floats. Nothing is transmitted anywhere; this writes a file.",
|
|
187
187
|
inputSchema: z
|
|
188
188
|
.object({
|
|
@@ -369,6 +369,8 @@ export const ledgerQuery = buildTool({
|
|
|
369
369
|
// LedgerReconcile
|
|
370
370
|
// ---------------------------------------------------------------------------
|
|
371
371
|
const MAX_STATEMENT_BYTES = 64 * 1024 * 1024;
|
|
372
|
+
/** A template file, like an inline `template`, is at most 256 KiB. */
|
|
373
|
+
const MAX_TEMPLATE_BYTES = 256 * 1024;
|
|
372
374
|
/** The row shape is `@crewhaus/tool-money`'s, so the schema mirrors it exactly. */
|
|
373
375
|
const transactionSchema = z
|
|
374
376
|
.object({
|
|
@@ -403,45 +405,72 @@ const sideSchema = z
|
|
|
403
405
|
to: isoDate.optional(),
|
|
404
406
|
})
|
|
405
407
|
.strict();
|
|
408
|
+
/** How many of a statement's unreadable rows a reconciliation lists by name. */
|
|
409
|
+
const UNREADABLE_ROWS_SHOWN = 50;
|
|
406
410
|
function loadSide(side, label, input) {
|
|
407
411
|
if (side.kind === "lines") {
|
|
408
412
|
if (side.lines === undefined)
|
|
409
413
|
throw new LedgerError(`${label}.kind is "lines" but no lines were given`);
|
|
410
|
-
return side.lines;
|
|
414
|
+
return { rows: side.lines };
|
|
411
415
|
}
|
|
412
416
|
if (side.kind === "statement") {
|
|
413
417
|
if (side.file === undefined)
|
|
414
418
|
throw new LedgerError(`${label}.kind is "statement" but no file was given`);
|
|
415
|
-
const at = resolveSafe("LedgerReconcile", side.file);
|
|
416
|
-
const size = statSync(at.real).size;
|
|
417
|
-
if (size > MAX_STATEMENT_BYTES) {
|
|
418
|
-
throw new LedgerError(`${at.rel} is ${size} bytes, over the ${MAX_STATEMENT_BYTES}-byte limit`);
|
|
419
|
-
}
|
|
420
419
|
// tool-money's parser, not a second one: it is the thing that refuses a
|
|
421
420
|
// file whose dates could be day-first or month-first, and a reconciliation
|
|
422
|
-
// run on months guessed the wrong way balances to twice the error.
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
421
|
+
// run on months guessed the wrong way balances to twice the error. It
|
|
422
|
+
// holds one row past the side limit, so an over-long file is refused by
|
|
423
|
+
// its true count without every row of it in memory first.
|
|
424
|
+
const parsed = parseStatement(readTextFile("LedgerReconcile", side.file, MAX_STATEMENT_BYTES), {
|
|
425
|
+
dateOrder: side.dateOrder,
|
|
426
|
+
decimalComma: side.decimalComma,
|
|
427
|
+
decimals: side.decimals,
|
|
428
|
+
keep: { transactions: RECONCILE_LIMITS.rowsPerSide + 1, rejected: UNREADABLE_ROWS_SHOWN },
|
|
429
|
+
});
|
|
430
|
+
if (parsed.count > RECONCILE_LIMITS.rowsPerSide) {
|
|
431
|
+
throw new LedgerError(`the ${label} side has ${parsed.count} rows, over the ${RECONCILE_LIMITS.rowsPerSide} limit`);
|
|
432
|
+
}
|
|
433
|
+
// A row the parser could not read is not in the reconciliation, so it is
|
|
434
|
+
// named beside it rather than silently missing from both sides.
|
|
435
|
+
return {
|
|
436
|
+
rows: parsed.transactions,
|
|
437
|
+
...(parsed.rejectedCount === 0
|
|
438
|
+
? {}
|
|
439
|
+
: { unreadable: { count: parsed.rejectedCount, rows: parsed.rejected } }),
|
|
440
|
+
};
|
|
430
441
|
}
|
|
431
442
|
if (side.account === undefined) {
|
|
432
443
|
throw new LedgerError(`${label}.kind is "ledger" but no account was given`);
|
|
433
444
|
}
|
|
434
445
|
const opened = open("LedgerReconcile", input, "read");
|
|
435
446
|
try {
|
|
436
|
-
return ledgerAsTransactions(opened.db, side.account, side.from, side.to);
|
|
447
|
+
return { rows: ledgerAsTransactions(opened.db, side.account, side.from, side.to) };
|
|
437
448
|
}
|
|
438
449
|
finally {
|
|
439
450
|
opened.db.close();
|
|
440
451
|
}
|
|
441
452
|
}
|
|
442
|
-
/**
|
|
443
|
-
|
|
444
|
-
|
|
453
|
+
/**
|
|
454
|
+
* One place that reads a caller-named file, so one place decides where it
|
|
455
|
+
* may be, what kind of file it may be and how much of it is held.
|
|
456
|
+
*
|
|
457
|
+
* The path is contained first, with the refusal every path here gives. The
|
|
458
|
+
* file is then opened without blocking and must be a regular file: a FIFO
|
|
459
|
+
* with no writer blocks an ordinary open for ever, and this read is
|
|
460
|
+
* synchronous, so a named pipe planted in the workspace used to stop the
|
|
461
|
+
* whole harness, heartbeats and other sessions included. And the byte limit
|
|
462
|
+
* is enforced while reading, not by a size the file reported before it was
|
|
463
|
+
* opened.
|
|
464
|
+
*/
|
|
465
|
+
function readTextFile(toolName, given, maxBytes) {
|
|
466
|
+
resolveSafe(toolName, given);
|
|
467
|
+
const read = openForReadSync(workspaceRoot(), given, { maxBytes });
|
|
468
|
+
if (!read.ok)
|
|
469
|
+
throw new LedgerError(`${toolName}: ${read.reason}`);
|
|
470
|
+
if (read.truncated) {
|
|
471
|
+
throw new LedgerError(`${toolName}: ${JSON.stringify(given)} is over the ${maxBytes}-byte limit, so it was not read`);
|
|
472
|
+
}
|
|
473
|
+
return read.text;
|
|
445
474
|
}
|
|
446
475
|
/**
|
|
447
476
|
* One account's posted lines as statement rows.
|
|
@@ -547,7 +576,9 @@ export const ledgerReconcile = buildTool({
|
|
|
547
576
|
concurrencySafe: true,
|
|
548
577
|
execute: async (input) => {
|
|
549
578
|
const currency = (input.currency ?? "USD").toUpperCase();
|
|
550
|
-
const
|
|
579
|
+
const left = loadSide(input.left, "left", input);
|
|
580
|
+
const right = loadSide(input.right, "right", input);
|
|
581
|
+
const result = reconcile(left.rows, right.rows, {
|
|
551
582
|
toleranceMinor: BigInt(input.toleranceMinor ?? 0),
|
|
552
583
|
windowDays: input.windowDays ?? 3,
|
|
553
584
|
allowManyToOne: input.allowManyToOne !== false,
|
|
@@ -559,7 +590,19 @@ export const ledgerReconcile = buildTool({
|
|
|
559
590
|
currency,
|
|
560
591
|
propose: input.propose,
|
|
561
592
|
});
|
|
562
|
-
|
|
593
|
+
const unreadable = {
|
|
594
|
+
...(left.unreadable === undefined ? {} : { left: left.unreadable }),
|
|
595
|
+
...(right.unreadable === undefined ? {} : { right: right.unreadable }),
|
|
596
|
+
};
|
|
597
|
+
return json(Object.keys(unreadable).length === 0
|
|
598
|
+
? result
|
|
599
|
+
: {
|
|
600
|
+
...result,
|
|
601
|
+
// Statement rows that could not be read, and so are in neither
|
|
602
|
+
// the matched nor the unmatched lists: the reconciliation does
|
|
603
|
+
// not cover them.
|
|
604
|
+
unreadableStatementRows: unreadable,
|
|
605
|
+
});
|
|
563
606
|
},
|
|
564
607
|
});
|
|
565
608
|
// ---------------------------------------------------------------------------
|
|
@@ -576,6 +619,13 @@ const partySchema = z
|
|
|
576
619
|
.strict();
|
|
577
620
|
export const invoiceRender = buildTool({
|
|
578
621
|
name: "InvoiceRender",
|
|
622
|
+
// `templateFile` is read into the rendered document: a deny or ask reads
|
|
623
|
+
// it, an allow on where the tool writes need not.
|
|
624
|
+
operativeArgs: [
|
|
625
|
+
{ field: "dbPath", kind: "path", default: DEFAULT_DB_PATH },
|
|
626
|
+
{ field: "outDir", kind: "path", beneath: "all" },
|
|
627
|
+
{ field: "templateFile", kind: "path", source: true },
|
|
628
|
+
],
|
|
579
629
|
description: "Render an invoice, receipt, credit note or quote to HTML, Markdown and JSON with a gap-free document number and totals computed rather than supplied. Use it instead of a model emitting invoice HTML: the number and the document record are allocated in ONE transaction, so a crash cannot burn a number out of a legally required sequence, and repeating the call with the same idempotency key returns the same number and the same bytes. Nothing is formatted through Intl, so the output does not move with an ICU upgrade; the yearly reset takes its year from the issue date, not the clock. Files are written under the workspace. It submits nothing and asks for no payment credentials.",
|
|
580
630
|
inputSchema: z
|
|
581
631
|
.object({
|
|
@@ -707,7 +757,7 @@ export const invoiceRender = buildTool({
|
|
|
707
757
|
}
|
|
708
758
|
const custom = input.templateFile === undefined
|
|
709
759
|
? input.template
|
|
710
|
-
: readTextFile(
|
|
760
|
+
: readTextFile("InvoiceRender", input.templateFile, MAX_TEMPLATE_BYTES);
|
|
711
761
|
// The hash covers everything that determines the rendered bytes, so a
|
|
712
762
|
// replay under the same key can be checked for being the same document —
|
|
713
763
|
// and a re-render after a crash produces byte-identical files.
|
|
@@ -796,21 +846,36 @@ export const invoiceRender = buildTool({
|
|
|
796
846
|
const files = [];
|
|
797
847
|
if (outDir !== null) {
|
|
798
848
|
const dir = outDir;
|
|
799
|
-
mkdirSync(dir.real, { recursive: true });
|
|
800
849
|
for (const [format, text] of Object.entries(rendered).sort()) {
|
|
801
850
|
const name = `${allocation.number}.${format === "markdown" ? "md" : format}`;
|
|
802
|
-
|
|
803
|
-
//
|
|
804
|
-
//
|
|
805
|
-
// character rule that produced
|
|
806
|
-
|
|
807
|
-
//
|
|
808
|
-
//
|
|
809
|
-
//
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
851
|
+
const rel = joinRel(dir.rel, name);
|
|
852
|
+
// Belt and braces over the check above: the composed path is contained
|
|
853
|
+
// again where it is written, by the physical location of its directory
|
|
854
|
+
// and its leaf, not only by the character rule that produced the name.
|
|
855
|
+
// writeFileSafe writes a temp under a RANDOM name, created
|
|
856
|
+
// O_EXCL|O_NOFOLLOW beside the target, and renames it into place: a
|
|
857
|
+
// reader never sees half an invoice, a crash leaves the previous file,
|
|
858
|
+
// and nothing is written through a link that LEAVES the workspace. The
|
|
859
|
+
// old temp name (`<target>.<hash8>.tmp`) was predictable from the
|
|
860
|
+
// caller's own input, so a link planted there wrote the invoice
|
|
861
|
+
// outside the workspace and left the target linked out. Missing
|
|
862
|
+
// directories under outDir are created one at a time, each checked. A
|
|
863
|
+
// link at the target that stays inside the workspace is followed (an
|
|
864
|
+
// operator who archives invoices behind a link keeps working, as on
|
|
865
|
+
// 0.7.0); a link OUT of the workspace, or a FIFO or other special
|
|
866
|
+
// file, is refused.
|
|
867
|
+
const written = writeFileSafe(workspaceRoot(), rel, text, {
|
|
868
|
+
overwrite: true,
|
|
869
|
+
createParents: true,
|
|
870
|
+
leafSymlink: "follow-contained",
|
|
871
|
+
});
|
|
872
|
+
if (!written.ok) {
|
|
873
|
+
// The number is already allocated and recorded with this payload, so
|
|
874
|
+
// it is not lost: a replay under the same key re-renders these bytes.
|
|
875
|
+
// written.reason already states nothing was written, so it is not
|
|
876
|
+
// repeated here.
|
|
877
|
+
throw new LedgerError(`InvoiceRender: ${allocation.number} is allocated and recorded, but its file could not be written — ${written.reason}. Fix the destination (a link out of the workspace, or a special file at the target: move it aside, or choose another outDir) and repeat the call with the same idempotencyKey to write the same files.`);
|
|
878
|
+
}
|
|
814
879
|
files.push(`${dir.rel}/${name}`);
|
|
815
880
|
}
|
|
816
881
|
}
|
package/dist/lib/invoice.js
CHANGED
|
@@ -6,6 +6,22 @@ export const INVOICE_LIMITS = {
|
|
|
6
6
|
lines: 1_000,
|
|
7
7
|
templateBytes: 256 * 1024,
|
|
8
8
|
};
|
|
9
|
+
/**
|
|
10
|
+
* `digits` in groups of three from the right, joined by `group`.
|
|
11
|
+
*
|
|
12
|
+
* Sliced and joined, never `replace(regex, group)`: the separator is the
|
|
13
|
+
* caller's text, and as a replacement STRING its `$'`, `` $` `` and `$1`
|
|
14
|
+
* expanded to pieces of the number, so a separator of `$'` rendered
|
|
15
|
+
* 1234567.89 as "1234567234567567.89" — a wrong amount on an invoice. The
|
|
16
|
+
* lookahead regex was also quadratic in the digit count.
|
|
17
|
+
*/
|
|
18
|
+
function groupDigits(digits, group) {
|
|
19
|
+
const head = digits.length % 3 || 3;
|
|
20
|
+
const parts = [digits.slice(0, head)];
|
|
21
|
+
for (let at = head; at < digits.length; at += 3)
|
|
22
|
+
parts.push(digits.slice(at, at + 3));
|
|
23
|
+
return parts.join(group);
|
|
24
|
+
}
|
|
9
25
|
/**
|
|
10
26
|
* Minor units as the document shows them. No `Intl`, on purpose (see above):
|
|
11
27
|
* the digits come from exact bigint arithmetic and the separators come from
|
|
@@ -20,7 +36,7 @@ export function formatAmount(minor, exponent, options = {}) {
|
|
|
20
36
|
const fraction = dot === -1 ? "" : body.slice(dot + 1);
|
|
21
37
|
const group = options.groupSeparator ?? "";
|
|
22
38
|
if (group !== "")
|
|
23
|
-
whole = whole
|
|
39
|
+
whole = groupDigits(whole, group);
|
|
24
40
|
const decimal = options.decimalSeparator ?? ".";
|
|
25
41
|
return `${negative ? "-" : ""}${whole}${fraction === "" ? "" : decimal + fraction}`;
|
|
26
42
|
}
|
package/dist/paths.d.ts
CHANGED
|
@@ -1,10 +1,29 @@
|
|
|
1
1
|
import { CrewhausError } from "@crewhaus/errors";
|
|
2
|
-
/**
|
|
2
|
+
/**
|
|
3
|
+
* The longest path this resolves, in UTF-16 code units; a longer one is
|
|
4
|
+
* refused before it is walked. Nothing that long can be opened or created:
|
|
5
|
+
* PATH_MAX is 1,024 bytes on macOS and 4,096 on Linux, Windows stops at
|
|
6
|
+
* 32,767 UTF-16 units, and a path's UTF-8 form is never shorter than its
|
|
7
|
+
* UTF-16 one. The limit is twice that because the part of a path that exists
|
|
8
|
+
* is itself under PATH_MAX, so the part that does not is over PATH_MAX on its
|
|
9
|
+
* own: no spelling of the place reaches it, not even one through a symlink
|
|
10
|
+
* that shortens the part that exists.
|
|
11
|
+
*/
|
|
12
|
+
export declare const MAX_PATH_CHARS: number;
|
|
13
|
+
/**
|
|
14
|
+
* Raised when a caller-supplied path resolves outside the workspace root, or
|
|
15
|
+
* is longer than any path can be.
|
|
16
|
+
*/
|
|
3
17
|
export declare class ToolPermissionError extends CrewhausError {
|
|
4
18
|
readonly name = "ToolPermissionError";
|
|
5
19
|
readonly toolName: string;
|
|
6
20
|
readonly path: string;
|
|
7
|
-
|
|
21
|
+
/**
|
|
22
|
+
* Why, when it is not that the location escapes the workspace root: a path
|
|
23
|
+
* longer than any path can be. A caller that rewords the refusal says this.
|
|
24
|
+
*/
|
|
25
|
+
readonly reason: string | undefined;
|
|
26
|
+
constructor(toolName: string, attemptedPath: string, reason?: string);
|
|
8
27
|
}
|
|
9
28
|
/**
|
|
10
29
|
* A validated path, in both forms the tools need.
|
package/dist/paths.js
CHANGED
|
@@ -11,15 +11,45 @@
|
|
|
11
11
|
import { lstatSync, readlinkSync, realpathSync } from "node:fs";
|
|
12
12
|
import * as path from "node:path";
|
|
13
13
|
import { CrewhausError } from "@crewhaus/errors";
|
|
14
|
-
/**
|
|
14
|
+
/**
|
|
15
|
+
* The longest path this resolves, in UTF-16 code units; a longer one is
|
|
16
|
+
* refused before it is walked. Nothing that long can be opened or created:
|
|
17
|
+
* PATH_MAX is 1,024 bytes on macOS and 4,096 on Linux, Windows stops at
|
|
18
|
+
* 32,767 UTF-16 units, and a path's UTF-8 form is never shorter than its
|
|
19
|
+
* UTF-16 one. The limit is twice that because the part of a path that exists
|
|
20
|
+
* is itself under PATH_MAX, so the part that does not is over PATH_MAX on its
|
|
21
|
+
* own: no spelling of the place reaches it, not even one through a symlink
|
|
22
|
+
* that shortens the part that exists.
|
|
23
|
+
*/
|
|
24
|
+
export const MAX_PATH_CHARS = 2 * (process.platform === "darwin" ? 1_024 : process.platform === "win32" ? 32_767 : 4_096);
|
|
25
|
+
/** A path as a refusal quotes it: whole, unless it is past {@link MAX_PATH_CHARS}. */
|
|
26
|
+
function shownPath(given) {
|
|
27
|
+
return given.length > MAX_PATH_CHARS ? `${given.slice(0, 64)}…` : given;
|
|
28
|
+
}
|
|
29
|
+
/** Why a path past {@link MAX_PATH_CHARS} is refused: its length and the limit. */
|
|
30
|
+
function tooLong(abs) {
|
|
31
|
+
return `it is ${abs.length} characters once resolved, over the ${MAX_PATH_CHARS}-character limit: no path that long can be opened or created`;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Raised when a caller-supplied path resolves outside the workspace root, or
|
|
35
|
+
* is longer than any path can be.
|
|
36
|
+
*/
|
|
15
37
|
export class ToolPermissionError extends CrewhausError {
|
|
16
38
|
name = "ToolPermissionError";
|
|
17
39
|
toolName;
|
|
18
40
|
path;
|
|
19
|
-
|
|
20
|
-
|
|
41
|
+
/**
|
|
42
|
+
* Why, when it is not that the location escapes the workspace root: a path
|
|
43
|
+
* longer than any path can be. A caller that rewords the refusal says this.
|
|
44
|
+
*/
|
|
45
|
+
reason;
|
|
46
|
+
constructor(toolName, attemptedPath, reason) {
|
|
47
|
+
super("tool", reason === undefined
|
|
48
|
+
? `tool "${toolName}" rejected path "${attemptedPath}": resolved location escapes the workspace root`
|
|
49
|
+
: `tool "${toolName}" rejected path "${shownPath(attemptedPath)}": ${reason}`);
|
|
21
50
|
this.toolName = toolName;
|
|
22
51
|
this.path = attemptedPath;
|
|
52
|
+
this.reason = reason;
|
|
23
53
|
}
|
|
24
54
|
}
|
|
25
55
|
/** The workspace root, resolved. Every path is contained within it. */
|
|
@@ -67,15 +97,7 @@ function nameExists(p) {
|
|
|
67
97
|
function resolveLocation(target, depth = 0) {
|
|
68
98
|
if (depth > 40)
|
|
69
99
|
throw new Error(`symlink chain at "${target}" is too long to resolve`);
|
|
70
|
-
|
|
71
|
-
const tail = [];
|
|
72
|
-
while (!nameExists(probe)) {
|
|
73
|
-
tail.unshift(path.basename(probe));
|
|
74
|
-
const parent = path.dirname(probe);
|
|
75
|
-
if (parent === probe)
|
|
76
|
-
break; // reached the filesystem root
|
|
77
|
-
probe = parent;
|
|
78
|
-
}
|
|
100
|
+
const { probe, tail } = deepestName(target);
|
|
79
101
|
let probeReal;
|
|
80
102
|
try {
|
|
81
103
|
probeReal = realpathSync(probe);
|
|
@@ -97,7 +119,41 @@ function resolveLocation(target, depth = 0) {
|
|
|
97
119
|
const base = realpathSync(path.dirname(probe));
|
|
98
120
|
probeReal = resolveLocation(path.resolve(base, link), depth + 1);
|
|
99
121
|
}
|
|
100
|
-
|
|
122
|
+
// One string, not one argument per name: Bun's `path.join` keeps only
|
|
123
|
+
// (argument count mod 65,536) of its arguments.
|
|
124
|
+
return tail.length > 0 ? path.join(probeReal, tail) : probeReal;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* `target`, an absolute path, split where its deepest prefix that exists as
|
|
128
|
+
* a NAME ends: that prefix, and the names below it, which do not exist, as
|
|
129
|
+
* one string ("" when `target` itself exists). This is `path.dirname` and
|
|
130
|
+
* `path.basename` worked by index on `target` itself: handing them each
|
|
131
|
+
* shorter prefix in turn copied the rest of the path once per missing name,
|
|
132
|
+
* the square of a count the caller picks.
|
|
133
|
+
*/
|
|
134
|
+
function deepestName(target) {
|
|
135
|
+
const top = path.parse(target).root.length;
|
|
136
|
+
const isSep = (i) => target[i] === "/" || target[i] === path.sep;
|
|
137
|
+
let probe = target;
|
|
138
|
+
let start = target.length;
|
|
139
|
+
let stop = -1;
|
|
140
|
+
while (!nameExists(probe)) {
|
|
141
|
+
// `path.basename(probe)` is `target.slice(start, end)`, and
|
|
142
|
+
// `path.dirname(probe)` is `target.slice(0, up)`.
|
|
143
|
+
let end = probe.length;
|
|
144
|
+
while (end > top && isSep(end - 1))
|
|
145
|
+
end--;
|
|
146
|
+
if (stop < 0)
|
|
147
|
+
stop = end;
|
|
148
|
+
start = end;
|
|
149
|
+
while (start > top && !isSep(start - 1))
|
|
150
|
+
start--;
|
|
151
|
+
const up = start > top ? start - 1 : top;
|
|
152
|
+
if (up === probe.length)
|
|
153
|
+
break; // reached the filesystem root
|
|
154
|
+
probe = target.slice(0, up);
|
|
155
|
+
}
|
|
156
|
+
return { probe, tail: stop < 0 ? "" : target.slice(start, stop) };
|
|
101
157
|
}
|
|
102
158
|
export function resolveSafe(toolName, rel, root = workspaceRoot()) {
|
|
103
159
|
const rootResolved = path.resolve(root);
|
|
@@ -107,6 +163,9 @@ export function resolveSafe(toolName, rel, root = workspaceRoot()) {
|
|
|
107
163
|
if (abs !== rootResolved && !abs.startsWith(`${rootResolved}${path.sep}`)) {
|
|
108
164
|
throw new ToolPermissionError(toolName, rel);
|
|
109
165
|
}
|
|
166
|
+
// Longer than any path can be: refused before the walk below reads it.
|
|
167
|
+
if (abs.length > MAX_PATH_CHARS)
|
|
168
|
+
throw new ToolPermissionError(toolName, rel, tooLong(abs));
|
|
110
169
|
let real;
|
|
111
170
|
try {
|
|
112
171
|
const rootReal = realpathSync(rootResolved);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crewhaus/tool-ledger",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Deterministic double-entry ledger: hash-chained postings, queries, reconciliation and invoice rendering",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -8,19 +8,21 @@
|
|
|
8
8
|
"exports": {
|
|
9
9
|
".": {
|
|
10
10
|
"types": "./dist/index.d.ts",
|
|
11
|
-
"import": "./dist/index.js"
|
|
11
|
+
"import": "./dist/index.js",
|
|
12
|
+
"default": "./dist/index.js"
|
|
12
13
|
}
|
|
13
14
|
},
|
|
14
15
|
"scripts": {
|
|
15
16
|
"test": "bun test src"
|
|
16
17
|
},
|
|
17
18
|
"dependencies": {
|
|
18
|
-
"@crewhaus/errors": "0.
|
|
19
|
-
"@crewhaus/tool-builder": "0.
|
|
20
|
-
"@crewhaus/tool-catalog": "0.
|
|
21
|
-
"@crewhaus/tool-datetime": "0.
|
|
22
|
-
"@crewhaus/tool-math": "0.
|
|
23
|
-
"@crewhaus/tool-money": "0.
|
|
19
|
+
"@crewhaus/errors": "0.8.0",
|
|
20
|
+
"@crewhaus/tool-builder": "0.8.0",
|
|
21
|
+
"@crewhaus/tool-catalog": "0.8.0",
|
|
22
|
+
"@crewhaus/tool-datetime": "0.8.0",
|
|
23
|
+
"@crewhaus/tool-math": "0.8.0",
|
|
24
|
+
"@crewhaus/tool-money": "0.8.0",
|
|
25
|
+
"@crewhaus/tool-safety": "0.8.0",
|
|
24
26
|
"zod": "^3.23.8"
|
|
25
27
|
},
|
|
26
28
|
"devDependencies": {
|
|
@@ -44,5 +46,8 @@
|
|
|
44
46
|
"publishConfig": {
|
|
45
47
|
"access": "public"
|
|
46
48
|
},
|
|
47
|
-
"files": ["dist", "README.md", "LICENSE", "NOTICE"]
|
|
49
|
+
"files": ["dist", "README.md", "LICENSE", "NOTICE"],
|
|
50
|
+
"engines": {
|
|
51
|
+
"bun": ">=1.3.14"
|
|
52
|
+
}
|
|
48
53
|
}
|