@formepdf/core 0.12.0 → 0.13.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/dist/index.d.ts CHANGED
@@ -17,42 +17,163 @@ export interface CornerValues {
17
17
  bottom_right: number;
18
18
  bottom_left: number;
19
19
  }
20
+ export type ElementFlexDirection = 'Row' | 'Column' | 'RowReverse' | 'ColumnReverse';
21
+ export type ElementJustifyContent = 'FlexStart' | 'FlexEnd' | 'Center' | 'SpaceBetween' | 'SpaceAround' | 'SpaceEvenly';
22
+ export type ElementAlignItems = 'FlexStart' | 'FlexEnd' | 'Center' | 'Stretch' | 'Baseline';
23
+ export type ElementAlignContent = 'FlexStart' | 'FlexEnd' | 'Center' | 'SpaceBetween' | 'SpaceAround' | 'SpaceEvenly' | 'Stretch';
24
+ export type ElementFlexWrap = 'NoWrap' | 'Wrap' | 'WrapReverse';
25
+ export type ElementFontStyle = 'Normal' | 'Italic' | 'Oblique';
26
+ export type ElementTextAlign = 'Left' | 'Right' | 'Center' | 'Justify';
27
+ export type ElementTextDecoration = 'None' | 'Underline' | 'LineThrough';
28
+ export type ElementTextTransform = 'None' | 'Uppercase' | 'Lowercase' | 'Capitalize';
29
+ export type ElementOverflow = 'Visible' | 'Hidden';
30
+ export type ElementPosition = 'Relative' | 'Absolute';
31
+ /**
32
+ * Semantic role of a layout node. Note the specific transforms below
33
+ * (also documented on `ElementInfo`) — this union describes what the
34
+ * runtime actually emits, not what the JSX author wrote:
35
+ *
36
+ * - Six discrete heading tags (`H1`–`H6`) — NO generic `'Heading'`
37
+ * - `TableRow` / `TableCell` — NO `Table` wrapper (unwrapped by layout)
38
+ * - `List` + `ListItem` + `Lbl` — from `<OrderedList>` / `<UnorderedList>`
39
+ * - `FixedHeader` / `FixedFooter` — NO single `Fixed` (split by position)
40
+ * - `Bookmark` — zero-height marker from `bookmark` on a container, emitted
41
+ * on every container path (fits or overflowing) and the sole carrier of
42
+ * the outline entry
43
+ * - `TextLine` — leaf lines under `Text` blocks (holds `textContent`)
44
+ * - Inline `<Strong>`/`<Em>`/`<Code>`/`<Link>` do not appear here;
45
+ * they contribute style runs within `TextLine`
46
+ *
47
+ * ### When adding a new value here
48
+ *
49
+ * Also add a `<Component>` that produces the new nodeType to
50
+ * `RICH_FIXTURE` in `packages/core/tests/layout-shape.test.ts`.
51
+ * A coverage tripwire in that file fails otherwise ("declared but
52
+ * never rendered"), on the exact drift risk this whole file exists
53
+ * to prevent.
54
+ */
55
+ export type ElementNodeType = 'View' | 'Text' | 'TextLine' | 'H1' | 'H2' | 'H3' | 'H4' | 'H5' | 'H6' | 'TableRow' | 'TableCell' | 'List' | 'ListItem' | 'Lbl' | 'FixedHeader' | 'FixedFooter' | 'Bookmark' | 'Image' | 'Svg' | 'QrCode' | 'Barcode' | 'Canvas' | 'Watermark' | 'BarChart' | 'LineChart' | 'PieChart' | 'AreaChart' | 'DotPlot' | 'TextField' | 'Checkbox' | 'Dropdown' | 'RadioButton';
56
+ /**
57
+ * Drawing kind for the node. Governs the PDF operator the serializer
58
+ * emits; NOT the same as `nodeType`, which describes semantic role.
59
+ */
60
+ export type ElementKind = 'None' | 'Rect' | 'Text' | 'Image' | 'Svg' | 'QrCode' | 'Barcode' | 'Chart' | 'FormField' | 'Watermark';
20
61
  export interface ElementStyleInfo {
62
+ flexDirection: ElementFlexDirection;
63
+ justifyContent: ElementJustifyContent;
64
+ alignItems: ElementAlignItems;
65
+ alignContent: ElementAlignContent;
66
+ flexWrap: ElementFlexWrap;
67
+ flexGrow: number;
68
+ flexShrink: number;
69
+ gap: number;
70
+ columnGap: number;
71
+ rowGap: number;
72
+ position: ElementPosition;
73
+ /** Offset from parent, in points. Only meaningful when `position === 'Absolute'`. */
74
+ top?: number;
75
+ right?: number;
76
+ bottom?: number;
77
+ left?: number;
21
78
  margin: EdgeValues<number>;
22
79
  padding: EdgeValues<number>;
23
80
  borderWidth: EdgeValues<number>;
24
- flexDirection: string;
25
- justifyContent: string;
26
- alignItems: string;
27
- flexWrap: string;
28
- gap: number;
81
+ borderColor: EdgeValues<Color>;
82
+ borderRadius: CornerValues;
83
+ /**
84
+ * Explicit `style.width` from the source. May be a number (points) or
85
+ * a stringified value (e.g. percentage) — the layout engine formats
86
+ * some dimension variants as strings in the JSON output. Prefer the
87
+ * top-level `ElementInfo.width` for the resolved rendered width.
88
+ */
89
+ width?: number | string;
90
+ /** Explicit `style.height`. See `width` for shape notes. */
91
+ height?: number | string;
29
92
  fontFamily: string;
30
93
  fontSize: number;
31
94
  fontWeight: number;
32
- fontStyle: string;
95
+ fontStyle: ElementFontStyle;
33
96
  lineHeight: number;
34
- textAlign: string;
97
+ letterSpacing: number;
98
+ textAlign: ElementTextAlign;
99
+ textDecoration: ElementTextDecoration;
100
+ textTransform: ElementTextTransform;
35
101
  color: Color;
36
102
  backgroundColor: Color | null;
37
- borderColor: EdgeValues<Color>;
38
- borderRadius: CornerValues;
39
103
  opacity: number;
104
+ overflow: ElementOverflow;
105
+ breakBefore: boolean;
106
+ breakable: boolean;
107
+ minOrphanLines: number;
108
+ minWidowLines: number;
40
109
  }
