@formepdf/shared 0.13.0 → 0.15.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,27 @@
1
+ /**
2
+ * Prop encoding for the emitting components.
3
+ *
4
+ * Each Forme adapter component (Svelte, Vue) renders one placeholder tag whose
5
+ * `props` attribute carries the component's props as JSON (part of
6
+ * the internal emitter/parser contract - see `parser.ts`). Values
7
+ * that cannot survive the JSON round-trip fail loudly here, naming
8
+ * the component and prop, rather than silently producing a wrong PDF.
9
+ * The one exception is `Uint8Array` (byte font sources on
10
+ * `<Document fonts>`): it is tunneled through a marker object and
11
+ * restored by the parser's reviver, so byte sources survive
12
+ * serialization exactly as they do in the react adapter.
13
+ */
14
+ /**
15
+ * `JSON.parse` reviver restoring `Uint8Array` values that
16
+ * `encodeProps` tunneled through byte markers.
17
+ */
18
+ export declare function reviveBytesMarker(_key: string, value: unknown): unknown;
19
+ /**
20
+ * JSON-encode a component's props for the placeholder `props`
21
+ * attribute. `undefined` values are omitted (matching how absent
22
+ * props behave in the react adapter). `Uint8Array` values become
23
+ * byte markers (see `reviveBytesMarker`). Functions, symbols,
24
+ * bigints, and circular structures throw an error naming the
25
+ * component and the offending prop.
26
+ */
27
+ export declare function encodeProps(component: string, props: object): string;
package/dist/encode.js ADDED
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Prop encoding for the emitting components.
3
+ *
4
+ * Each Forme adapter component (Svelte, Vue) renders one placeholder tag whose
5
+ * `props` attribute carries the component's props as JSON (part of
6
+ * the internal emitter/parser contract - see `parser.ts`). Values
7
+ * that cannot survive the JSON round-trip fail loudly here, naming
8
+ * the component and prop, rather than silently producing a wrong PDF.
9
+ * The one exception is `Uint8Array` (byte font sources on
10
+ * `<Document fonts>`): it is tunneled through a marker object and
11
+ * restored by the parser's reviver, so byte sources survive
12
+ * serialization exactly as they do in the react adapter.
13
+ */
14
+ /**
15
+ * Marker key wrapping a base64-encoded `Uint8Array` inside the props
16
+ * JSON. Part of the internal emitter/parser contract.
17
+ */
18
+ const BYTES_MARKER = '__formeBytes';
19
+ /** Encode bytes to base64 without Node APIs (works in edge runtimes). */
20
+ function bytesToBase64(bytes) {
21
+ let binary = '';
22
+ const chunk = 0x8000;
23
+ for (let i = 0; i < bytes.length; i += chunk) {
24
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
25
+ }
26
+ return btoa(binary);
27
+ }
28
+ function base64ToBytes(b64) {
29
+ const binary = atob(b64);
30
+ const bytes = new Uint8Array(binary.length);
31
+ for (let i = 0; i < binary.length; i++)
32
+ bytes[i] = binary.charCodeAt(i);
33
+ return bytes;
34
+ }
35
+ /**
36
+ * `JSON.parse` reviver restoring `Uint8Array` values that
37
+ * `encodeProps` tunneled through byte markers.
38
+ */
39
+ export function reviveBytesMarker(_key, value) {
40
+ if (value !== null &&
41
+ typeof value === 'object' &&
42
+ typeof value[BYTES_MARKER] === 'string') {
43
+ return base64ToBytes(value[BYTES_MARKER]);
44
+ }
45
+ return value;
46
+ }
47
+ /**
48
+ * JSON-encode a component's props for the placeholder `props`
49
+ * attribute. `undefined` values are omitted (matching how absent
50
+ * props behave in the react adapter). `Uint8Array` values become
51
+ * byte markers (see `reviveBytesMarker`). Functions, symbols,
52
+ * bigints, and circular structures throw an error naming the
53
+ * component and the offending prop.
54
+ */
55
+ export function encodeProps(component, props) {
56
+ const parts = [];
57
+ for (const [key, value] of Object.entries(props)) {
58
+ if (value === undefined)
59
+ continue;
60
+ let json;
61
+ try {
62
+ json = JSON.stringify(value, (_k, v) => {
63
+ const t = typeof v;
64
+ if (t === 'function' || t === 'symbol' || t === 'bigint') {
65
+ throw new TypeError(`contains a ${t}, which cannot be serialized to JSON`);
66
+ }
67
+ if (v instanceof Uint8Array) {
68
+ return { [BYTES_MARKER]: bytesToBase64(v) };
69
+ }
70
+ // A user object carrying the marker key would be revived as a
71
+ // Uint8Array on the other side - fail loudly instead of
72
+ // silently corrupting it. (Marker objects produced above are
73
+ // never re-visited by the replacer, so this only fires on
74
+ // user-supplied values.)
75
+ if (v !== null && t === 'object' && BYTES_MARKER in v) {
76
+ throw new TypeError(`contains a reserved "${BYTES_MARKER}" key`);
77
+ }
78
+ return v;
79
+ });
80
+ }
81
+ catch (err) {
82
+ const reason = err instanceof Error ? err.message : String(err);
83
+ throw new Error(`[Forme] <${component}>: prop "${key}" is not serializable: ${reason}`);
84
+ }
85
+ // JSON.stringify returns undefined (without throwing) for values
86
+ // with no JSON representation at the top level, e.g. functions -
87
+ // drop such props rather than emitting invalid JSON.
88
+ if (json === undefined)
89
+ continue;
90
+ parts.push(`${JSON.stringify(key)}:${json}`);
91
+ }
92
+ return `{${parts.join(',')}}`;
93
+ }
package/dist/index.d.ts CHANGED
@@ -6,3 +6,5 @@ export { STRONG_DEFAULTS, EM_DEFAULTS, CODE_DEFAULTS, LINK_DEFAULTS, HEADING_DEF
6
6
  export { buildBarChartKind, buildLineChartKind, buildPieChartKind, buildAreaChartKind, buildDotPlotKind, } from './charts.js';
7
7
  export type { BarChartProps, LineChartProps, PieChartProps, AreaChartProps, DotPlotProps, } from './charts.js';
8
8
  export type { Style, GridTrackSize, Edges, Corners, EdgeColors, CertificationConfig, SignatureConfig, ColumnDef, BarcodeFormat, ChartDataPoint, PieDataPoint, ChartSeries, DotPlotGroup, CanvasContext, CanvasOp, TextRun, ListMarker, FormeDocument, FormeFont, FormeNode, FormeNodeKind, FormeStyle, FormeMetadata, FormePageConfig, FormePageSize, FormeEdges, FormeBoxShadow, FormeGradientStop, FormeBackground, FormeMarginEdges, FormeColumnDef, FormeColumnWidth, FormeDimension, FormeColor, FormeEdgeValues, FormeCornerValues, FormeGridTrackSize, FormeGridPlacement, FormeListMarkerType, FormeTransformOp, } from './types.js';
9
+ export { parseMarkup } from './parser.js';
10
+ export { encodeProps, reviveBytesMarker } from './encode.js';
package/dist/index.js CHANGED
@@ -8,3 +8,8 @@ export { recordCanvasOperations } from './canvas.js';
8
8
  export { STRONG_DEFAULTS, EM_DEFAULTS, CODE_DEFAULTS, LINK_DEFAULTS, HEADING_DEFAULTS, mapListMarker, } from './semantics.js';
9
9
  // Chart kind builders (shared camelCase-to-snake_case prop mapping)
10
10
  export { buildBarChartKind, buildLineChartKind, buildPieChartKind, buildAreaChartKind, buildDotPlotKind, } from './charts.js';
11
+ // Adapter SSR markup pipeline (shared by the Svelte and Vue adapters):
12
+ // placeholder markup → Forme document model, plus the prop codec both
13
+ // adapters' placeholder components use.
14
+ export { parseMarkup } from './parser.js';
15
+ export { encodeProps, reviveBytesMarker } from './encode.js';
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Markup parser: Svelte SSR output in, Forme document model out.
3
+ *
4
+ * The Forme Svelte components render namespaced placeholder tags
5
+ * (`<forme-document>`, `<forme-page>`, `<forme-view>`, `<forme-text>`)
6
+ * with a single `props` attribute holding the JSON-encoded component
7
+ * props. This module parses that markup - the emitting components and
8
+ * this parser are a matched pair inside this package. The placeholder
9
+ * tag/attribute vocabulary is an INTERNAL contract, not a public
10
+ * format: it may change in any release without notice.
11
+ *
12
+ * Whitespace is normalized to JSX-equivalent semantics so that a
13
+ * `.svelte` template and its TSX counterpart serialize identically:
14
+ * indentation and newlines never leak into text content, while
15
+ * interior spaces and interpolation boundaries are preserved. The
16
+ * Svelte compiler trims fragment edges and collapses inter-element
17
+ * whitespace before we ever see the markup, so the remaining rules
18
+ * are applied here (see `cleanJsxText`). Known divergences from JSX,
19
+ * where the compiler destroys the distinction before serialization -
20
+ * each matches how Svelte itself renders the template to the DOM:
21
+ *
22
+ * - Same-line leading/trailing spaces inside `<Text>` are trimmed
23
+ * (`<Text> a </Text>` → `"a"`; JSX keeps them).
24
+ * - Interpolations split across lines join with a single space
25
+ * (JSX drops the whitespace-only literal between them entirely).
26
+ * - Newlines inside interpolated *values* are treated like template
27
+ * text and collapse to a space.
28
+ */
29
+ import type { FormeDocument } from './index.js';
30
+ export declare function parseMarkup(markup: string): FormeDocument;
package/dist/parser.js ADDED
@@ -0,0 +1,756 @@
1
+ /**
2
+ * Markup parser: Svelte SSR output in, Forme document model out.
3
+ *
4
+ * The Forme Svelte components render namespaced placeholder tags
5
+ * (`<forme-document>`, `<forme-page>`, `<forme-view>`, `<forme-text>`)
6
+ * with a single `props` attribute holding the JSON-encoded component
7
+ * props. This module parses that markup - the emitting components and
8
+ * this parser are a matched pair inside this package. The placeholder
9
+ * tag/attribute vocabulary is an INTERNAL contract, not a public
10
+ * format: it may change in any release without notice.
11
+ *
12
+ * Whitespace is normalized to JSX-equivalent semantics so that a
13
+ * `.svelte` template and its TSX counterpart serialize identically:
14
+ * indentation and newlines never leak into text content, while
15
+ * interior spaces and interpolation boundaries are preserved. The
16
+ * Svelte compiler trims fragment edges and collapses inter-element
17
+ * whitespace before we ever see the markup, so the remaining rules
18
+ * are applied here (see `cleanJsxText`). Known divergences from JSX,
19
+ * where the compiler destroys the distinction before serialization -
20
+ * each matches how Svelte itself renders the template to the DOM:
21
+ *
22
+ * - Same-line leading/trailing spaces inside `<Text>` are trimmed
23
+ * (`<Text> a </Text>` → `"a"`; JSX keeps them).
24
+ * - Interpolations split across lines join with a single space
25
+ * (JSX drops the whitespace-only literal between them entirely).
26
+ * - Newlines inside interpolated *values* are treated like template
27
+ * text and collapse to a space.
28
+ */
29
+ import { parseFragment } from 'parse5';
30
+ import { buildAreaChartKind, buildBarChartKind, buildDotPlotKind, buildLineChartKind, buildPieChartKind, CODE_DEFAULTS, EM_DEFAULTS, expandEdges, Font, HEADING_DEFAULTS, LINK_DEFAULTS, mapColumnWidth, mapListMarker, mapStyle, mergeFonts, parseColor, STRONG_DEFAULTS, } from './index.js';
31
+ import { reviveBytesMarker } from './encode.js';
32
+ function isElement(node) {
33
+ return 'tagName' in node;
34
+ }
35
+ function isText(node) {
36
+ return node.nodeName === '#text';
37
+ }
38
+ export function parseMarkup(markup) {
39
+ const fragment = parseFragment(markup);
40
+ const root = findDocumentRoot(fragment.childNodes);
41
+ const props = decodeProps(root, 'Document');
42
+ // Separate Page children from content children
43
+ const pageNodes = [];
44
+ const contentNodes = [];
45
+ for (const child of root.childNodes) {
46
+ if (isElement(child) && child.tagName === 'forme-page') {
47
+ pageNodes.push(parsePage(child));
48
+ }
49
+ else {
50
+ const node = parseChild(child, 'Document');
51
+ if (node)
52
+ contentNodes.push(node);
53
+ }
54
+ }
55
+ // If there are page nodes, use them. Otherwise the content stands alone.
56
+ let children;
57
+ if (pageNodes.length > 0) {
58
+ // Any loose content nodes get added to the last page's children
59
+ if (contentNodes.length > 0) {
60
+ const lastPage = pageNodes[pageNodes.length - 1];
61
+ lastPage.children.push(...contentNodes);
62
+ }
63
+ children = pageNodes;
64
+ }
65
+ else {
66
+ children = contentNodes;
67
+ }
68
+ const metadata = {};
69
+ if (props.title !== undefined)
70
+ metadata.title = props.title;
71
+ if (props.author !== undefined)
72
+ metadata.author = props.author;
73
+ if (props.subject !== undefined)
74
+ metadata.subject = props.subject;
75
+ if (props.creator !== undefined)
76
+ metadata.creator = props.creator;
77
+ if (props.lang !== undefined)
78
+ metadata.lang = props.lang;
79
+ // Merge global + document fonts (document fonts override on conflict)
80
+ const mergedFonts = mergeFonts(Font.getRegistered(), props.fonts);
81
+ const result = {
82
+ children,
83
+ metadata,
84
+ defaultPage: {
85
+ size: 'A4',
86
+ margin: { top: 54, right: 54, bottom: 54, left: 54 },
87
+ wrap: true,
88
+ },
89
+ };
90
+ if (props.style)
91
+ result.defaultStyle = mapStyle(props.style);
92
+ if (props.tagged !== undefined)
93
+ result.tagged = props.tagged;
94
+ if (props.pdfa !== undefined)
95
+ result.pdfa = props.pdfa;
96
+ if (props.pdfUa)
97
+ result.pdfUa = true;
98
+ const cert = props.certification ?? props.signature;
99
+ if (cert) {
100
+ if (props.signature && !props.certification) {
101
+ console.warn('[Forme] The `signature` prop is deprecated. Use `certification` instead.');
102
+ }
103
+ result.certification = cert;
104
+ }
105
+ if (mergedFonts.length > 0) {
106
+ result.fonts = mergedFonts;
107
+ }
108
+ return result;
109
+ }
110
+ /**
111
+ * Parse one markup node into a Forme node. Returns null for nodes that
112
+ * produce no output (comments, i.e. Svelte SSR block anchors, and
113
+ * whitespace-only text between elements).
114
+ */
115
+ function parseChild(node, parent) {
116
+ if (isElement(node)) {
117
+ return parseElement(node, parent);
118
+ }
119
+ if (isText(node)) {
120
+ // Loose text directly inside a container becomes an anonymous Text
121
+ // node. Edges are trimmed: the Svelte compiler collapses the
122
+ // whitespace around inter-element newlines to a single space, so
123
+ // by the time the markup reaches the parser, indentation and
124
+ // intentional edge spaces are indistinguishable.
125
+ const content = cleanJsxText(node.value).replace(/^[ \t]+|[ \t]+$/g, '');
126
+ if (content === '')
127
+ return null;
128
+ return {
129
+ kind: { type: 'Text', content },
130
+ style: {},
131
+ children: [],
132
+ };
133
+ }
134
+ return null;
135
+ }
136
+ function parseElement(element, parent) {
137
+ switch (element.tagName) {
138
+ case 'forme-view':
139
+ return parseView(element);
140
+ case 'forme-text':
141
+ return parseText(element);
142
+ case 'forme-h1':
143
+ return parseHeading(element, 1);
144
+ case 'forme-h2':
145
+ return parseHeading(element, 2);
146
+ case 'forme-h3':
147
+ return parseHeading(element, 3);
148
+ case 'forme-h4':
149
+ return parseHeading(element, 4);
150
+ case 'forme-h5':
151
+ return parseHeading(element, 5);
152
+ case 'forme-h6':
153
+ return parseHeading(element, 6);
154
+ case 'forme-ordered-list':
155
+ return parseList(element, true);
156
+ case 'forme-unordered-list':
157
+ return parseList(element, false);
158
+ case 'forme-list-item':
159
+ return parseListItem(element);
160
+ case 'forme-table':
161
+ return parseTable(element);
162
+ case 'forme-row':
163
+ validateNesting('Row', parent);
164
+ return parseRow(element);
165
+ case 'forme-cell':
166
+ validateNesting('Cell', parent);
167
+ return parseCell(element);
168
+ case 'forme-fixed':
169
+ return parseFixed(element);
170
+ case 'forme-image':
171
+ return parseImage(element);
172
+ case 'forme-svg':
173
+ return parseSvg(element);
174
+ case 'forme-qrcode':
175
+ return parseQrCode(element);
176
+ case 'forme-barcode':
177
+ return parseBarcode(element);
178
+ case 'forme-canvas':
179
+ return parseCanvas(element);
180
+ case 'forme-watermark':
181
+ return parseWatermark(element);
182
+ case 'forme-bar-chart':
183
+ return parseChart(element, 'BarChart', buildBarChartKind);
184
+ case 'forme-line-chart':
185
+ return parseChart(element, 'LineChart', buildLineChartKind);
186
+ case 'forme-pie-chart':
187
+ return parseChart(element, 'PieChart', buildPieChartKind);
188
+ case 'forme-area-chart':
189
+ return parseChart(element, 'AreaChart', buildAreaChartKind);
190
+ case 'forme-dot-plot':
191
+ return parseChart(element, 'DotPlot', buildDotPlotKind);
192
+ case 'forme-text-field':
193
+ return parseTextField(element);
194
+ case 'forme-checkbox':
195
+ return parseCheckbox(element);
196
+ case 'forme-dropdown':
197
+ return parseDropdown(element);
198
+ case 'forme-radio-button':
199
+ return parseRadioButton(element);
200
+ case 'forme-strong':
201
+ case 'forme-em':
202
+ case 'forme-code':
203
+ case 'forme-link': {
204
+ const name = INLINE_COMPONENT_NAMES[element.tagName];
205
+ throw new Error(`<${name}> is an inline formatting component and must be inside a <Text> or heading. Wrap it: <Text><${name}>...</${name}></Text>`);
206
+ }
207
+ case 'forme-page-break':
208
+ return { kind: { type: 'PageBreak' }, style: {}, children: [] };
209
+ case 'forme-page':
210
+ validateNesting('Page', parent);
211
+ return parsePage(element);
212
+ default:
213
+ throw unknownElementError(element.tagName);
214
+ }
215
+ }
216
+ // ─── Nesting validation ──────────────────────────────────────────────
217
+ const VALID_PARENTS = {
218
+ Page: {
219
+ allowed: ['Document'],
220
+ suggestion: '<Page> must be a direct child of <Document>.',
221
+ },
222
+ Row: {
223
+ allowed: ['Table'],
224
+ suggestion: '<Row> must be inside a <Table>. Wrap it: <Table><Row>...</Row></Table>',
225
+ },
226
+ Cell: {
227
+ allowed: ['Row'],
228
+ suggestion: '<Cell> must be inside a <Row>. Wrap it: <Row><Cell>...</Cell></Row>',
229
+ },
230
+ };
231
+ function validateNesting(componentName, parent) {
232
+ const rule = VALID_PARENTS[componentName];
233
+ if (!rule)
234
+ return;
235
+ if (parent !== null && !rule.allowed.includes(parent)) {
236
+ throw new Error(`Invalid nesting: <${componentName}> found inside <${parent}>. ${rule.suggestion}`);
237
+ }
238
+ }
239
+ // ─── Unknown elements ────────────────────────────────────────────────
240
+ const HTML_SUGGESTIONS = {
241
+ div: 'View', span: 'Text', p: 'Text', h1: 'H1', h2: 'H2',
242
+ h3: 'H3', h4: 'H4', h5: 'H5', h6: 'H6', img: 'Image',
243
+ table: 'Table', tr: 'Row', td: 'Cell', ol: 'OrderedList',
244
+ ul: 'UnorderedList', li: 'ListItem', strong: 'Strong', b: 'Strong',
245
+ em: 'Em', i: 'Em', code: 'Code', a: 'Link',
246
+ };
247
+ function unknownElementError(tagName) {
248
+ const suggestion = HTML_SUGGESTIONS[tagName];
249
+ if (suggestion) {
250
+ return new Error(`HTML element <${tagName}> is not supported. Use <${suggestion}> instead.`);
251
+ }
252
+ return new Error(`Unsupported element <${tagName}> in a Forme template.`);
253
+ }
254
+ function parseChildren(nodes, parent) {
255
+ const children = [];
256
+ for (const node of nodes) {
257
+ const child = parseChild(node, parent);
258
+ if (child)
259
+ children.push(child);
260
+ }
261
+ return children;
262
+ }
263
+ function parsePage(element) {
264
+ const props = decodeProps(element, 'Page');
265
+ let size = 'A4';
266
+ if (props.size !== undefined) {
267
+ if (typeof props.size === 'string') {
268
+ size = props.size;
269
+ }
270
+ else {
271
+ size = { Custom: { width: props.size.width, height: props.size.height } };
272
+ }
273
+ }
274
+ let margin = { top: 54, right: 54, bottom: 54, left: 54 };
275
+ if (props.margin !== undefined) {
276
+ margin = expandEdges(props.margin);
277
+ }
278
+ const config = { size, margin, wrap: true };
279
+ if (props.backgroundImage !== undefined)
280
+ config.backgroundImage = props.backgroundImage;
281
+ if (props.backgroundOpacity !== undefined)
282
+ config.backgroundOpacity = props.backgroundOpacity;
283
+ if (props.backgroundSize !== undefined)
284
+ config.backgroundSize = props.backgroundSize;
285
+ if (props.backgroundPosition !== undefined)
286
+ config.backgroundPosition = props.backgroundPosition;
287
+ return {
288
+ kind: { type: 'Page', config },
289
+ style: props.style ? mapStyle(props.style) : {},
290
+ children: parseChildren(element.childNodes, 'Page'),
291
+ };
292
+ }
293
+ function parseView(element) {
294
+ const props = decodeProps(element, 'View');
295
+ const style = mapStyle(props.style);
296
+ if (props.wrap !== undefined) {
297
+ style.wrap = props.wrap;
298
+ }
299
+ const node = {
300
+ kind: { type: 'View' },
301
+ style,
302
+ children: parseChildren(element.childNodes, 'View'),
303
+ };
304
+ if (props.bookmark)
305
+ node.bookmark = props.bookmark;
306
+ if (props.href)
307
+ node.href = props.href;
308
+ return node;
309
+ }
310
+ function parseText(element) {
311
+ const props = decodeProps(element, 'Text');
312
+ const kind = { type: 'Text', content: '' };
313
+ const runs = textRunsOf(element.childNodes);
314
+ if (runs) {
315
+ kind.runs = runs;
316
+ }
317
+ else {
318
+ kind.content = textContentOf(element.childNodes);
319
+ }
320
+ if (props.href)
321
+ kind.href = props.href;
322
+ const node = {
323
+ kind,
324
+ style: mapStyle(props.style),
325
+ children: [],
326
+ };
327
+ if (props.bookmark)
328
+ node.bookmark = props.bookmark;
329
+ return node;
330
+ }
331
+ /** Inline formatting placeholder tags and their component-default
332
+ * styles. `forme-text` carries no defaults beyond the user's style -
333
+ * same table the react adapter keeps in `inlineDefaults()`. */
334
+ const INLINE_DEFAULTS = {
335
+ 'forme-text': {},
336
+ 'forme-strong': STRONG_DEFAULTS,
337
+ 'forme-em': EM_DEFAULTS,
338
+ 'forme-code': CODE_DEFAULTS,
339
+ 'forme-link': LINK_DEFAULTS,
340
+ };
341
+ const INLINE_COMPONENT_NAMES = {
342
+ 'forme-strong': 'Strong',
343
+ 'forme-em': 'Em',
344
+ 'forme-code': 'Code',
345
+ 'forme-link': 'Link',
346
+ };
347
+ /**
348
+ * Build styled text runs from a Text (or heading) element's children,
349
+ * mirroring the react adapter's `buildTextRuns`: only used when at
350
+ * least one direct child is an inline element (`<Text>`, `<Strong>`,
351
+ * `<Em>`, `<Code>`, `<Link>`) - returns null otherwise. Descent
352
+ * accumulates style and href: the outer accumulated style is overlaid
353
+ * by each inline component's defaults, which are overlaid by the
354
+ * user-supplied `style` on that element, so user style wins at every
355
+ * level. `<Strong><Em>both</Em></Strong>` produces a single run with
356
+ * bold + italic. Elements other than inline components are skipped but
357
+ * still split the surrounding text into separate runs, as react's
358
+ * per-child loop does.
359
+ */
360
+ function textRunsOf(nodes) {
361
+ if (!nodes.some(n => isElement(n) && n.tagName in INLINE_DEFAULTS))
362
+ return null;
363
+ return buildRuns(nodes, {}, undefined);
364
+ }
365
+ function buildRuns(nodes, accStyle, accHref) {
366
+ const runs = [];
367
+ let buffer = '';
368
+ const flush = () => {
369
+ const content = cleanJsxText(buffer);
370
+ buffer = '';
371
+ // JSX drops whitespace-only literals spanning lines but keeps
372
+ // same-line spaces between spans; cleanJsxText reproduces that,
373
+ // leaving only genuinely empty chunks to discard.
374
+ if (content === '')
375
+ return;
376
+ const run = { content };
377
+ if (Object.keys(accStyle).length > 0)
378
+ run.style = mapStyle(accStyle);
379
+ if (accHref)
380
+ run.href = accHref;
381
+ runs.push(run);
382
+ };
383
+ for (const node of nodes) {
384
+ if (isText(node)) {
385
+ buffer += node.value;
386
+ }
387
+ else if (isElement(node)) {
388
+ flush();
389
+ const defaults = INLINE_DEFAULTS[node.tagName];
390
+ if (defaults === undefined)
391
+ continue; // unknown element inside <Text> - skip
392
+ const props = decodeProps(node, INLINE_COMPONENT_NAMES[node.tagName] ?? 'Text');
393
+ // Cascade: outer accumulated -> this component's defaults -> user
394
+ // style. Later spreads win, so user style overrides defaults and
395
+ // outer.
396
+ const nextStyle = { ...accStyle, ...defaults, ...(props.style || {}) };
397
+ const nextHref = props.href ?? accHref;
398
+ runs.push(...buildRuns(node.childNodes, nextStyle, nextHref));
399
+ }
400
+ // Comments (SSR block anchors) fall through: the text around them
401
+ // stays one contiguous chunk.
402
+ }
403
+ flush();
404
+ return runs;
405
+ }
406
+ /**
407
+ * Parse an H1-H6 placeholder. Mirrors parseText for the children
408
+ * machinery (mixed strings + inline-formatting components produce
409
+ * runs) but emits the engine's `Heading { level }` node kind so the
410
+ * tagged-PDF builder can pick up the semantic role. Default styles per
411
+ * level are merged BEFORE the user's `style` prop, so user values win.
412
+ */
413
+ function parseHeading(element, level) {
414
+ const props = decodeProps(element, `H${level}`);
415
+ const kind = { type: 'Heading', level, content: '' };
416
+ const runs = textRunsOf(element.childNodes);
417
+ if (runs) {
418
+ kind.runs = runs;
419
+ }
420
+ else {
421
+ kind.content = textContentOf(element.childNodes);
422
+ }
423
+ if (props.href)
424
+ kind.href = props.href;
425
+ // Defaults underlay; user style wins on conflicting keys.
426
+ const mergedStyle = { ...HEADING_DEFAULTS[level], ...(props.style || {}) };
427
+ const node = {
428
+ kind,
429
+ style: mapStyle(mergedStyle),
430
+ children: [],
431
+ };
432
+ if (props.bookmark)
433
+ node.bookmark = props.bookmark;
434
+ return node;
435
+ }
436
+ function parseList(element, ordered) {
437
+ const props = decodeProps(element, ordered ? 'OrderedList' : 'UnorderedList');
438
+ const markerType = ordered
439
+ ? mapListMarker(props.type, 'decimal')
440
+ : mapListMarker(props.marker, 'disc');
441
+ const start = typeof props.start === 'number' && props.start >= 1 ? props.start : 1;
442
+ // Children must be ListItems - anything else is silently dropped to
443
+ // keep the serializer tolerant, matching the react adapter. (Loose
444
+ // whitespace and `{#if}` anchors between items are too common to be
445
+ // a real error.)
446
+ const children = element.childNodes
447
+ .filter((c) => isElement(c) && c.tagName === 'forme-list-item')
448
+ .map(c => parseListItem(c));
449
+ const node = {
450
+ kind: { type: 'List', ordered, marker_type: markerType, start },
451
+ style: mapStyle(props.style),
452
+ children,
453
+ };
454
+ if (props.bookmark)
455
+ node.bookmark = props.bookmark;
456
+ return node;
457
+ }
458
+ function parseListItem(element) {
459
+ const props = decodeProps(element, 'ListItem');
460
+ // ListItem content is laid out by the engine using layout_children,
461
+ // so whatever the user put inside serializes as the node's children.
462
+ // Loose strings auto-wrap in a Text node via parseChild, matching
463
+ // the react adapter's convention.
464
+ return {
465
+ kind: { type: 'ListItem' },
466
+ style: mapStyle(props.style),
467
+ children: parseChildren(element.childNodes, null),
468
+ };
469
+ }
470
+ /**
471
+ * Extract the merged text content of a Text element's children.
472
+ * Comments (Svelte SSR block anchors) vanish and the text around them
473
+ * is treated as one contiguous chunk, so `{#if}`/`{#each}` boundaries
474
+ * inside a `<Text>` never introduce breaks. Element children
475
+ * contribute their own descendant text (react's flattenTextContent
476
+ * recurses the same way).
477
+ */
478
+ function textContentOf(nodes) {
479
+ return cleanJsxText(rawTextOf(nodes));
480
+ }
481
+ function rawTextOf(nodes) {
482
+ let merged = '';
483
+ for (const node of nodes) {
484
+ if (isText(node))
485
+ merged += node.value;
486
+ else if (isElement(node))
487
+ merged += rawTextOf(node.childNodes);
488
+ }
489
+ return merged;
490
+ }
491
+ function parseTable(element) {
492
+ const props = decodeProps(element, 'Table');
493
+ const columns = (props.columns ?? []).map(col => ({
494
+ width: mapColumnWidth(col.width),
495
+ }));
496
+ return {
497
+ kind: { type: 'Table', columns },
498
+ style: mapStyle(props.style),
499
+ children: parseChildren(element.childNodes, 'Table'),
500
+ };
501
+ }
502
+ function parseRow(element) {
503
+ const props = decodeProps(element, 'Row');
504
+ return {
505
+ kind: { type: 'TableRow', is_header: props.header ?? false },
506
+ style: mapStyle(props.style),
507
+ children: parseChildren(element.childNodes, 'Row'),
508
+ };
509
+ }
510
+ function parseCell(element) {
511
+ const props = decodeProps(element, 'Cell');
512
+ return {
513
+ kind: { type: 'TableCell', col_span: props.colSpan ?? 1, row_span: props.rowSpan ?? 1 },
514
+ style: mapStyle(props.style),
515
+ children: parseChildren(element.childNodes, 'Cell'),
516
+ };
517
+ }
518
+ function parseFixed(element) {
519
+ const props = decodeProps(element, 'Fixed');
520
+ // Mirrors react: anything other than 'header' falls back to Footer.
521
+ const position = props.position === 'header' ? 'Header' : 'Footer';
522
+ const node = {
523
+ kind: { type: 'Fixed', position },
524
+ style: mapStyle(props.style),
525
+ children: parseChildren(element.childNodes, 'Fixed'),
526
+ };
527
+ if (props.bookmark)
528
+ node.bookmark = props.bookmark;
529
+ return node;
530
+ }
531
+ function parseImage(element) {
532
+ const props = decodeProps(element, 'Image');
533
+ const kind = { type: 'Image', src: props.src };
534
+ if (props.width !== undefined)
535
+ kind.width = props.width;
536
+ if (props.height !== undefined)
537
+ kind.height = props.height;
538
+ const node = {
539
+ kind,
540
+ style: mapStyle(props.style),
541
+ children: [],
542
+ };
543
+ if (props.href)
544
+ node.href = props.href;
545
+ if (props.alt)
546
+ node.alt = props.alt;
547
+ return node;
548
+ }
549
+ function parseSvg(element) {
550
+ const props = decodeProps(element, 'Svg');
551
+ const kind = {
552
+ type: 'Svg',
553
+ width: props.width,
554
+ height: props.height,
555
+ content: props.content ?? '',
556
+ };
557
+ if (props.viewBox)
558
+ kind.view_box = props.viewBox;
559
+ const node = {
560
+ kind,
561
+ style: mapStyle(props.style),
562
+ children: [],
563
+ };
564
+ if (props.href)
565
+ node.href = props.href;
566
+ if (props.alt)
567
+ node.alt = props.alt;
568
+ return node;
569
+ }
570
+ function parseQrCode(element) {
571
+ const props = decodeProps(element, 'QrCode');
572
+ const kind = { type: 'QrCode', data: props.data };
573
+ if (props.size !== undefined)
574
+ kind.size = props.size;
575
+ const style = mapStyle(props.style);
576
+ if (props.color)
577
+ style.color = parseColor(props.color);
578
+ return { kind, style, children: [] };
579
+ }
580
+ function parseBarcode(element) {
581
+ const props = decodeProps(element, 'Barcode');
582
+ const kind = {
583
+ type: 'Barcode',
584
+ data: props.data,
585
+ format: props.format ?? 'Code128',
586
+ height: props.height ?? 60,
587
+ };
588
+ if (props.width !== undefined)
589
+ kind.width = props.width;
590
+ const style = mapStyle(props.style);
591
+ if (props.color)
592
+ style.color = parseColor(props.color);
593
+ return { kind, style, children: [] };
594
+ }
595
+ function parseCanvas(element) {
596
+ const props = decodeProps(element, 'Canvas');
597
+ return {
598
+ kind: { type: 'Canvas', width: props.width, height: props.height, operations: props.operations },
599
+ style: mapStyle(props.style),
600
+ children: [],
601
+ };
602
+ }
603
+ function parseWatermark(element) {
604
+ const props = decodeProps(element, 'Watermark');
605
+ const fontSize = props.fontSize ?? 60;
606
+ const angle = props.angle ?? -45;
607
+ // Mirrors react: the color's alpha channel becomes opacity (multiplied
608
+ // with any style opacity); the stored color itself is fully opaque.
609
+ const parsed = parseColor(props.color ?? 'rgba(0,0,0,0.1)');
610
+ const style = mapStyle(props.style);
611
+ style.color = { r: parsed.r, g: parsed.g, b: parsed.b, a: 1 };
612
+ style.opacity = parsed.a * (style.opacity ?? 1);
613
+ style.fontSize = fontSize;
614
+ return {
615
+ kind: { type: 'Watermark', text: props.text, font_size: fontSize, angle },
616
+ style,
617
+ children: [],
618
+ };
619
+ }
620
+ function parseTextField(element) {
621
+ const props = decodeProps(element, 'TextField');
622
+ const kind = {
623
+ type: 'TextField',
624
+ name: props.name,
625
+ width: props.width,
626
+ height: props.height ?? 24,
627
+ multiline: props.multiline ?? false,
628
+ password: props.password ?? false,
629
+ read_only: props.readOnly ?? false,
630
+ font_size: props.fontSize ?? 12,
631
+ };
632
+ if (props.value !== undefined)
633
+ kind.value = props.value;
634
+ if (props.placeholder !== undefined)
635
+ kind.placeholder = props.placeholder;
636
+ if (props.maxLength !== undefined)
637
+ kind.max_length = props.maxLength;
638
+ return { kind, style: mapStyle(props.style), children: [] };
639
+ }
640
+ function parseCheckbox(element) {
641
+ const props = decodeProps(element, 'Checkbox');
642
+ return {
643
+ kind: {
644
+ type: 'Checkbox',
645
+ name: props.name,
646
+ checked: props.checked ?? false,
647
+ width: props.width ?? 14,
648
+ height: props.height ?? 14,
649
+ read_only: props.readOnly ?? false,
650
+ },
651
+ style: mapStyle(props.style),
652
+ children: [],
653
+ };
654
+ }
655
+ function parseDropdown(element) {
656
+ const props = decodeProps(element, 'Dropdown');
657
+ const kind = {
658
+ type: 'Dropdown',
659
+ name: props.name,
660
+ options: props.options,
661
+ width: props.width,
662
+ height: props.height ?? 24,
663
+ read_only: props.readOnly ?? false,
664
+ font_size: props.fontSize ?? 12,
665
+ };
666
+ if (props.value !== undefined)
667
+ kind.value = props.value;
668
+ return { kind, style: mapStyle(props.style), children: [] };
669
+ }
670
+ function parseRadioButton(element) {
671
+ const props = decodeProps(element, 'RadioButton');
672
+ return {
673
+ kind: {
674
+ type: 'RadioButton',
675
+ name: props.name,
676
+ value: props.value,
677
+ checked: props.checked ?? false,
678
+ width: props.width ?? 14,
679
+ height: props.height ?? 14,
680
+ read_only: props.readOnly ?? false,
681
+ },
682
+ style: mapStyle(props.style),
683
+ children: [],
684
+ };
685
+ }
686
+ // ─── Charts ──────────────────────────────────────────────────────────
687
+ /**
688
+ * Parse one chart placeholder. The camelCase-to-snake_case prop
689
+ * mapping (and its defaults) lives in the shared kind builders, the
690
+ * same functions the react adapter serializes with, so the two
691
+ * adapters cannot drift.
692
+ */
693
+ function parseChart(element, component, buildKind) {
694
+ const props = decodeProps(element, component);
695
+ return {
696
+ kind: buildKind(props),
697
+ style: mapStyle(props.style),
698
+ children: [],
699
+ };
700
+ }
701
+ // ─── Whitespace normalization ────────────────────────────────────────
702
+ /**
703
+ * Normalize template text to JSX-equivalent semantics - the same
704
+ * algorithm Babel, TypeScript, and esbuild apply to JSX text literals:
705
+ *
706
+ * - lines are trimmed (leading whitespace on all but the first line,
707
+ * trailing whitespace on all but the last line) and joined with a
708
+ * single space; whitespace-only lines are dropped
709
+ * - tabs count as spaces
710
+ * - only ASCII space/tab are trimmed, so non-breaking spaces survive
711
+ */
712
+ function cleanJsxText(text) {
713
+ const lines = text.split(/\r\n|\n|\r/);
714
+ let lastNonEmptyLine = 0;
715
+ for (let i = 0; i < lines.length; i++) {
716
+ if (/[^ \t]/.test(lines[i]))
717
+ lastNonEmptyLine = i;
718
+ }
719
+ let str = '';
720
+ for (let i = 0; i < lines.length; i++) {
721
+ const isFirstLine = i === 0;
722
+ const isLastLine = i === lines.length - 1;
723
+ const isLastNonEmptyLine = i === lastNonEmptyLine;
724
+ let trimmed = lines[i].replace(/\t/g, ' ');
725
+ if (!isFirstLine)
726
+ trimmed = trimmed.replace(/^ +/, '');
727
+ if (!isLastLine)
728
+ trimmed = trimmed.replace(/ +$/, '');
729
+ if (trimmed) {
730
+ if (!isLastNonEmptyLine)
731
+ trimmed += ' ';
732
+ str += trimmed;
733
+ }
734
+ }
735
+ return str;
736
+ }
737
+ function findDocumentRoot(nodes) {
738
+ for (const node of nodes) {
739
+ if (isElement(node) && node.tagName === 'forme-document') {
740
+ return node;
741
+ }
742
+ }
743
+ throw new Error('Top-level element must be <Document>');
744
+ }
745
+ /** Decode the JSON `props` attribute of a placeholder element. */
746
+ function decodeProps(element, component) {
747
+ const attr = element.attrs.find(a => a.name === 'props');
748
+ if (attr === undefined)
749
+ return {};
750
+ try {
751
+ return JSON.parse(attr.value, reviveBytesMarker);
752
+ }
753
+ catch (err) {
754
+ throw new Error(`[Forme] <${component}>: failed to decode props attribute: ${err instanceof Error ? err.message : String(err)}`);
755
+ }
756
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@formepdf/shared",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "Framework-agnostic document model and serialization core shared by Forme adapters",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -13,10 +13,15 @@
13
13
  }
14
14
  },
15
15
  "scripts": {
16
- "build": "tsc"
16
+ "build": "tsc",
17
+ "test": "vitest run"
18
+ },
19
+ "dependencies": {
20
+ "parse5": "^7.2.1"
17
21
  },
18
22
  "devDependencies": {
19
- "typescript": "^5.7.0"
23
+ "typescript": "^5.7.0",
24
+ "vitest": "^3.0.0"
20
25
  },
21
26
  "files": [
22
27
  "dist"