@le-space/eigenbeleg 0.0.0-stage → 0.1.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,306 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // What an Eigenbeleg says, before it is drawn (pdf.js) or written (csv.js).
3
+ //
4
+ // An Eigenbeleg is a receipt the payer writes for a payment that has no
5
+ // receipt from the other side. It is never an invoice, and never one written
6
+ // for somebody else: the payer issues it, for their own payments.
7
+ //
8
+ // For a blockchain, the clean case is the network fee: it goes to a
9
+ // peer-to-peer network that has no organisation to issue an invoice. A
10
+ // storage deposit to a protocol contract is the same. A transfer to another
11
+ // account may well be to a company that does invoice; it goes on the
12
+ // Eigenbeleg only when the payer says so (`includeKinds`), and is always in
13
+ // the CSV.
14
+ //
15
+ // Two layouts, the same content:
16
+ // collective one Eigenbeleg for the period (Sammel-Eigenbeleg), one
17
+ // position per transaction;
18
+ // single one Eigenbeleg per transaction (as Belege writes them), each
19
+ // with its own number, counted up from the first.
20
+ // Every transaction shows its full hash, who paid whom with full addresses,
21
+ // every movement it had (the gas too, and what is not on the Eigenbeleg,
22
+ // with the reason) and its explorer link as a QR code.
23
+ // Numbers come from the payer's own range, since this service stores nothing.
24
+
25
+ import { normalize, round, sum } from '@le-space/ledger';
26
+
27
+ /* The document is German: it is for German bookkeeping. */
28
+
29
+ export const NOTE =
30
+ 'Eigenbeleg. Für diese Zahlung gibt es keinen Fremdbeleg: Empfänger ist ein Peer-to-Peer-Netzwerk ohne rechnungsstellende Organisation. ' +
31
+ 'Ausgestellt vom Zahlenden auf Grundlage der öffentlichen Transaktion; jede Position ist über ihren Transaktions-Hash in einem öffentlichen Block-Explorer nachprüfbar.';
32
+
33
+ export const NOT_AN_INVOICE =
34
+ 'Dies ist keine Rechnung und kein Beleg eines Dritten. Le Space stellt keine Rechnungen für andere aus.';
35
+
36
+ /** Kinds that go on the Eigenbeleg unless the payer chooses otherwise. */
37
+ export const DEFAULT_KINDS = ['fee', 'storage'];
38
+
39
+ export const KIND_TEXT = {
40
+ fee: 'Netzwerkgebühr (Gas)',
41
+ storage: 'Speicherhinterlegung (Storage Deposit)',
42
+ transfer: 'Überweisung',
43
+ call: 'Zahlung an Contract',
44
+ stake: 'Staking (keine Zahlung)',
45
+ unstake: 'Unstaking',
46
+ reward: 'Staking-Ertrag',
47
+ swap: 'Tausch',
48
+ escrow: 'Hinterlegung für ein Deployment (Escrow)',
49
+ usage: 'Verbrauch (aus Guthaben abgerechnet)'
50
+ };
51
+
52
+ export const CHAIN_NAMES = {
53
+ near: 'NEAR Protocol',
54
+ akash: 'Akash',
55
+ filecoin: 'Filecoin',
56
+ aleph: 'Aleph Cloud (Credits)'
57
+ };
58
+
59
+ /** Where a chain's data comes from, named in the footer of its documents. */
60
+ export const DATA_SOURCES = /** @type {Record<string, string>} */ ({
61
+ near: 'NearBlocks.io APIs, NEAR-Archiv-RPC',
62
+ filecoin: 'Filfox',
63
+ akash: 'Akash-RPC, Akash Console',
64
+ aleph: 'Aleph-API (api2.aleph.im)'
65
+ });
66
+
67
+ /**
68
+ * @typedef {object} Payer who pays and issues the Eigenbeleg
69
+ * @property {string} name
70
+ * @property {string} address postal address, lines separated by \n
71
+ * @property {string[]} addresses own payment addresses on the chain
72
+ */
73
+
74
+ /**
75
+ * @typedef {object} Position
76
+ * @property {number} pos
77
+ * @property {import('./value.js').ValuedEntry} entry
78
+ * @property {string} what
79
+ * @property {string} recipient
80
+ */
81
+
82
+ /**
83
+ * @typedef {object} Movement one movement of a transaction
84
+ * @property {import('./value.js').ValuedEntry} entry
85
+ * @property {string} what
86
+ * @property {boolean} onIt on the Eigenbeleg
87
+ * @property {string} why why not, when not
88
+ */
89
+
90
+ /**
91
+ * @typedef {object} Transaction one position: a transaction with a payment on the Eigenbeleg
92
+ * @property {number} pos
93
+ * @property {string} number its own number in the single layout ('' in the collective one)
94
+ * @property {string} hash
95
+ * @property {string} time
96
+ * @property {string} explorerUrl
97
+ * @property {{ address: string, label: string }} from the own address that paid
98
+ * @property {{ address: string, label: string }} to who received the payment
99
+ * @property {Movement[]} movements every movement of the transaction the period has
100
+ * @property {string} eurExact what is on the Eigenbeleg, in EUR, positive
101
+ */
102
+
103
+ /**
104
+ * @param {object} p
105
+ * @param {Payer} p.payer
106
+ * @param {string} p.chain
107
+ * @param {string} p.network
108
+ * @param {{ from: string, to: string }} p.period
109
+ * @param {import('./value.js').ValuedEntry[]} p.entries every entry of the period, all own addresses
110
+ * @param {string} [p.number] the Eigenbeleg's number in the payer's range, e.g. EB-2026-007
111
+ * @param {string[]} [p.includeKinds]
112
+ * @param {string} [p.issuedAt] ISO; now when not given
113
+ * @param {'collective' | 'single'} [p.layout]
114
+ */
115
+ export function buildDocument({
116
+ payer,
117
+ chain,
118
+ network,
119
+ period,
120
+ entries,
121
+ number,
122
+ includeKinds = DEFAULT_KINDS,
123
+ issuedAt,
124
+ layout = 'collective'
125
+ }) {
126
+ if (layout !== 'collective' && layout !== 'single')
127
+ throw new Error('layout: collective or single');
128
+ checkPayer(payer);
129
+ const kinds = new Set(includeKinds);
130
+ const own = new Set(payer.addresses);
131
+ /** @type {Position[]} */
132
+ const positions = [];
133
+ /** @type {{ entry: import('./value.js').ValuedEntry, why: string }[]} */
134
+ const excluded = [];
135
+ for (const e of entries) {
136
+ const why =
137
+ e.type === 'received'
138
+ ? 'Eingang, keine Zahlung'
139
+ : !e.success
140
+ ? 'fehlgeschlagen, nichts gezahlt'
141
+ : own.has(e.counterparty)
142
+ ? 'Umbuchung zwischen eigenen Adressen'
143
+ : !kinds.has(e.kind)
144
+ ? e.kind === 'transfer' || e.kind === 'call'
145
+ ? 'Zahlung an ein Konto: Fremdbeleg anfordern oder bewusst einbeziehen'
146
+ : e.kind === 'escrow'
147
+ ? 'Hinterlegung (Escrow), noch kein Endbetrag'
148
+ : e.kind === 'usage'
149
+ ? 'Verbrauch aus Guthaben: steht im Verbrauchsauszug'
150
+ : 'keine Zahlung an das Netzwerk'
151
+ : !e.eur
152
+ ? 'kein verlässlicher Kurs (unbekannter Token)'
153
+ : '';
154
+ if (why) excluded.push({ entry: e, why });
155
+ else
156
+ positions.push({
157
+ pos: 0,
158
+ entry: e,
159
+ what: KIND_TEXT[/** @type {keyof typeof KIND_TEXT} */ (e.kind)] ?? e.kind,
160
+ recipient: e.counterpartyLabel || e.counterparty
161
+ });
162
+ }
163
+ const first = number || `EB-${period.to.slice(0, 4)}-001`;
164
+ /** @type {Transaction[]} */
165
+ const transactions = [];
166
+ for (const p of positions) {
167
+ let t = transactions.find((x) => x.hash === p.entry.hash);
168
+ if (!t) {
169
+ const all = entries.filter((e) => e.hash === p.entry.hash);
170
+ // The payment, not the gas, says to whom; a transaction with only gas paid the network.
171
+ const main = all.find((e) => e.type === 'sent') ?? p.entry;
172
+ t = {
173
+ pos: transactions.length + 1,
174
+ number: layout === 'single' ? nthNumber(first, transactions.length) : '',
175
+ hash: p.entry.hash,
176
+ time: p.entry.time,
177
+ explorerUrl: p.entry.explorerUrl,
178
+ from: { address: p.entry.account, label: 'eigene Adresse' },
179
+ to: { address: main.counterparty, label: main.counterpartyLabel },
180
+ movements: all.map((e) => {
181
+ const x = excluded.find((y) => y.entry === e);
182
+ return {
183
+ entry: e,
184
+ what: KIND_TEXT[/** @type {keyof typeof KIND_TEXT} */ (e.kind)] ?? e.kind,
185
+ onIt: !x,
186
+ why: x?.why ?? ''
187
+ };
188
+ }),
189
+ eurExact: '0'
190
+ };
191
+ transactions.push(t);
192
+ }
193
+ p.pos = t.pos;
194
+ }
195
+ for (const t of transactions)
196
+ t.eurExact = sum(
197
+ t.movements.filter((m) => m.onIt).map((m) => /** @type {any} */ (m.entry.eur).value)
198
+ ).replace(/^-/, '');
199
+ /** @type {Record<string, string>} */
200
+ const quantities = {};
201
+ for (const asset of new Set(positions.map((p) => p.entry.asset)))
202
+ quantities[asset] = normalize(
203
+ sum(positions.filter((p) => p.entry.asset === asset).map((p) => p.entry.amount)).replace(
204
+ /^-/,
205
+ ''
206
+ )
207
+ );
208
+ const eurExact = positions.length
209
+ ? sum(positions.map((p) => /** @type {any} */ (p.entry.eur).value))
210
+ : '0';
211
+ return {
212
+ number:
213
+ layout === 'single' && transactions.length > 1
214
+ ? `${first} – ${transactions.at(-1)?.number}`
215
+ : first,
216
+ layout,
217
+ transactions,
218
+ issuedAt: issuedAt ?? new Date().toISOString(),
219
+ payer: {
220
+ name: payer.name.trim(),
221
+ address: payer.address.trim(),
222
+ addresses: [...payer.addresses]
223
+ },
224
+ chain,
225
+ chainName: CHAIN_NAMES[/** @type {keyof typeof CHAIN_NAMES} */ (chain)] ?? chain,
226
+ network,
227
+ testnet: network !== 'mainnet',
228
+ period,
229
+ positions,
230
+ excluded,
231
+ totals: {
232
+ quantities,
233
+ // What was paid, as a positive amount, rounded to cents.
234
+ eur: round(eurExact.replace(/^-/, ''), 2),
235
+ eurExact: eurExact.replace(/^-/, '')
236
+ },
237
+ sources: [
238
+ ...new Set(
239
+ positions.map((p) =>
240
+ /** @type {any} */ (p.entry.eur).source.replace(/ \d{4}-\d{2}-\d{2}.*$/, '')
241
+ )
242
+ )
243
+ ],
244
+ note: NOTE,
245
+ notInvoice: NOT_AN_INVOICE
246
+ };
247
+ }
248
+
249
+ /** @typedef {ReturnType<typeof buildDocument>} EigenbelegDocument */
250
+
251
+ /**
252
+ * The n-th number counted up from the first: EB-2026-007 → EB-2026-008 …
253
+ * A number without digits at its end gets -1, -2 …
254
+ *
255
+ * @param {string} first @param {number} n
256
+ */
257
+ export function nthNumber(first, n) {
258
+ if (n === 0) return first;
259
+ const m = /^(.*?)(\d+)$/.exec(first);
260
+ if (!m) return `${first}-${n + 1}`;
261
+ return `${m[1]}${String(Number(m[2]) + n).padStart(m[2].length, '0')}`;
262
+ }
263
+
264
+ /** @param {Payer} payer */
265
+ function checkPayer(payer) {
266
+ if (!payer || typeof payer !== 'object') throw new Error('payer is required');
267
+ if (typeof payer.name !== 'string' || payer.name.trim().length < 2 || payer.name.length > 200)
268
+ throw new Error('payer.name is required');
269
+ if (
270
+ typeof payer.address !== 'string' ||
271
+ payer.address.trim().length < 5 ||
272
+ payer.address.length > 500
273
+ )
274
+ throw new Error('payer.address (postal) is required');
275
+ if (
276
+ !Array.isArray(payer.addresses) ||
277
+ payer.addresses.length === 0 ||
278
+ payer.addresses.length > 20
279
+ )
280
+ throw new Error('payer.addresses: one to twenty own addresses');
281
+ }
282
+
283
+ // ---- German formats ---------------------------------------------------------
284
+
285
+ /** `-1234.5` → `-1.234,5`; keeps every decimal. @param {string} amount */
286
+ export function deNumber(amount) {
287
+ const s = normalize(String(amount));
288
+ const neg = s.startsWith('-');
289
+ const [int, frac] = s.replace(/^-/, '').split('.');
290
+ const grouped = int.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
291
+ return `${neg ? '−' : ''}${grouped}${frac ? ',' + frac : ''}`;
292
+ }
293
+
294
+ /** A euro amount with fixed decimals: `0.0017` → `0,0017 €`. @param {string} amount @param {number} places */
295
+ export function deEuro(amount, places = 2) {
296
+ const r = round(String(amount), places);
297
+ const [int, frac = ''] = r.replace(/^-/, '').split('.');
298
+ const grouped = int.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
299
+ return `${r.startsWith('-') ? '−' : ''}${grouped},${frac.padEnd(places, '0')} €`;
300
+ }
301
+
302
+ /** `2026-10-05` → `05.10.2026`. @param {string} date */
303
+ export function deDate(date) {
304
+ const [y, m, d] = date.slice(0, 10).split('-');
305
+ return `${d}.${m}.${y}`;
306
+ }
package/src/index.js ADDED
@@ -0,0 +1,32 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // @le-space/eigenbeleg: the Eigenbeleg and the Kontoauszug of Le Space's
3
+ // tools (Belege, the Eigenbeleg API and web UI) – what they say, as PDF/A-2b
4
+ // and CSV. Browser and Node.
5
+ export {
6
+ buildDocument,
7
+ nthNumber,
8
+ NOTE,
9
+ NOT_AN_INVOICE,
10
+ DEFAULT_KINDS,
11
+ KIND_TEXT,
12
+ CHAIN_NAMES,
13
+ DATA_SOURCES,
14
+ deNumber,
15
+ deEuro,
16
+ deDate
17
+ } from './document.js';
18
+ export { eigenbelegCsv } from './csv.js';
19
+ export { eigenbelegPdf, CREATOR, PRODUCER } from './pdf.js';
20
+ export { buildStatement, STATEMENT_NOTE, USAGE_NOTE } from './statement.js';
21
+ export { statementPdf } from './statement-pdf.js';
22
+ export { valueEntries, fixedRates } from './value.js';
23
+ export { nextSelfNumber, bookingNote, bookingNotInvoice } from './booking.js';
24
+ export { bookingPdf } from './booking-pdf.js';
25
+ export { statementLayout } from './statement-layout.js';
26
+ /** @typedef {import('./value.js').Rate} Rate */
27
+ /** @typedef {import('./value.js').Rates} Rates */
28
+ /** @typedef {import('./value.js').ValuedEntry} ValuedEntry */
29
+ /** @typedef {import('./document.js').EigenbelegDocument} EigenbelegDocument */
30
+ /** @typedef {import('./statement.js').Statement} Statement */
31
+ /** @typedef {import('./booking.js').BookingEigenbeleg} BookingEigenbeleg */
32
+ /** @typedef {import('./booking.js').ChainDetails} ChainDetails */
package/src/layout.js ADDED
@@ -0,0 +1,229 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Eigenbeleg's look, shared by every document this package draws (the
3
+ // Eigenbeleg of a period, the Kontoauszug, the Eigenbeleg of one booking, a
4
+ // statement Eigenbeleg): A4, a 48 pt margin, grey labels beside their values,
5
+ // thin rules, a tinted box for the note, tables whose header repeats on a
6
+ // new page, a QR code of the explorer link. Text in any script the fonts
7
+ // have (@le-space/pdf); pages as many as the content needs.
8
+ //
9
+ // The drawing helpers of Eigenbeleg's pdf.js and statement-pdf.js (from
10
+ // Le-Space/eigenbeleg-agent at e6cde90), on faces instead of pdf-lib fonts.
11
+
12
+ import { rgb } from 'pdf-lib';
13
+ import { encode } from 'uqr';
14
+ import { pdfText, wrapText } from '@le-space/pdf';
15
+
16
+ /** @typedef {import('@le-space/pdf').Face} Face */
17
+ /** @typedef {{ regular: Face, bold: Face, mono: Face }} Fonts */
18
+ /** @typedef {import('pdf-lib').Color} Color */
19
+
20
+ export const A4 = /** @type {[number, number]} */ ([595.28, 841.89]);
21
+ export const BLACK = rgb(0, 0, 0);
22
+ export const GREY = rgb(0.38, 0.38, 0.38);
23
+ export const RULE = rgb(0.78, 0.78, 0.78);
24
+ export const TINT = rgb(0.95, 0.95, 0.93);
25
+ export const BAND = rgb(0.93, 0.94, 0.95);
26
+ export const WARN = rgb(0.6, 0.12, 0.08);
27
+ export const OK = rgb(0.1, 0.42, 0.2);
28
+
29
+ /**
30
+ * @typedef {object} Column
31
+ * @property {string} title
32
+ * @property {number} width
33
+ * @property {boolean} [right] aligned right, as numbers are
34
+ * @property {boolean} [mono]
35
+ */
36
+
37
+ /**
38
+ * A layout on a new A4 page of `pdf`.
39
+ *
40
+ * @param {import('pdf-lib').PDFDocument} pdf
41
+ * @param {Fonts} fonts
42
+ * @param {object} [o]
43
+ * @param {number} [o.margin]
44
+ * @param {number} [o.bottom] room kept free above the bottom margin, for the footer
45
+ * @param {(l: Layout) => void} [o.leavePage] before a new page: the old one's footer
46
+ * @param {(l: Layout) => void} [o.enterPage] on a new page: its running head
47
+ */
48
+ export function pageLayout(pdf, fonts, { margin = 48, bottom = 14, leavePage, enterPage } = {}) {
49
+ const { regular } = fonts;
50
+ const l = {
51
+ pdf,
52
+ fonts,
53
+ margin,
54
+ width: A4[0] - 2 * margin,
55
+ page: pdf.addPage(A4),
56
+ y: A4[1] - margin,
57
+ /** @type {import('pdf-lib').PDFPage[]} */
58
+ pages: /** @type {import('pdf-lib').PDFPage[]} */ ([]),
59
+
60
+ newPage() {
61
+ leavePage?.(l);
62
+ l.page = pdf.addPage(A4);
63
+ l.pages.push(l.page);
64
+ l.y = A4[1] - margin;
65
+ enterPage?.(l);
66
+ },
67
+
68
+ /** A new page when fewer than `h` points are left. @param {number} h */
69
+ ensure(h) {
70
+ if (l.y - h >= margin + bottom) return false;
71
+ l.newPage();
72
+ return true;
73
+ },
74
+
75
+ /** @param {number} h */
76
+ gap(h) {
77
+ l.y -= h;
78
+ },
79
+
80
+ /**
81
+ * Wrapped text, a new page where it runs out.
82
+ *
83
+ * @param {string} t
84
+ * @param {{ x?: number, size?: number, face?: Face, color?: Color, max?: number, lead?: number }} [o]
85
+ */
86
+ text(t, o = {}) {
87
+ const {
88
+ x = margin,
89
+ size = 9.5,
90
+ face = regular,
91
+ color = BLACK,
92
+ max = l.width - (x - margin),
93
+ lead = 1.35
94
+ } = o;
95
+ for (const line of wrapText(t, face, size, max)) {
96
+ l.ensure(size * lead);
97
+ face.draw(l.page, line, { x, y: l.y - size, size, color });
98
+ l.y -= size * lead;
99
+ }
100
+ },
101
+
102
+ /** One line, right-aligned at `xRight`. @param {string} t @param {number} xRight @param {number} size @param {Face} face @param {Color} [color] */
103
+ right(t, xRight, size, face, color = BLACK) {
104
+ const c = pdfText(t);
105
+ face.draw(l.page, c, { x: xRight - face.width(c, size), y: l.y - size, size, color });
106
+ },
107
+
108
+ /** One line at `x`, on the current line. @param {string} t @param {number} x @param {number} size @param {Face} face @param {Color} [color] */
109
+ at(t, x, size, face, color = BLACK) {
110
+ face.draw(l.page, pdfText(t), { x, y: l.y - size, size, color });
111
+ },
112
+
113
+ /** @param {number} [thickness] @param {Color} [color] */
114
+ rule(thickness = 0.6, color = RULE) {
115
+ l.page.drawLine({
116
+ start: { x: margin, y: l.y },
117
+ end: { x: A4[0] - margin, y: l.y },
118
+ thickness,
119
+ color
120
+ });
121
+ },
122
+
123
+ /**
124
+ * A label and its value side by side.
125
+ *
126
+ * @param {string} label
127
+ * @param {string} value
128
+ * @param {{ face?: Face, size?: number, max?: number, labelWidth?: number }} [o]
129
+ */
130
+ field(label, value, o = {}) {
131
+ const lw = o.labelWidth ?? 92;
132
+ const size = o.size ?? 8.5;
133
+ const lines = wrapText(value || '—', o.face ?? regular, size, (o.max ?? l.width) - lw);
134
+ l.ensure(Math.min(lines.length, 3) * size * 1.35);
135
+ const top = l.y;
136
+ l.text(label, { face: fonts.bold, size: 8, color: GREY, max: lw - 6 });
137
+ const after = l.y;
138
+ const page = l.page;
139
+ l.y = top;
140
+ l.text(value || '—', {
141
+ x: margin + lw,
142
+ face: o.face ?? regular,
143
+ size,
144
+ max: (o.max ?? l.width) - lw
145
+ });
146
+ // Where the value went on to a new page, the label's end does not count.
147
+ l.y = l.page === page ? Math.min(l.y, after) : l.y;
148
+ },
149
+
150
+ /** A note in a tinted box. @param {string} t @param {number} [size] */
151
+ box(t, size = 9) {
152
+ const lines = wrapText(t, regular, size, l.width - 16);
153
+ const h = lines.length * size * 1.35 + 14;
154
+ l.ensure(h);
155
+ l.page.drawRectangle({
156
+ x: margin,
157
+ y: l.y - h,
158
+ width: l.width,
159
+ height: h,
160
+ color: TINT,
161
+ borderColor: RULE,
162
+ borderWidth: 0.6
163
+ });
164
+ l.y -= 7;
165
+ for (const line of lines) {
166
+ regular.draw(l.page, line, { x: margin + 8, y: l.y - size, size });
167
+ l.y -= size * 1.35;
168
+ }
169
+ l.y -= 7;
170
+ },
171
+
172
+ /** A QR code of `value`, `side` points wide, its top left at (x, top). @param {string} value @param {number} x @param {number} top @param {number} side */
173
+ qr(value, x, top, side) {
174
+ const code = encode(value, { border: 0 });
175
+ const cell = side / code.size;
176
+ code.data.forEach((row, r) => {
177
+ // Runs of dark cells as one rectangle each.
178
+ for (let c = 0; c < row.length; c++) {
179
+ if (!row[c]) continue;
180
+ let n = 1;
181
+ while (row[c + n]) n++;
182
+ l.page.drawRectangle({
183
+ x: x + c * cell,
184
+ y: top - (r + 1) * cell,
185
+ width: n * cell + 0.05,
186
+ height: cell + 0.05,
187
+ color: BLACK
188
+ });
189
+ c += n - 1;
190
+ }
191
+ });
192
+ },
193
+
194
+ /**
195
+ * One row of a table, its cells wrapped; a new page (and `header` again) where it does not fit.
196
+ *
197
+ * @param {Column[]} columns
198
+ * @param {string[]} cells
199
+ * @param {{ face?: Face, color?: Color, size?: number, lead?: number, header?: () => void }} [o]
200
+ */
201
+ row(columns, cells, o = {}) {
202
+ const { face = regular, color = BLACK, size = 7.5, lead = 9.5, header } = o;
203
+ const wrapped = columns.map((c, i) =>
204
+ wrapText(cells[i] ?? '', c.mono ? fonts.mono : face, size, c.width - 6)
205
+ );
206
+ const h = Math.max(...wrapped.map((w) => w.length)) * lead + 2;
207
+ if (l.ensure(h)) header?.();
208
+ let x = margin;
209
+ columns.forEach((c, i) => {
210
+ const f = c.mono ? fonts.mono : face;
211
+ wrapped[i].forEach((line, j) => {
212
+ const w = f.width(line, size);
213
+ f.draw(l.page, line, {
214
+ x: c.right ? x + c.width - 6 - w : x,
215
+ y: l.y - size - j * lead,
216
+ size,
217
+ color
218
+ });
219
+ });
220
+ x += c.width;
221
+ });
222
+ l.y -= h;
223
+ }
224
+ };
225
+ l.pages.push(l.page);
226
+ return l;
227
+ }
228
+
229
+ /** @typedef {ReturnType<typeof pageLayout>} Layout */