110
+ /**
111
+ * A single node in the layout tree returned by
112
+ * `renderDocumentWithLayout()`. The tree does NOT mirror the JSX
113
+ * source — several transforms happen during layout:
114
+ *
115
+ * - `<Table>` is unwrapped. Its `<Row>` children appear as sibling
116
+ * `TableRow` nodes at the containing page/View level. There is no
117
+ * `Table` wrapper node.
118
+ * - `<OrderedList>` and `<UnorderedList>` both produce a `List` node
119
+ * containing `ListItem` children. Each `ListItem` has a `Lbl` child
120
+ * (the marker "1." / "•") followed by the item's own content children.
121
+ * - `<Fixed position="header">` produces a `FixedHeader` nodeType and
122
+ * `<Fixed position="footer">` produces `FixedFooter`. There is no
123
+ * single `Fixed` nodeType.
124
+ * - Headings render as six discrete `H1` … `H6` nodeTypes. There is
125
+ * no generic `Heading` nodeType with a `level` field.
126
+ * - `<Text>` block content is split into `TextLine` leaf children.
127
+ * The actual text lives on `TextLine.textContent`; on non-`TextLine`
128
+ * nodes (including the parent `Text` block), `textContent` is `null`.
129
+ * - Inline elements (`<Strong>`, `<Em>`, `<Code>`, `<Link>`) do NOT
130
+ * appear as their own nodes — they contribute style runs within
131
+ * `TextLine` leaves.
132
+ * - `<PageBreak>` produces no node. It triggers a page break at
133
+ * layout time and is otherwise invisible.
134
+ * - `bookmark` on a container (`<View>`, `<Page>`, and bare `<ListItem>` /
135
+ * `<TableRow>` / `<TableCell>`) produces a zero-height `Bookmark` marker
136
+ * node (no rect, draws nothing) so the entry reaches the PDF outline.
137
+ * The marker is emitted whether or not the container overflows a page,
138
+ * and it is the ONLY element carrying that `bookmark` — one marker, one
139
+ * outline entry.
140
+ * Caveat: `bookmark` on a NON-container (`<Text>`, `<Image>`, `<Svg>`,
141
+ * charts, form fields) still rides on that node's own element, and rows
142
+ * or cells laid out inside a `<Table>` carry it on the row/cell element.
143
+ * So `Bookmark` nodes are not an exhaustive index of the document's
144
+ * bookmarks — scan the `bookmark` field for that.
145
+ *
146
+ * The runtime-conformance test in this package asserts every one of
147
+ * these transforms explicitly. If it breaks, update this JSDoc first.
148
+ */
41
149
  export interface ElementInfo {
42
150
  x: number;
43
151
  y: number;
44
152
  width: number;
45
153
  height: number;
46
- kind: string;
47
- nodeType: string;
154
+ kind: ElementKind;
155
+ nodeType: ElementNodeType;
48
156
  style: ElementStyleInfo;
49
157
  children: ElementInfo[];
158
+ /**
159
+ * Rendered text for this line. Present ONLY on `TextLine` nodeType
160
+ * leaves — every non-`TextLine` node (including the parent `Text`
161
+ * block) emits `null` here at runtime. If you need the text of a
162
+ * `Text` block, concatenate its `TextLine` children's `textContent`.
163
+ */
164
+ textContent?: string | null;
165
+ /**
166
+ * Source file / line / column of the JSX that produced this node.
167
+ * Populated only when the render pipeline seeds
168
+ * `globalThis.__formeSourceMap` — currently only the CLI dev server
169
+ * does that. Production `renderDocument` / `renderDocumentWithLayout`
170
+ * calls never populate this field.
171
+ */
50
172
  sourceLocation?: {
51
173
  file: string;
52
174
  line: number;
53
175
  column: number;
54
176
  };
55
- textContent?: string;
56
177
  }
