@btps/boundview 0.0.0-stage → 1.2.0-rc.3

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,23 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+ import { initWasm } from '@resvg/resvg-wasm';
8
+ /** What the engine's WebAssembly is loaded from: its bytes, a compiled module, a URL or a fetch response. */
9
+ export type BoundViewEngineSource = Parameters<typeof initWasm>[0];
10
+ /**
11
+ * Loads the drawing engine once. In Node it is read from the package by
12
+ * default; in a browser or app, pass where the app serves
13
+ * `@resvg/resvg-wasm/index_bg.wasm` from.
14
+ */
15
+ export declare const initBoundViewEngine: (source?: BoundViewEngineSource) => Promise<void>;
16
+ /**
17
+ * An opened document's BoundView as a PNG at `scale` (2 for high-resolution
18
+ * screens), or null when it carries none or fails a check: then the app
19
+ * shows its own view of the signed data.
20
+ */
21
+ export declare const renderBoundView: (document: unknown, { scale }?: {
22
+ scale?: number;
23
+ }) => Promise<Uint8Array | null>;
package/dist/render.js ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+ /*
8
+ * Drawing a received BoundView (Rendering page). One engine, resvg and its
9
+ * rasterizer tiny-skia, compiled to WebAssembly: the same code in a browser,
10
+ * on a server and in an app. It is handed no network, no files and no fonts;
11
+ * it reads the drawing made from checked values and gives back a PNG.
12
+ */
13
+ import { initWasm, Resvg } from '@resvg/resvg-wasm';
14
+ import { boundViewResultOf } from '@btps/sdk/boundview';
15
+ import { boundViewToSvg } from './svg.js';
16
+ import { bundledFontsFor, loadBundledFonts } from './glyphs.js';
17
+ let engine;
18
+ /**
19
+ * Loads the drawing engine once. In Node it is read from the package by
20
+ * default; in a browser or app, pass where the app serves
21
+ * `@resvg/resvg-wasm/index_bg.wasm` from.
22
+ */
23
+ export const initBoundViewEngine = (source) => {
24
+ engine ??= (async () => {
25
+ if (source !== undefined)
26
+ return initWasm(source);
27
+ const [{ readFile }, { createRequire }] = await Promise.all([import('node:fs/promises'), import('node:module')]);
28
+ const wasm = createRequire(import.meta.url).resolve('@resvg/resvg-wasm/index_bg.wasm');
29
+ return initWasm(await readFile(wasm));
30
+ })();
31
+ return engine;
32
+ };
33
+ /**
34
+ * An opened document's BoundView as a PNG at `scale` (2 for high-resolution
35
+ * screens), or null when it carries none or fails a check: then the app
36
+ * shows its own view of the signed data.
37
+ */
38
+ export const renderBoundView = async (document, { scale = 2 } = {}) => {
39
+ const result = boundViewResultOf(document);
40
+ if (result === undefined || !result.show)
41
+ return null;
42
+ await initBoundViewEngine();
43
+ const doc = document;
44
+ const bundled = await loadBundledFonts(bundledFontsFor(doc, doc.boundView));
45
+ const resvg = new Resvg(boundViewToSvg(doc, doc.boundView, bundled), {
46
+ fitTo: { mode: 'zoom', value: scale },
47
+ font: { loadSystemFonts: false },
48
+ });
49
+ return resvg.render().asPng();
50
+ };
@@ -0,0 +1,63 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+ import { type BoundValue } from '@btps/sdk/boundview';
8
+ /** A line of one text node as laid out: its text, and each character's box. */
9
+ export type Run = {
10
+ text: string;
11
+ /** One box a code point of `text`: left and right edges. */
12
+ chars: {
13
+ left: number;
14
+ right: number;
15
+ }[];
16
+ /** The line's baseline, used to tell rows of a table apart. */
17
+ baseline: number;
18
+ };
19
+ type Bind = {
20
+ field: string;
21
+ format?: {
22
+ money: {
23
+ group: string;
24
+ decimal: string;
25
+ prefix?: string;
26
+ suffix?: string;
27
+ };
28
+ } | {
29
+ date: string;
30
+ } | {
31
+ percent: {
32
+ decimals: 0 | 1 | 2;
33
+ decimal: string;
34
+ };
35
+ } | {
36
+ groups: {
37
+ sizes: number[];
38
+ separator: string;
39
+ };
40
+ };
41
+ range?: [number, number];
42
+ };
43
+ /** Part of a run, by code point: shown as a fact (`bind`) or as the sender's own words. */
44
+ export type Segment = {
45
+ run: number;
46
+ from: number;
47
+ to: number;
48
+ bind?: Bind;
49
+ };
50
+ type Doc = Record<string, unknown>;
51
+ /** Every field a BoundView may bind in `document`, with its value. */
52
+ export declare const bindableFields: (document: Doc) => {
53
+ field: string;
54
+ value: BoundValue;
55
+ }[];
56
+ /**
57
+ * Binds the preview's runs to `document`'s fields. Line items first, a row at
58
+ * a time on its own band, so a line's amount is never taken for a total;
59
+ * then every other field, the longest writing first, every place it appears.
60
+ * Whatever is left is the sender's own words.
61
+ */
62
+ export declare const bindRuns: (document: Doc, runs: Run[]) => Segment[];
63
+ export {};
@@ -0,0 +1,286 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+ /*
8
+ * Binding by value: which text in a preview shows which signed field, and in
9
+ * which format. The preview is the platform's own; nothing in it is marked.
10
+ * A run's text is matched against every way each field may be written, and a
11
+ * binding is kept only when the receiver would write the field exactly as the
12
+ * preview showed it (`writtenValue`), so a binding can never change a fact.
13
+ */
14
+ import { boundValue, writtenValue } from '@btps/sdk/boundview';
15
+ const DATE_PATTERNS = [
16
+ 'd MMMM yyyy',
17
+ 'MMMM d, yyyy',
18
+ 'd MMM yyyy',
19
+ 'MMM d, yyyy',
20
+ 'dd/MM/yyyy',
21
+ 'MM/dd/yyyy',
22
+ 'dd.MM.yyyy',
23
+ 'dd-MM-yyyy',
24
+ 'yyyy-MM-dd',
25
+ ];
26
+ const GROUPS = [',', '.', ' ', "'", ''];
27
+ /** Every field a BoundView may bind in `document`, with its value. */
28
+ export const bindableFields = (document) => {
29
+ const found = [];
30
+ const walk = (value, path) => {
31
+ if (path.length > 0) {
32
+ const field = path.join('.');
33
+ const bound = boundValue(document, field);
34
+ if (bound !== undefined) {
35
+ found.push({ field, value: bound });
36
+ return;
37
+ }
38
+ }
39
+ if (Array.isArray(value))
40
+ value.forEach((item, index) => walk(item, [...path, String(index)]));
41
+ else if (typeof value === 'object' && value !== null) {
42
+ for (const [key, inner] of Object.entries(value)) {
43
+ if (path.length === 0 && (key === 'boundView' || key === 'metadata'))
44
+ continue;
45
+ walk(inner, [...path, key]);
46
+ }
47
+ }
48
+ };
49
+ walk(document, []);
50
+ return found;
51
+ };
52
+ /** Each way a value may be written without a range: the text, and the binding that writes it. */
53
+ const writings = (field, value) => {
54
+ const out = [];
55
+ const add = (bind) => out.push({ text: writtenValue(value, bind), bind });
56
+ if (value.kind === 'money') {
57
+ for (const group of GROUPS) {
58
+ for (const decimal of ['.', ',']) {
59
+ if (group !== decimal)
60
+ add({ field, format: { money: { group, decimal } } });
61
+ }
62
+ }
63
+ }
64
+ else if (value.kind === 'date') {
65
+ for (const date of DATE_PATTERNS)
66
+ add({ field, format: { date } });
67
+ }
68
+ else if (value.kind === 'percent') {
69
+ for (const decimals of [0, 1, 2]) {
70
+ for (const decimal of ['.', ','])
71
+ add({ field, format: { percent: { decimals, decimal } } });
72
+ }
73
+ }
74
+ else if (value.text.trim() !== '') {
75
+ add({ field });
76
+ }
77
+ return out;
78
+ };
79
+ const isSpace = (char) => char === undefined || /\s/u.test(char);
80
+ /** A match starts and ends a word: nothing but space or punctuation beside it. */
81
+ const isEdge = (char) => char === undefined || /[\s,.;:()[\]{}"'“”‘’!?/|–—-]/u.test(char);
82
+ /**
83
+ * Binds the preview's runs to `document`'s fields. Line items first, a row at
84
+ * a time on its own band, so a line's amount is never taken for a total;
85
+ * then every other field, the longest writing first, every place it appears.
86
+ * Whatever is left is the sender's own words.
87
+ */
88
+ export const bindRuns = (document, runs) => {
89
+ const characters = runs.map((run) => [...run.text]);
90
+ const taken = characters.map((chars) => chars.map(() => false));
91
+ const segments = [];
92
+ const free = (run, from, to) => taken[run]?.slice(from, to).every((used) => !used) ?? false;
93
+ const take = (run, from, to, bind) => {
94
+ for (let at = from; at < to; at++)
95
+ taken[run][at] = true;
96
+ segments.push({ run, from, to, bind });
97
+ };
98
+ /**
99
+ * Where `text` stands in a run, from `after` on: as a whole word, or for an
100
+ * amount anywhere, its prefix and suffix being checked by `moneyAt`.
101
+ */
102
+ const find = (run, text, after = 0, whole = true) => {
103
+ const chars = characters[run];
104
+ const want = [...text];
105
+ for (let at = after; at + want.length <= chars.length; at++) {
106
+ if (want.every((char, i) => chars[at + i] === char) && free(run, at, at + want.length)) {
107
+ if (!whole || (isEdge(chars[at - 1]) && isEdge(chars[at + want.length])))
108
+ return at;
109
+ }
110
+ }
111
+ return -1;
112
+ };
113
+ /** A money writing with its prefix and suffix: a currency sign or code beside the number. */
114
+ const moneyAt = (run, at, length, bind, value) => {
115
+ const chars = characters[run];
116
+ let from = at;
117
+ while (from > 0 && !isSpace(chars[from - 1]) && at - from < 8 && !/\d/.test(chars[from - 1] ?? ''))
118
+ from--;
119
+ // A code before the number with a space between: "AUD 1,452.00".
120
+ if (from === at && chars[at - 1] === ' ' && /^[A-Z]{3}$/.test(chars.slice(at - 4, at - 1).join('')) && isSpace(chars[at - 5])) {
121
+ from = at - 4;
122
+ }
123
+ let to = at + length;
124
+ while (to < chars.length && !isSpace(chars[to]) && to - (at + length) < 8 && !/\d/.test(chars[to] ?? ''))
125
+ to++;
126
+ if (to === at + length && chars[to] === ' ' && /^[A-Z]{3}$/.test(chars.slice(to + 1, to + 4).join('')) && isSpace(chars[to + 4])) {
127
+ to += 4;
128
+ }
129
+ // A negative amount is written with '-' before its prefix.
130
+ const sign = value.kind === 'money' && value.amount < 0 && chars[from] === '-' ? 1 : 0;
131
+ const prefix = chars.slice(from + sign, at).join('');
132
+ const suffix = chars.slice(at + length, to).join('');
133
+ if (!isEdge(chars[from - 1]) || !isEdge(chars[to]))
134
+ return undefined;
135
+ const format = bind.format.money;
136
+ const full = {
137
+ field: bind.field,
138
+ format: { money: { ...format, ...(prefix && { prefix }), ...(suffix && { suffix }) } },
139
+ };
140
+ const shown = chars.slice(from, to).join('');
141
+ return writtenValue(value, full) === shown && free(run, from, to) ? { from, to, bind: full } : undefined;
142
+ };
143
+ /** Binds every place a writing of `field` appears, in `only` runs if given. */
144
+ const bindEverywhere = (field, value, only) => {
145
+ let found = false;
146
+ for (const { text, bind } of writings(field, value).sort((a, b) => b.text.length - a.text.length)) {
147
+ const money = value.kind === 'money';
148
+ // An amount is found by its digits: its sign and prefix come before them.
149
+ const number = money && value.amount < 0 ? text.slice(1) : text;
150
+ for (let run = 0; run < runs.length; run++) {
151
+ if (only && !only(run))
152
+ continue;
153
+ for (let at = find(run, number, 0, !money); at !== -1; at = find(run, number, at + 1, !money)) {
154
+ if (money) {
155
+ const placed = moneyAt(run, at, [...number].length, bind, value);
156
+ if (placed) {
157
+ take(run, placed.from, placed.to, placed.bind);
158
+ found = true;
159
+ }
160
+ }
161
+ else {
162
+ take(run, at, at + [...number].length, bind);
163
+ found = true;
164
+ }
165
+ }
166
+ }
167
+ if (found)
168
+ return true;
169
+ }
170
+ return found;
171
+ };
172
+ /** Text shown in groups: "51 824 753 556" for "51824753556". */
173
+ const bindGroups = (field, text) => {
174
+ const want = [...text.replace(/ /g, '')];
175
+ if (want.length < 4)
176
+ return false;
177
+ for (let run = 0; run < runs.length; run++) {
178
+ const chars = characters[run];
179
+ for (let at = 0; at < chars.length; at++) {
180
+ if (chars[at] !== want[0] || !isEdge(chars[at - 1]))
181
+ continue;
182
+ let i = at;
183
+ let separator;
184
+ const sizes = [];
185
+ let size = 0;
186
+ let matched = 0;
187
+ while (i < chars.length && matched < want.length) {
188
+ if (chars[i] === want[matched]) {
189
+ size++;
190
+ matched++;
191
+ i++;
192
+ }
193
+ else if (size > 0 && (separator === undefined || chars[i] === separator) && /[ .\-/]/.test(chars[i] ?? '')) {
194
+ separator = chars[i];
195
+ sizes.push(size);
196
+ size = 0;
197
+ i++;
198
+ }
199
+ else
200
+ break;
201
+ }
202
+ if (matched === want.length && separator !== undefined && isEdge(chars[i]) && free(run, at, i)) {
203
+ take(run, at, i, { field, format: { groups: { sizes: [...sizes, size], separator } } });
204
+ return true;
205
+ }
206
+ }
207
+ }
208
+ return false;
209
+ };
210
+ /** A long text over several runs: each run that is part of it, bound by its range, in order. */
211
+ const bindRanges = (field, text) => {
212
+ const value = [...text];
213
+ let cursor = 0;
214
+ let found = false;
215
+ for (let run = 0; run < runs.length; run++) {
216
+ const trimmed = characters[run].join('').trim();
217
+ if (trimmed.length < 2 || !free(run, 0, characters[run].length))
218
+ continue;
219
+ const lead = characters[run].findIndex((char) => !isSpace(char));
220
+ const want = [...trimmed];
221
+ for (let at = cursor; at + want.length <= value.length; at++) {
222
+ if (want.every((char, i) => value[at + i] === char)) {
223
+ take(run, lead, lead + want.length, { field, range: [at, at + want.length] });
224
+ cursor = at + want.length;
225
+ found = true;
226
+ break;
227
+ }
228
+ }
229
+ }
230
+ return found;
231
+ };
232
+ const fields = bindableFields(document);
233
+ // Line items, a row at a time: each cell only on its description's band.
234
+ const lines = fields.filter(({ field }) => field.startsWith('lineItems.rows.'));
235
+ const rows = new Map();
236
+ for (const line of lines) {
237
+ const row = line.field.split('.').slice(0, 3).join('.');
238
+ rows.set(row, [...(rows.get(row) ?? []), line]);
239
+ }
240
+ for (const cells of rows.values()) {
241
+ const ordered = [...cells].sort((a, b) => Number(a.value.kind === 'money') - Number(b.value.kind === 'money'));
242
+ let band;
243
+ for (const { field, value } of ordered) {
244
+ // A row's amounts are only taken on the band its text anchors: never loose, where a total could be.
245
+ if (band === undefined && value.kind !== 'text')
246
+ break;
247
+ const before = segments.length;
248
+ bindEverywhere(field, value, (run) => band === undefined || Math.abs(runs[run].baseline - band) < 2);
249
+ const placed = segments[before];
250
+ if (band === undefined && placed !== undefined)
251
+ band = runs[placed.run].baseline;
252
+ }
253
+ }
254
+ // Everything else, longest writing first so "A$1,452.00" is not taken as "1,452".
255
+ const rest = fields
256
+ .filter(({ field }) => !field.startsWith('lineItems.rows.'))
257
+ .sort((a, b) => {
258
+ const length = (entry) => Math.max(0, ...writings(entry.field, entry.value).map(({ text }) => text.length));
259
+ return length(b) - length(a);
260
+ });
261
+ for (const { field, value } of rest) {
262
+ if (bindEverywhere(field, value))
263
+ continue;
264
+ if (value.kind === 'text' && !bindGroups(field, value.text))
265
+ bindRanges(field, value.text);
266
+ }
267
+ // The sender's own words: every stretch of a run no field took.
268
+ characters.forEach((chars, run) => {
269
+ let from = -1;
270
+ for (let at = 0; at <= chars.length; at++) {
271
+ const open = at < chars.length && !taken[run][at];
272
+ if (open && from === -1)
273
+ from = at;
274
+ if (!open && from !== -1) {
275
+ const words = chars.slice(from, at).join('');
276
+ if (words.trim() !== '') {
277
+ const lead = chars.slice(from, at).findIndex((char) => !isSpace(char));
278
+ const trail = chars.slice(from, at).length - [...chars.slice(from, at)].reverse().findIndex((char) => !isSpace(char));
279
+ segments.push({ run, from: from + lead, to: from + trail });
280
+ }
281
+ from = -1;
282
+ }
283
+ }
284
+ });
285
+ return segments.sort((a, b) => a.run - b.run || a.from - b.from);
286
+ };
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+ import type { BTPBoundViewFont } from '@btps/sdk/boundview';
8
+ /** The parts of an opentype.js font a glyph table is read from. */
9
+ export type OpenTypeFont = {
10
+ unitsPerEm: number;
11
+ charToGlyph(char: string): OpenTypeGlyph;
12
+ getKerningValue(left: OpenTypeGlyph, right: OpenTypeGlyph): number;
13
+ glyphs: {
14
+ get(index: number): OpenTypeGlyph;
15
+ };
16
+ substitution?: {
17
+ getSingle(feature: string, script: string, language: string): {
18
+ sub: number;
19
+ by: number;
20
+ }[] | undefined;
21
+ };
22
+ };
23
+ type OpenTypeGlyph = {
24
+ index: number;
25
+ advanceWidth?: number;
26
+ getPath(x: number, y: number, size: number): {
27
+ commands: PathCommand[];
28
+ };
29
+ };
30
+ type PathCommand = {
31
+ type: 'M' | 'L';
32
+ x: number;
33
+ y: number;
34
+ } | {
35
+ type: 'Q';
36
+ x1: number;
37
+ y1: number;
38
+ x: number;
39
+ y: number;
40
+ } | {
41
+ type: 'C';
42
+ x1: number;
43
+ y1: number;
44
+ x2: number;
45
+ y2: number;
46
+ x: number;
47
+ y: number;
48
+ } | {
49
+ type: 'Z';
50
+ };
51
+ /** The characters a font always carries, so any amount or date a binding names can be drawn. */
52
+ export declare const ALWAYS = "0123456789.,-+%$\u20AC\u00A3\u00A5/: ";
53
+ /**
54
+ * A font's glyph table for `characters`: each one's outline and advance, the
55
+ * kerning of the pairs among them, and its ascent and descent as far as its
56
+ * glyphs actually reach. Tabular figures swap in the font's own fixed-width
57
+ * digits, as the page drew them. Characters the font has no glyph for are
58
+ * returned apart, so the caller can say so.
59
+ */
60
+ export declare const glyphTable: (font: OpenTypeFont, characters: Iterable<string>, { tabular }?: {
61
+ tabular?: boolean;
62
+ }) => {
63
+ font: BTPBoundViewFont;
64
+ missing: string[];
65
+ };
66
+ /** The fallback a family is drawn with when its font file cannot be read: a font with its widths. */
67
+ export declare const fallbackFor: (family: string) => "arimo" | "tinos" | "cousine" | "carlito" | "caladea";
68
+ export {};
@@ -0,0 +1,119 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+ /** The characters a font always carries, so any amount or date a binding names can be drawn. */
8
+ export const ALWAYS = '0123456789.,-+%$€£¥/: ';
9
+ const GLYPH_PATH_LIMIT = 4000;
10
+ /** An outline as absolute commands, rounded to `places` decimals, in font units with y down. */
11
+ const outline = (commands, places) => {
12
+ const r = (value) => {
13
+ const rounded = Math.round(value * 10 ** places) / 10 ** places;
14
+ return Object.is(rounded, -0) ? 0 : rounded;
15
+ };
16
+ return commands
17
+ .map((c) => {
18
+ switch (c.type) {
19
+ case 'M':
20
+ case 'L':
21
+ return `${c.type}${r(c.x)} ${r(c.y)}`;
22
+ case 'Q':
23
+ return `Q${r(c.x1)} ${r(c.y1)} ${r(c.x)} ${r(c.y)}`;
24
+ case 'C':
25
+ return `C${r(c.x1)} ${r(c.y1)} ${r(c.x2)} ${r(c.y2)} ${r(c.x)} ${r(c.y)}`;
26
+ default:
27
+ return 'Z';
28
+ }
29
+ })
30
+ .join('');
31
+ };
32
+ /**
33
+ * A font's glyph table for `characters`: each one's outline and advance, the
34
+ * kerning of the pairs among them, and its ascent and descent as far as its
35
+ * glyphs actually reach. Tabular figures swap in the font's own fixed-width
36
+ * digits, as the page drew them. Characters the font has no glyph for are
37
+ * returned apart, so the caller can say so.
38
+ */
39
+ export const glyphTable = (font, characters, { tabular = false } = {}) => {
40
+ const swap = new Map();
41
+ if (tabular) {
42
+ for (const script of ['DFLT', 'latn']) {
43
+ try {
44
+ for (const { sub, by } of font.substitution?.getSingle('tnum', script, 'dflt') ?? [])
45
+ swap.set(sub, by);
46
+ }
47
+ catch {
48
+ // The font has no such script.
49
+ }
50
+ }
51
+ }
52
+ const glyphOf = (char) => {
53
+ const glyph = font.charToGlyph(char);
54
+ const swapped = swap.get(glyph.index);
55
+ return swapped === undefined ? glyph : font.glyphs.get(swapped);
56
+ };
57
+ const glyphs = {};
58
+ const missing = [];
59
+ let ascent = 0;
60
+ let descent = 0;
61
+ for (const char of new Set([...characters, ...ALWAYS])) {
62
+ const glyph = glyphOf(char);
63
+ if (glyph.index === 0 && char !== ' ') {
64
+ if (!ALWAYS.includes(char))
65
+ missing.push(char);
66
+ continue;
67
+ }
68
+ const { commands } = glyph.getPath(0, 0, font.unitsPerEm);
69
+ for (const command of commands) {
70
+ if (command.type === 'Z')
71
+ continue;
72
+ const ys = command.type === 'C' ? [command.y1, command.y2, command.y] : command.type === 'Q' ? [command.y1, command.y] : [command.y];
73
+ for (const y of ys) {
74
+ ascent = Math.max(ascent, -y);
75
+ descent = Math.max(descent, y);
76
+ }
77
+ }
78
+ let path = commands.length > 0 ? outline(commands, 2) : undefined;
79
+ if (path !== undefined && path.length > GLYPH_PATH_LIMIT)
80
+ path = outline(commands, 0);
81
+ if (path !== undefined && path.length > GLYPH_PATH_LIMIT) {
82
+ missing.push(char);
83
+ continue;
84
+ }
85
+ glyphs[char] = { advance: Math.round((glyph.advanceWidth ?? 0) * 100) / 100, ...(path && { path }) };
86
+ }
87
+ const kerning = {};
88
+ const present = Object.keys(glyphs);
89
+ for (const left of present) {
90
+ for (const right of present) {
91
+ const value = font.getKerningValue(glyphOf(left), glyphOf(right));
92
+ if (value)
93
+ kerning[left + right] = Math.round(value * 100) / 100;
94
+ }
95
+ }
96
+ return {
97
+ font: {
98
+ unitsPerEm: font.unitsPerEm,
99
+ ascent: Math.ceil(ascent),
100
+ descent: Math.ceil(descent),
101
+ glyphs,
102
+ ...(Object.keys(kerning).length > 0 && { kerning }),
103
+ },
104
+ missing,
105
+ };
106
+ };
107
+ /** The fallback a family is drawn with when its font file cannot be read: a font with its widths. */
108
+ export const fallbackFor = (family) => {
109
+ const name = family.toLowerCase();
110
+ if (/times|georgia|serif$|garamond|baskerville|tinos/.test(name) && !/sans/.test(name))
111
+ return 'tinos';
112
+ if (/courier|mono|consol|menlo|cousine/.test(name))
113
+ return 'cousine';
114
+ if (/calibri|carlito/.test(name))
115
+ return 'carlito';
116
+ if (/cambria|caladea/.test(name))
117
+ return 'caladea';
118
+ return 'arimo';
119
+ };
@@ -0,0 +1,32 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+ import { type BTPBoundView } from '@btps/sdk/boundview';
8
+ import { type BoundViewEngineSource } from '../render.js';
9
+ type Doc = Record<string, unknown>;
10
+ export type SnapshotOptions = {
11
+ /**
12
+ * Where the drawing engine's WebAssembly is served from. With it, an SVG
13
+ * logo travels as its outlines when they draw exactly as the browser drew
14
+ * them; without it, as its pixels.
15
+ */
16
+ engine?: BoundViewEngineSource;
17
+ /** Told of each label that looks like a fact but shows none: most often an example left in a design. */
18
+ onWarning?: (warning: string) => void;
19
+ };
20
+ /** A BoundView that cannot be sent as it is, and why. */
21
+ export declare class BoundViewSnapshotError extends Error {
22
+ readonly problems: string[];
23
+ constructor(message: string, problems: string[]);
24
+ }
25
+ /**
26
+ * Captures a preview as a BoundView: the preview's own element, laid out as
27
+ * the sender sees it, and the unsigned document it shows. Every fact found in
28
+ * the preview is bound to its field; the result passes every check a
29
+ * receiver runs, or this throws with what is wrong.
30
+ */
31
+ export declare const snapshotBoundView: (preview: HTMLElement, document: Doc, { engine, onWarning }?: SnapshotOptions) => Promise<BTPBoundView>;
32
+ export {};