57
178
  export interface PageInfo {
58
179
  width: number;
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Stable accessor helpers for the layout tree returned by
3
+ * `renderDocumentWithLayout()`.
4
+ *
5
+ * These helpers exist for one specific reason: the raw `ElementInfo` /
6
+ * `LayoutInfo` shape is documented but the documentation is not a
7
+ * contract, and it has drifted from runtime twice now. Consumers that
8
+ * hard-code invariants like "the text lives on `TextLine` children,
9
+ * not the parent `Text`" break silently every time an internal refactor
10
+ * shifts them.
11
+ *
12
+ * The helpers in this module encapsulate those invariants once, in a
13
+ * narrow, deliberately-maintained surface. Each helper corresponds to
14
+ * one of the layout-time transforms documented on `ElementInfo`. When
15
+ * an invariant changes in the engine, this file is where you update it
16
+ * — the runtime-conformance test (`tests/layout-shape.test.ts`) catches
17
+ * engine drift; helper tests (`tests/layout-helpers.test.ts`) catch
18
+ * drift in the helpers themselves.
19
+ *
20
+ * **Prefer these helpers to raw tree walking unless you specifically
21
+ * need raw shape access** (e.g. custom snapshot comparison, structural
22
+ * analysis the helpers don't cover).
23
+ */
24
+ import type { LayoutInfo, PageInfo, ElementInfo, ElementNodeType } from './index.js';
25
+ /**
26
+ * Any of the layout-tree root shapes a helper might reasonably accept.
27
+ * All helpers that traverse the tree accept this union so consumers
28
+ * don't have to unwrap `layout.pages[0].elements` themselves.
29
+ */
30
+ export type LayoutRoot = LayoutInfo | PageInfo | PageInfo[] | ElementInfo | ElementInfo[];
31
+ /**
32
+ * Depth-first walk of every node in `root`, calling `cb` for each.
33
+ *
34
+ * `path` is a human-readable string identifying where in the tree the
35
+ * node lives (e.g. `"[0].children[2]"` for the third child of the first
36
+ * root element). Useful for building error messages; ignore if you
37
+ * don't need it.
38
+ *
39
+ * Callbacks that return `false` skip descent into that node's children.
40
+ * Any other return (including `void`) descends normally.
41
+ */
42
+ export declare function walkElements(root: LayoutRoot, cb: (node: ElementInfo, path: string) => void | boolean): void;
43
+ /**
44
+ * Every node in `root` for which `predicate` returns truthy. Order is
45
+ * depth-first, source-order.
46
+ */
47
+ export declare function findElements(root: LayoutRoot, predicate: (node: ElementInfo, path: string) => boolean): ElementInfo[];
48
+ /**
49
+ * First node in `root` for which `predicate` returns truthy, or `null`
50
+ * if none. Order is depth-first, source-order. Stops as soon as a match
51
+ * is found (does not descend into the match's children).
52
+ */
53
+ export declare function findFirstElement(root: LayoutRoot, predicate: (node: ElementInfo, path: string) => boolean): ElementInfo | null;
54
+ /**
55
+ * Every `TextLine` leaf descendant of `node`, in source order. If
56
+ * `node` is itself a `TextLine`, returns `[node]`.
57
+ *
58
+ * This is the load-bearing helper: it encapsulates the invariant that
59
+ * text lives on `TextLine` children, never on the parent `Text` block.
60
+ */
61
+ export declare function getTextLines(node: ElementInfo): ElementInfo[];
62
+ /**
63
+ * Concatenated text of every `TextLine` descendant of `node`, joined
64
+ * with `"\n"`. If `node` is itself a `TextLine`, returns its own text.
65
+ *
66
+ * Lines are joined with newlines rather than spaces because the layout
67
+ * engine may have wrapped a single JSX string across multiple lines,
68
+ * and preserving that structure is more useful than silently smushing
69
+ * or space-joining. If you want a flat string, `.replace(/\n/g, ' ')`
70
+ * the result.
71
+ *
72
+ * Returns `""` if no `TextLine` descendants exist.
73
+ */
74
+ export declare function getNodeText(node: ElementInfo): string;
75
+ /**
76
+ * If `node` is a heading (`H1`–`H6`), returns the numeric level (1–6).
77
+ * Returns `null` otherwise.
78
+ *
79
+ * Encapsulates the invariant that headings render as six discriminated
80
+ * nodeTypes (`H1`, `H2`, …) rather than a generic `Heading` node with a
81
+ * separate `level` field.
82
+ */
83
+ export declare function getHeadingLevel(node: ElementInfo): 1 | 2 | 3 | 4 | 5 | 6 | null;
84
+ /**
85
+ * Every `TableRow` that is a direct child of `parent`.
86
+ *
87
+ * Encapsulates the invariant that `<Table>` unwraps at layout time —
88
+ * its `<Row>` children become sibling `TableRow` nodes on the
89
+ * containing page/View, and there is no `Table` wrapper node to hang
90
+ * rows off of. Pass the containing `page` (or the parent `View` that
91
+ * held the `<Table>` in JSX) as `parent`.
92
+ *
93
+ * Returns rows in source order.
94
+ */
95
+ export declare function getTableRows(parent: PageInfo | ElementInfo): ElementInfo[];
96
+ /**
97
+ * The `FixedHeader` and `FixedFooter` nodes on `page`. Encapsulates the
98
+ * invariant that `<Fixed position="header">` and `<Fixed position="footer">`
99
+ * produce two distinct nodeTypes rather than a shared `Fixed` node with
100
+ * a `position` field.
101
+ *
102
+ * Both arrays may be empty. Multiple entries in either array indicate
103
+ * repeating fixed regions (e.g. when the same `<Fixed>` repeats across
104
+ * page breaks — the layout may emit one node per occurrence).
105
+ */
106
+ export declare function getFixedRegions(page: PageInfo): {
107
+ header: ElementInfo[];
108
+ footer: ElementInfo[];
109
+ };
110
+ /**
111
+ * Every `ListItem` child of a `List` node. Returns `[]` if `list` is
112
+ * not a `List` (silently — no throw, so this composes cleanly with
113
+ * `.flatMap`).
114
+ */
115
+ export declare function getListItems(list: ElementInfo): ElementInfo[];
116
+ /**
117
+ * Rendered text of the marker (`Lbl`) child of a `ListItem` — e.g.
118
+ * `"1."` for the first item of an `<OrderedList>`, `"•"` for an
119
+ * `<UnorderedList>` item. Returns `null` if `item` is not a `ListItem`
120
+ * or has no `Lbl` child.
121
+ *
122
+ * Encapsulates the invariant that list markers are separate `Lbl`
123
+ * children of each `ListItem` rather than a field on `ListItem` itself.
124
+ */
125
+ export declare function getListItemMarker(item: ElementInfo): string | null;
126
+ /**
127
+ * Type-guard for narrowing to a specific `ElementNodeType`. Useful for
128
+ * `.filter(isNodeType('TableRow'))` chains.
129
+ */
130
+ export declare function isNodeType<T extends ElementNodeType>(nodeType: T): (node: ElementInfo) => node is ElementInfo & {
131
+ nodeType: T;
132
+ };
package/dist/layout.js ADDED
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Stable accessor helpers for the layout tree returned by
3
+ * `renderDocumentWithLayout()`.
4
+ *
5
+ * These helpers exist for one specific reason: the raw `ElementInfo` /
6
+ * `LayoutInfo` shape is documented but the documentation is not a
7
+ * contract, and it has drifted from runtime twice now. Consumers that
8
+ * hard-code invariants like "the text lives on `TextLine` children,
9
+ * not the parent `Text`" break silently every time an internal refactor
10
+ * shifts them.
11
+ *
12
+ * The helpers in this module encapsulate those invariants once, in a
13
+ * narrow, deliberately-maintained surface. Each helper corresponds to
14
+ * one of the layout-time transforms documented on `ElementInfo`. When
15
+ * an invariant changes in the engine, this file is where you update it
16
+ * — the runtime-conformance test (`tests/layout-shape.test.ts`) catches
17
+ * engine drift; helper tests (`tests/layout-helpers.test.ts`) catch
18
+ * drift in the helpers themselves.
19
+ *
20
+ * **Prefer these helpers to raw tree walking unless you specifically
21
+ * need raw shape access** (e.g. custom snapshot comparison, structural
22
+ * analysis the helpers don't cover).
23
+ */
24
+ function normalizeRoot(root) {
25
+ if (Array.isArray(root)) {
26
+ // ElementInfo[] or PageInfo[]
27
+ if (root.length === 0)
28
+ return [];
29
+ if ('elements' in root[0]) {
30
+ // PageInfo[]
31
+ return root.flatMap((p) => p.elements);
32
+ }
33
+ return root;
34
+ }
35
+ if ('pages' in root)
36
+ return root.pages.flatMap((p) => p.elements); // LayoutInfo
37
+ if ('elements' in root)
38
+ return root.elements; // PageInfo
39
+ return [root]; // ElementInfo
40
+ }
41
+ // ── Traversal ──────────────────────────────────────────────────────
42
+ /**
43
+ * Depth-first walk of every node in `root`, calling `cb` for each.
44
+ *
45
+ * `path` is a human-readable string identifying where in the tree the
46
+ * node lives (e.g. `"[0].children[2]"` for the third child of the first
47
+ * root element). Useful for building error messages; ignore if you
48
+ * don't need it.
49
+ *
50
+ * Callbacks that return `false` skip descent into that node's children.
51
+ * Any other return (including `void`) descends normally.
52
+ */
53
+ export function walkElements(root, cb) {
54
+ const roots = normalizeRoot(root);
55
+ const stack = [];
56
+ // Reverse-push so we process in source order.
57
+ for (let i = roots.length - 1; i >= 0; i--) {
58
+ stack.push({ node: roots[i], path: `[${i}]` });
59
+ }
60
+ while (stack.length > 0) {
61
+ const { node, path } = stack.pop();
62
+ const skip = cb(node, path) === false;
63
+ if (skip)
64
+ continue;
65
+ for (let i = node.children.length - 1; i >= 0; i--) {
66
+ stack.push({ node: node.children[i], path: `${path}.children[${i}]` });
67
+ }
68
+ }
69
+ }
70
+ /**
71
+ * Every node in `root` for which `predicate` returns truthy. Order is
72
+ * depth-first, source-order.
73
+ */
74
+ export function findElements(root, predicate) {
75
+ const hits = [];
76
+ walkElements(root, (node, path) => {
77
+ if (predicate(node, path))
78
+ hits.push(node);
79
+ });
80
+ return hits;
81
+ }
82
+ /**
83
+ * First node in `root` for which `predicate` returns truthy, or `null`
84
+ * if none. Order is depth-first, source-order. Stops as soon as a match
85
+ * is found (does not descend into the match's children).
86
+ */
87
+ export function findFirstElement(root, predicate) {
88
+ let hit = null;
89
+ walkElements(root, (node, path) => {
90
+ if (hit !== null)
91
+ return false;
92
+ if (predicate(node, path)) {
93
+ hit = node;
94
+ return false;
95
+ }
96
+ });
97
+ return hit;
98
+ }
99
+ // ── Text access ────────────────────────────────────────────────────
100
+ /**
101
+ * Every `TextLine` leaf descendant of `node`, in source order. If
102
+ * `node` is itself a `TextLine`, returns `[node]`.
103
+ *
104
+ * This is the load-bearing helper: it encapsulates the invariant that
105
+ * text lives on `TextLine` children, never on the parent `Text` block.
106
+ */
107
+ export function getTextLines(node) {
108
+ if (node.nodeType === 'TextLine')
109
+ return [node];
110
+ const lines = [];
111
+ walkElements(node.children, (n) => {
112
+ if (n.nodeType === 'TextLine') {
113
+ lines.push(n);
114
+ return false; // TextLines don't nest further; skip descent
115
+ }
116
+ });
117
+ return lines;
118
+ }
119
+ /**
120
+ * Concatenated text of every `TextLine` descendant of `node`, joined
121
+ * with `"\n"`. If `node` is itself a `TextLine`, returns its own text.
122
+ *
123
+ * Lines are joined with newlines rather than spaces because the layout
124
+ * engine may have wrapped a single JSX string across multiple lines,
125
+ * and preserving that structure is more useful than silently smushing
126
+ * or space-joining. If you want a flat string, `.replace(/\n/g, ' ')`
127
+ * the result.
128
+ *
129
+ * Returns `""` if no `TextLine` descendants exist.
130
+ */
131
+ export function getNodeText(node) {
132
+ const lines = getTextLines(node);
133
+ return lines
134
+ .map((l) => (typeof l.textContent === 'string' ? l.textContent : ''))
135
+ .join('\n');
136
+ }
137
+ // ── Structural queries encapsulating layout-time transforms ────────
138
+ /**
139
+ * If `node` is a heading (`H1`–`H6`), returns the numeric level (1–6).
140
+ * Returns `null` otherwise.
141
+ *
142
+ * Encapsulates the invariant that headings render as six discriminated
143
+ * nodeTypes (`H1`, `H2`, …) rather than a generic `Heading` node with a
144
+ * separate `level` field.
145
+ */
146
+ export function getHeadingLevel(node) {
147
+ const nt = node.nodeType;
148
+ if (nt === 'H1')
149
+ return 1;
150
+ if (nt === 'H2')
151
+ return 2;
152
+ if (nt === 'H3')
153
+ return 3;
154
+ if (nt === 'H4')
155
+ return 4;
156
+ if (nt === 'H5')
157
+ return 5;
158
+ if (nt === 'H6')
159
+ return 6;
160
+ return null;
161
+ }
162
+ /**
163
+ * Every `TableRow` that is a direct child of `parent`.
164
+ *
165
+ * Encapsulates the invariant that `<Table>` unwraps at layout time —
166
+ * its `<Row>` children become sibling `TableRow` nodes on the
167
+ * containing page/View, and there is no `Table` wrapper node to hang
168
+ * rows off of. Pass the containing `page` (or the parent `View` that
169
+ * held the `<Table>` in JSX) as `parent`.
170
+ *
171
+ * Returns rows in source order.
172
+ */
173
+ export function getTableRows(parent) {
174
+ const kids = 'elements' in parent ? parent.elements : parent.children;
175
+ return kids.filter((k) => k.nodeType === 'TableRow');
176
+ }
177
+ /**
178
+ * The `FixedHeader` and `FixedFooter` nodes on `page`. Encapsulates the
179
+ * invariant that `<Fixed position="header">` and `<Fixed position="footer">`
180
+ * produce two distinct nodeTypes rather than a shared `Fixed` node with
181
+ * a `position` field.
182
+ *
183
+ * Both arrays may be empty. Multiple entries in either array indicate
184
+ * repeating fixed regions (e.g. when the same `<Fixed>` repeats across
185
+ * page breaks — the layout may emit one node per occurrence).
186
+ */
187
+ export function getFixedRegions(page) {
188
+ const header = [];
189
+ const footer = [];
190
+ for (const el of page.elements) {
191
+ if (el.nodeType === 'FixedHeader')
192
+ header.push(el);
193
+ else if (el.nodeType === 'FixedFooter')
194
+ footer.push(el);
195
+ }
196
+ return { header, footer };
197
+ }
198
+ /**
199
+ * Every `ListItem` child of a `List` node. Returns `[]` if `list` is
200
+ * not a `List` (silently — no throw, so this composes cleanly with
201
+ * `.flatMap`).
202
+ */
203
+ export function getListItems(list) {
204
+ if (list.nodeType !== 'List')
205
+ return [];
206
+ return list.children.filter((c) => c.nodeType === 'ListItem');
207
+ }
208
+ /**
209
+ * Rendered text of the marker (`Lbl`) child of a `ListItem` — e.g.
210
+ * `"1."` for the first item of an `<OrderedList>`, `"•"` for an
211
+ * `<UnorderedList>` item. Returns `null` if `item` is not a `ListItem`
212
+ * or has no `Lbl` child.
213
+ *
214
+ * Encapsulates the invariant that list markers are separate `Lbl`
215
+ * children of each `ListItem` rather than a field on `ListItem` itself.
216
+ */
217
+ export function getListItemMarker(item) {
218
+ if (item.nodeType !== 'ListItem')
219
+ return null;
220
+ const lbl = item.children.find((c) => c.nodeType === 'Lbl');
221
+ if (!lbl)
222
+ return null;
223
+ return getNodeText(lbl);
224
+ }
225
+ // ── Node-type narrowing utility ────────────────────────────────────
226
+ /**
227
+ * Type-guard for narrowing to a specific `ElementNodeType`. Useful for
228
+ * `.filter(isNodeType('TableRow'))` chains.
229
+ */
230
+ export function isNodeType(nodeType) {
231
+ return (node) => node.nodeType === nodeType;
232
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@formepdf/core",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "WASM-powered PDF rendering engine for Forme",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -39,6 +39,10 @@
39
39
  "types": "./dist/worker.d.ts",
40
40
  "import": "./dist/worker.js"
41
41
  },
42
+ "./layout": {
43
+ "types": "./dist/layout.d.ts",
44
+ "import": "./dist/layout.js"
45
+ },
42
46
  "./pkg/forme.js": {
43
47
  "types": "./pkg/forme.d.ts",
44
48
  "import": "./pkg/forme.js"
@@ -55,17 +59,20 @@
55
59
  "build:ts": "tsc",
56
60
  "build": "npm run build:wasm && npm run build:ts",
57
61
  "test": "vitest run",
62
+ "test:templates": "vitest run --config vitest.config.templates.ts",
58
63
  "test:workers": "vitest run --config vitest.config.workers.ts",
59
64
  "prepublishOnly": "npm run build && ./scripts/assert-tarball.sh"
60
65
  },
61
66
  "dependencies": {
62
- "@formepdf/react": "0.12.0"
67
+ "@formepdf/react": "0.13.0"
63
68
  },
64
69
  "peerDependencies": {
65
70
  "react": "^18 || ^19"
66
71
  },
67
72
  "devDependencies": {
68
73
  "@cloudflare/vitest-pool-workers": "^0.12.21",
74
+ "@formepdf/templates": "0.13.0",
75
+ "@pdf-testkit/vitest": "^0.1.1",
69
76
  "@types/node": "^22.0.0",
70
77
  "@types/react": "^19.0.0",
71
78
  "react": "^19.0.0",
package/pkg/forme_bg.wasm CHANGED
Binary file
package/pkg/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "forme-pdf",
3
3
  "type": "module",
4
4
  "description": "A page-native PDF rendering engine. Layout INTO pages, not onto an infinite canvas.",
5
- "version": "0.12.0",
5
+ "version": "0.13.0",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -28,4 +28,4 @@
28
28
  "document",
29
29
  "report"
30
30
  ]
31
- }
31
+ }
Binary file
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "forme-pdf",
3
3
  "description": "A page-native PDF rendering engine. Layout INTO pages, not onto an infinite canvas.",
4
- "version": "0.12.0",
4
+ "version": "0.13.0",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -22,4 +22,4 @@
22
22
  "document",
23
23
  "report"
24
24
  ]
25
- }
25
+ }
Binary file
@@ -2,7 +2,7 @@
2
2
  "name": "forme-pdf",
3
3
  "type": "module",
4
4
  "description": "A page-native PDF rendering engine. Layout INTO pages, not onto an infinite canvas.",
5
- "version": "0.12.0",
5
+ "version": "0.13.0",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -26,4 +26,4 @@
26
26
  "document",
27
27
  "report"
28
28
  ]
29
- }
29
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Render one shipped template and write its raw `LayoutInfo` JSON to disk.
3
+ *
4
+ * Exists for CI's "Document Regression Demo" job, which needs the *current*
5
+ * run as a file on disk to hand to @pdf-testkit/action. The vitest matcher
6
+ * compares in memory and never writes one, so this is the missing producer —
7
+ * deliberately the same two calls the regression suite makes (`getTemplate` +
8
+ * `renderDocumentWithLayout`), so the demo can't drift from what that suite
9
+ * asserts.
10
+ *
11
+ * `pdf-testkit snapshot` converts the LayoutInfo emitted here into the same
12
+ * StructuralSnapshot shape as the committed baselines.
13
+ *
14
+ * Usage: node scripts/render-template-layout.mjs <template-name> <out.json>
15
+ */
16
+ import { writeFile } from 'node:fs/promises';
17
+ import { getTemplate } from '@formepdf/templates';
18
+ import * as schemas from '@formepdf/templates/schemas';
19
+ import { renderDocumentWithLayout } from '../dist/index.js';
20
+
21
+ const [name, out] = process.argv.slice(2);
22
+ if (!name || !out) {
23
+ console.error('usage: render-template-layout.mjs <template-name> <out.json>');
24
+ process.exit(2);
25
+ }
26
+
27
+ const template = getTemplate(name);
28
+ if (!template) {
29
+ console.error(`getTemplate(${JSON.stringify(name)}) returned null`);
30
+ process.exit(1);
31
+ }
32
+
33
+ // Same `*Example` fixtures the regression suite uses. They're validated against
34
+ // their Zod schemas at import time, so they can't drift from the schemas.
35
+ const exampleKey = `${name.replace(/-([a-z])/g, (_, c) => c.toUpperCase())}Example`;
36
+ const data = schemas[exampleKey];
37
+ if (!data) {
38
+ console.error(`No example fixture exported as "${exampleKey}" from @formepdf/templates/schemas`);
39
+ process.exit(1);
40
+ }
41
+
42
+ const { layout } = await renderDocumentWithLayout(template(data));
43
+ await writeFile(out, JSON.stringify(layout, null, 2) + '\n', 'utf8');
44
+ console.error(`wrote layout: ${out} (${layout.pages.length} page(s))`);