@imggion/html2realpdf 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.
- package/README.md +292 -0
- package/dist/LICENSE.md +465 -0
- package/dist/compat.d.ts +113 -0
- package/dist/compat.js +215 -0
- package/dist/compat.js.map +1 -0
- package/dist/errors.d.ts +55 -0
- package/dist/errors.js +73 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/libhtml2realpdf.wasm +0 -0
- package/dist/page.d.ts +23 -0
- package/dist/page.js +54 -0
- package/dist/page.js.map +1 -0
- package/dist/pdf-document.d.ts +51 -0
- package/dist/pdf-document.js +107 -0
- package/dist/pdf-document.js.map +1 -0
- package/dist/preview.d.ts +74 -0
- package/dist/preview.js +369 -0
- package/dist/preview.js.map +1 -0
- package/dist/renderer.d.ts +64 -0
- package/dist/renderer.js +276 -0
- package/dist/renderer.js.map +1 -0
- package/dist/snapshot.d.ts +79 -0
- package/dist/snapshot.js +2972 -0
- package/dist/snapshot.js.map +1 -0
- package/dist/types.d.ts +273 -0
- package/dist/types.js +7 -0
- package/dist/types.js.map +1 -0
- package/dist/vendor/pdf.min.mjs +28 -0
- package/dist/vendor/pdf.worker.min.mjs +28 -0
- package/dist/wasm.d.ts +39 -0
- package/dist/wasm.js +176 -0
- package/dist/wasm.js.map +1 -0
- package/dist/worker.d.ts +1 -0
- package/dist/worker.js +30 -0
- package/dist/worker.js.map +1 -0
- package/package.json +57 -0
- package/skills/html2realpdf/SKILL.md +260 -0
- package/skills/html2realpdf/agents/openai.yaml +4 -0
package/dist/snapshot.js
ADDED
|
@@ -0,0 +1,2972 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser snapshot boundary that converts live or inert HTML into deterministic,
|
|
3
|
+
* self-contained renderer input.
|
|
4
|
+
*
|
|
5
|
+
* @packageDocumentation
|
|
6
|
+
*/
|
|
7
|
+
import { CanvasToSvgError, InvalidSourceError, ResourceLoadError, UnsupportedCssError, UnsupportedEnvironmentError } from "./errors.js";
|
|
8
|
+
const SUPPORTED_COMPUTED_PROPERTIES = [
|
|
9
|
+
"display",
|
|
10
|
+
"position",
|
|
11
|
+
"top",
|
|
12
|
+
"right",
|
|
13
|
+
"bottom",
|
|
14
|
+
"left",
|
|
15
|
+
"z-index",
|
|
16
|
+
"opacity",
|
|
17
|
+
"transform",
|
|
18
|
+
"transform-origin",
|
|
19
|
+
"float",
|
|
20
|
+
"clear",
|
|
21
|
+
"flex-direction",
|
|
22
|
+
"flex-wrap",
|
|
23
|
+
"flex-grow",
|
|
24
|
+
"flex-shrink",
|
|
25
|
+
"flex-basis",
|
|
26
|
+
"order",
|
|
27
|
+
"row-gap",
|
|
28
|
+
"column-gap",
|
|
29
|
+
"justify-content",
|
|
30
|
+
"align-items",
|
|
31
|
+
"align-self",
|
|
32
|
+
"align-content",
|
|
33
|
+
"justify-items",
|
|
34
|
+
"justify-self",
|
|
35
|
+
"grid-template-columns",
|
|
36
|
+
"grid-template-rows",
|
|
37
|
+
"grid-template-areas",
|
|
38
|
+
"grid-auto-columns",
|
|
39
|
+
"grid-auto-rows",
|
|
40
|
+
"grid-auto-flow",
|
|
41
|
+
"grid-column-start",
|
|
42
|
+
"grid-column-end",
|
|
43
|
+
"grid-row-start",
|
|
44
|
+
"grid-row-end",
|
|
45
|
+
"width",
|
|
46
|
+
"height",
|
|
47
|
+
"min-width",
|
|
48
|
+
"max-width",
|
|
49
|
+
"min-height",
|
|
50
|
+
"max-height",
|
|
51
|
+
"aspect-ratio",
|
|
52
|
+
"object-fit",
|
|
53
|
+
"object-position",
|
|
54
|
+
"box-sizing",
|
|
55
|
+
"box-decoration-break",
|
|
56
|
+
"list-style-type",
|
|
57
|
+
"list-style-position",
|
|
58
|
+
"margin-top",
|
|
59
|
+
"margin-right",
|
|
60
|
+
"margin-bottom",
|
|
61
|
+
"margin-left",
|
|
62
|
+
"padding-top",
|
|
63
|
+
"padding-right",
|
|
64
|
+
"padding-bottom",
|
|
65
|
+
"padding-left",
|
|
66
|
+
"border-top-width",
|
|
67
|
+
"border-right-width",
|
|
68
|
+
"border-bottom-width",
|
|
69
|
+
"border-left-width",
|
|
70
|
+
"border-top-style",
|
|
71
|
+
"border-right-style",
|
|
72
|
+
"border-bottom-style",
|
|
73
|
+
"border-left-style",
|
|
74
|
+
"border-top-color",
|
|
75
|
+
"border-right-color",
|
|
76
|
+
"border-bottom-color",
|
|
77
|
+
"border-left-color",
|
|
78
|
+
"border-collapse",
|
|
79
|
+
"border-spacing",
|
|
80
|
+
"caption-side",
|
|
81
|
+
"border-top-left-radius",
|
|
82
|
+
"border-top-right-radius",
|
|
83
|
+
"border-bottom-right-radius",
|
|
84
|
+
"border-bottom-left-radius",
|
|
85
|
+
"background-color",
|
|
86
|
+
"background-image",
|
|
87
|
+
"background-position",
|
|
88
|
+
"background-size",
|
|
89
|
+
"background-repeat",
|
|
90
|
+
"box-shadow",
|
|
91
|
+
"color",
|
|
92
|
+
"direction",
|
|
93
|
+
"font-family",
|
|
94
|
+
"font-size",
|
|
95
|
+
"font-style",
|
|
96
|
+
"font-weight",
|
|
97
|
+
"line-height",
|
|
98
|
+
"letter-spacing",
|
|
99
|
+
"word-spacing",
|
|
100
|
+
"text-indent",
|
|
101
|
+
"text-align",
|
|
102
|
+
"text-transform",
|
|
103
|
+
"word-break",
|
|
104
|
+
"overflow-wrap",
|
|
105
|
+
"overflow",
|
|
106
|
+
"text-overflow",
|
|
107
|
+
"text-shadow",
|
|
108
|
+
"vertical-align",
|
|
109
|
+
"text-decoration-line",
|
|
110
|
+
"text-decoration-style",
|
|
111
|
+
"text-decoration-color",
|
|
112
|
+
"text-decoration-thickness",
|
|
113
|
+
"white-space",
|
|
114
|
+
"break-before",
|
|
115
|
+
"break-after",
|
|
116
|
+
"break-inside",
|
|
117
|
+
"page",
|
|
118
|
+
];
|
|
119
|
+
const SVG_COMPUTED_PROPERTIES = [
|
|
120
|
+
"clip-path",
|
|
121
|
+
"clip-rule",
|
|
122
|
+
"dominant-baseline",
|
|
123
|
+
"filter",
|
|
124
|
+
"fill",
|
|
125
|
+
"fill-opacity",
|
|
126
|
+
"fill-rule",
|
|
127
|
+
"marker-end",
|
|
128
|
+
"marker-mid",
|
|
129
|
+
"marker-start",
|
|
130
|
+
"mask-image",
|
|
131
|
+
"mix-blend-mode",
|
|
132
|
+
"paint-order",
|
|
133
|
+
"stroke",
|
|
134
|
+
"stroke-dasharray",
|
|
135
|
+
"stroke-dashoffset",
|
|
136
|
+
"stroke-linecap",
|
|
137
|
+
"stroke-linejoin",
|
|
138
|
+
"stroke-miterlimit",
|
|
139
|
+
"stroke-opacity",
|
|
140
|
+
"stroke-width",
|
|
141
|
+
"stop-color",
|
|
142
|
+
"stop-opacity",
|
|
143
|
+
"text-anchor",
|
|
144
|
+
"vector-effect",
|
|
145
|
+
"visibility",
|
|
146
|
+
];
|
|
147
|
+
/** Properties the native cascade inherits without requiring a child declaration. */
|
|
148
|
+
const INHERITED_SNAPSHOT_ELISION = new Set([
|
|
149
|
+
"color",
|
|
150
|
+
"font-family",
|
|
151
|
+
"font-size",
|
|
152
|
+
"font-style",
|
|
153
|
+
"font-weight",
|
|
154
|
+
"letter-spacing",
|
|
155
|
+
"text-transform",
|
|
156
|
+
"white-space",
|
|
157
|
+
"word-break",
|
|
158
|
+
"word-spacing",
|
|
159
|
+
"overflow-wrap",
|
|
160
|
+
"border-spacing",
|
|
161
|
+
]);
|
|
162
|
+
/** Browser initial values that map exactly to an unmodified native Style. */
|
|
163
|
+
const NATIVE_INITIAL_COMPUTED_VALUES = {
|
|
164
|
+
"align-content": ["normal", "stretch"],
|
|
165
|
+
"align-items": ["normal", "stretch"],
|
|
166
|
+
"align-self": ["auto"],
|
|
167
|
+
"aspect-ratio": ["auto"],
|
|
168
|
+
"background-image": ["none"],
|
|
169
|
+
"background-position": ["0% 0%"],
|
|
170
|
+
"background-repeat": ["repeat"],
|
|
171
|
+
"background-size": ["auto"],
|
|
172
|
+
"border-bottom-left-radius": ["0px"],
|
|
173
|
+
"border-bottom-right-radius": ["0px"],
|
|
174
|
+
"border-bottom-style": ["none"],
|
|
175
|
+
"border-bottom-width": ["0px"],
|
|
176
|
+
"border-collapse": ["separate"],
|
|
177
|
+
"border-spacing": ["0px"],
|
|
178
|
+
"border-left-style": ["none"],
|
|
179
|
+
"border-left-width": ["0px"],
|
|
180
|
+
"border-right-style": ["none"],
|
|
181
|
+
"border-right-width": ["0px"],
|
|
182
|
+
"border-top-left-radius": ["0px"],
|
|
183
|
+
"border-top-right-radius": ["0px"],
|
|
184
|
+
"border-top-style": ["none"],
|
|
185
|
+
"border-top-width": ["0px"],
|
|
186
|
+
"box-decoration-break": ["slice"],
|
|
187
|
+
"box-shadow": ["none"],
|
|
188
|
+
"box-sizing": ["content-box"],
|
|
189
|
+
"clear": ["none"],
|
|
190
|
+
"column-gap": ["normal"],
|
|
191
|
+
"flex-basis": ["auto"],
|
|
192
|
+
"flex-direction": ["row"],
|
|
193
|
+
"flex-grow": ["0"],
|
|
194
|
+
"flex-shrink": ["1"],
|
|
195
|
+
"flex-wrap": ["nowrap"],
|
|
196
|
+
"float": ["none"],
|
|
197
|
+
"grid-auto-columns": ["auto"],
|
|
198
|
+
"grid-auto-flow": ["row"],
|
|
199
|
+
"grid-auto-rows": ["auto"],
|
|
200
|
+
"grid-column-end": ["auto"],
|
|
201
|
+
"grid-column-start": ["auto"],
|
|
202
|
+
"grid-row-end": ["auto"],
|
|
203
|
+
"grid-row-start": ["auto"],
|
|
204
|
+
"grid-template-areas": ["none"],
|
|
205
|
+
"grid-template-columns": ["none"],
|
|
206
|
+
"grid-template-rows": ["none"],
|
|
207
|
+
"justify-content": ["normal"],
|
|
208
|
+
"justify-self": ["auto"],
|
|
209
|
+
"margin-bottom": ["0px"],
|
|
210
|
+
"margin-left": ["0px"],
|
|
211
|
+
"margin-right": ["0px"],
|
|
212
|
+
"margin-top": ["0px"],
|
|
213
|
+
"object-fit": ["fill"],
|
|
214
|
+
"object-position": ["50% 50%"],
|
|
215
|
+
"opacity": ["1"],
|
|
216
|
+
"order": ["0"],
|
|
217
|
+
"overflow": ["visible"],
|
|
218
|
+
"padding-bottom": ["0px"],
|
|
219
|
+
"padding-left": ["0px"],
|
|
220
|
+
"padding-right": ["0px"],
|
|
221
|
+
"padding-top": ["0px"],
|
|
222
|
+
"position": ["static"],
|
|
223
|
+
"row-gap": ["normal"],
|
|
224
|
+
"text-overflow": ["clip"],
|
|
225
|
+
"text-shadow": ["none"],
|
|
226
|
+
"transform": ["none"],
|
|
227
|
+
"vertical-align": ["baseline"],
|
|
228
|
+
"z-index": ["auto"],
|
|
229
|
+
};
|
|
230
|
+
// Pagination properties deliberately remain explicit, including `auto`.
|
|
231
|
+
// Browser-resolved pseudo selectors such as :last-child can override an
|
|
232
|
+
// authored forced break that the renderer's selector subset cannot replay.
|
|
233
|
+
const SVG_SERIALIZED_STYLE_PROPERTIES = new Set([
|
|
234
|
+
...SVG_COMPUTED_PROPERTIES,
|
|
235
|
+
"display", "opacity", "transform", "transform-origin", "color", "direction",
|
|
236
|
+
"font-family", "font-size", "font-style", "font-weight", "letter-spacing", "word-spacing",
|
|
237
|
+
]);
|
|
238
|
+
const SUPPORTED_DISPLAY = new Set([
|
|
239
|
+
"none",
|
|
240
|
+
"block",
|
|
241
|
+
"list-item",
|
|
242
|
+
"inline",
|
|
243
|
+
"inline-block",
|
|
244
|
+
"flex",
|
|
245
|
+
"inline-flex",
|
|
246
|
+
"grid",
|
|
247
|
+
"inline-grid",
|
|
248
|
+
"table",
|
|
249
|
+
"table-row-group",
|
|
250
|
+
"table-header-group",
|
|
251
|
+
"table-footer-group",
|
|
252
|
+
"table-row",
|
|
253
|
+
"table-cell",
|
|
254
|
+
"table-caption",
|
|
255
|
+
"table-column",
|
|
256
|
+
"table-column-group",
|
|
257
|
+
]);
|
|
258
|
+
const ACTIVE_ELEMENTS = "script,iframe,object,embed";
|
|
259
|
+
const AUTHORED_PAGE_MIRROR = "--html2realpdf-authored-page";
|
|
260
|
+
const AUTHORED_FLOW_DIMENSION_MIRRORS = {
|
|
261
|
+
width: "--html2realpdf-authored-width",
|
|
262
|
+
height: "--html2realpdf-authored-height",
|
|
263
|
+
"min-width": "--html2realpdf-authored-min-width",
|
|
264
|
+
"max-width": "--html2realpdf-authored-max-width",
|
|
265
|
+
"min-height": "--html2realpdf-authored-min-height",
|
|
266
|
+
"max-height": "--html2realpdf-authored-max-height",
|
|
267
|
+
};
|
|
268
|
+
const AUTHORED_AUTO_MARGIN_MIRRORS = {
|
|
269
|
+
"margin-top": "--html2realpdf-authored-margin-top",
|
|
270
|
+
"margin-right": "--html2realpdf-authored-margin-right",
|
|
271
|
+
"margin-bottom": "--html2realpdf-authored-margin-bottom",
|
|
272
|
+
"margin-left": "--html2realpdf-authored-margin-left",
|
|
273
|
+
};
|
|
274
|
+
const AUTHORED_FLOW_MIRRORS = {
|
|
275
|
+
...AUTHORED_FLOW_DIMENSION_MIRRORS,
|
|
276
|
+
...AUTHORED_AUTO_MARGIN_MIRRORS,
|
|
277
|
+
};
|
|
278
|
+
const VECTOR_SVG_ELEMENTS = new Set([
|
|
279
|
+
"svg", "g", "defs", "path", "rect", "circle", "ellipse", "line", "polyline", "polygon",
|
|
280
|
+
"text", "tspan", "linearGradient", "radialGradient", "stop", "clipPath", "title", "desc",
|
|
281
|
+
]);
|
|
282
|
+
const VECTOR_SVG_UNSUPPORTED_PROPERTIES = [
|
|
283
|
+
"filter",
|
|
284
|
+
"mix-blend-mode",
|
|
285
|
+
"mask",
|
|
286
|
+
"mask-image",
|
|
287
|
+
"marker-start",
|
|
288
|
+
"marker-mid",
|
|
289
|
+
"marker-end",
|
|
290
|
+
"vector-effect",
|
|
291
|
+
"paint-order",
|
|
292
|
+
];
|
|
293
|
+
const SUPPORTED_CSS_PROPERTIES = new Set([
|
|
294
|
+
...SUPPORTED_COMPUTED_PROPERTIES,
|
|
295
|
+
"margin", "padding", "border", "border-top", "border-right", "border-bottom", "border-left", "border-radius",
|
|
296
|
+
"border-width", "border-style", "border-color", "background", "font", "page-break-before", "page-break-after",
|
|
297
|
+
"page-break-inside", "list-style", "flex", "flex-flow", "gap", "inset", "inset-block", "inset-inline",
|
|
298
|
+
"inset-block-start", "inset-block-end", "inset-inline-start", "inset-inline-end", "orphans", "widows",
|
|
299
|
+
"grid", "grid-template", "grid-column", "grid-row", "grid-area",
|
|
300
|
+
"place-content", "place-items", "place-self",
|
|
301
|
+
]);
|
|
302
|
+
const NO_OP_SERIALIZED_FONT_LONGHANDS = {
|
|
303
|
+
"font-feature-settings": ["normal"],
|
|
304
|
+
"font-kerning": ["auto"],
|
|
305
|
+
"font-optical-sizing": ["auto"],
|
|
306
|
+
"font-size-adjust": ["none"],
|
|
307
|
+
"font-variant-alternates": ["normal"],
|
|
308
|
+
"font-variant-caps": ["normal"],
|
|
309
|
+
"font-variant-east-asian": ["normal"],
|
|
310
|
+
"font-variant-emoji": ["normal"],
|
|
311
|
+
"font-variant-ligatures": ["normal"],
|
|
312
|
+
"font-variant-numeric": ["normal"],
|
|
313
|
+
"font-variant-position": ["normal"],
|
|
314
|
+
"font-variation-settings": ["normal"],
|
|
315
|
+
"font-width": ["normal"],
|
|
316
|
+
};
|
|
317
|
+
/**
|
|
318
|
+
* Selects the inert-string or live-element snapshot path.
|
|
319
|
+
*
|
|
320
|
+
* @remarks
|
|
321
|
+
* A requested viewport or print media environment isolates even mounted
|
|
322
|
+
* elements so media queries can be evaluated without mutating the source page.
|
|
323
|
+
*/
|
|
324
|
+
export async function snapshotSource(source, options) {
|
|
325
|
+
if (typeof window === "undefined" || typeof Element === "undefined")
|
|
326
|
+
throw new UnsupportedEnvironmentError();
|
|
327
|
+
if (typeof source === "string")
|
|
328
|
+
return snapshotHtmlString(source, options);
|
|
329
|
+
const element = isRefLike(source) ? source.current : source;
|
|
330
|
+
if (!element)
|
|
331
|
+
throw new InvalidSourceError("The supplied ref is null; render after the element has mounted");
|
|
332
|
+
if (!(element instanceof Element))
|
|
333
|
+
throw new InvalidSourceError("Expected an HTML string, Element, or ref-like object");
|
|
334
|
+
if (options.viewport !== undefined || options.mediaType === "print")
|
|
335
|
+
return snapshotElementInEnvironment(element, options);
|
|
336
|
+
const { clone, diagnostics, page, pageMarginBoxes, pageRules } = await snapshotElement(element, options);
|
|
337
|
+
return { html: clone.outerHTML, diagnostics, ...(page ? { page } : {}), ...(pageMarginBoxes ? { pageMarginBoxes } : {}), ...(pageRules ? { pageRules } : {}) };
|
|
338
|
+
}
|
|
339
|
+
/** Clones an element and its selector context into an off-screen media environment. */
|
|
340
|
+
async function snapshotElementInEnvironment(element, options) {
|
|
341
|
+
const viewport = options.viewport ?? { width: window.innerWidth || 1280, height: window.innerHeight || 720 };
|
|
342
|
+
const iframe = createSnapshotFrame(viewport);
|
|
343
|
+
const csp = "default-src 'none'; script-src 'none'; style-src 'unsafe-inline'; img-src data: blob:; font-src data: blob:";
|
|
344
|
+
iframe.srcdoc = `<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="${csp}"></head><body></body></html>`;
|
|
345
|
+
document.body.append(iframe);
|
|
346
|
+
try {
|
|
347
|
+
await waitForSnapshotFrame(iframe);
|
|
348
|
+
const targetDocument = iframe.contentDocument;
|
|
349
|
+
if (!targetDocument)
|
|
350
|
+
throw new InvalidSourceError("The isolated element snapshot document is unavailable");
|
|
351
|
+
copySafeAttributes(element.ownerDocument.documentElement, targetDocument.documentElement);
|
|
352
|
+
if (element.ownerDocument.body)
|
|
353
|
+
copySafeAttributes(element.ownerDocument.body, targetDocument.body);
|
|
354
|
+
const base = targetDocument.createElement("base");
|
|
355
|
+
base.href = options.baseUrl?.toString() ?? element.ownerDocument.baseURI;
|
|
356
|
+
targetDocument.head.append(base);
|
|
357
|
+
const stylesheet = targetDocument.createElement("style");
|
|
358
|
+
stylesheet.textContent = serializeAccessibleStylesheets(element.ownerDocument);
|
|
359
|
+
targetDocument.head.append(stylesheet);
|
|
360
|
+
const canvasOrigins = new WeakMap();
|
|
361
|
+
const target = cloneEnvironmentNode(element, targetDocument, canvasOrigins);
|
|
362
|
+
let mounted = target;
|
|
363
|
+
for (let ancestor = element.parentElement; ancestor && ancestor.localName !== "body" && ancestor.localName !== "html"; ancestor = ancestor.parentElement) {
|
|
364
|
+
const wrapper = targetDocument.importNode(ancestor.cloneNode(false), false);
|
|
365
|
+
removeEventHandlers(wrapper);
|
|
366
|
+
wrapper.append(mounted);
|
|
367
|
+
mounted = wrapper;
|
|
368
|
+
}
|
|
369
|
+
targetDocument.body.append(mounted);
|
|
370
|
+
freezeDynamicStyles(targetDocument);
|
|
371
|
+
await waitForStyleResolution(targetDocument.defaultView);
|
|
372
|
+
forceRequestedMedia(targetDocument, options.mediaType ?? "screen", viewport);
|
|
373
|
+
forceShadowMediaRules(target, options.mediaType ?? "screen", viewport);
|
|
374
|
+
const snapshot = await snapshotElement(target, options, canvasOrigins);
|
|
375
|
+
return {
|
|
376
|
+
html: snapshot.clone.outerHTML,
|
|
377
|
+
diagnostics: snapshot.diagnostics,
|
|
378
|
+
...(snapshot.page ? { page: snapshot.page } : {}),
|
|
379
|
+
...(snapshot.pageMarginBoxes ? { pageMarginBoxes: snapshot.pageMarginBoxes } : {}),
|
|
380
|
+
...(snapshot.pageRules ? { pageRules: snapshot.pageRules } : {}),
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
finally {
|
|
384
|
+
iframe.remove();
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
function createSnapshotFrame(viewport) {
|
|
388
|
+
const iframe = document.createElement("iframe");
|
|
389
|
+
const viewportWidth = Math.max(viewport.width, 1);
|
|
390
|
+
const viewportHeight = Math.max(viewport.height, 1);
|
|
391
|
+
iframe.width = String(viewportWidth);
|
|
392
|
+
iframe.height = String(viewportHeight);
|
|
393
|
+
iframe.style.cssText = `position:fixed;left:-100000px;top:0;width:${viewportWidth}px;height:${viewportHeight}px;min-width:${viewportWidth}px;max-width:${viewportWidth}px;min-height:${viewportHeight}px;max-height:${viewportHeight}px;border:0;visibility:hidden`;
|
|
394
|
+
return iframe;
|
|
395
|
+
}
|
|
396
|
+
function waitForSnapshotFrame(iframe) {
|
|
397
|
+
return new Promise((resolve, reject) => {
|
|
398
|
+
iframe.addEventListener("load", () => resolve(), { once: true });
|
|
399
|
+
iframe.addEventListener("error", () => reject(new InvalidSourceError("Could not create the inert HTML snapshot document")), { once: true });
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
function waitForStyleResolution(view) {
|
|
403
|
+
if (!view)
|
|
404
|
+
return Promise.resolve();
|
|
405
|
+
return new Promise((resolve) => {
|
|
406
|
+
let settled = false;
|
|
407
|
+
const finish = () => {
|
|
408
|
+
if (settled)
|
|
409
|
+
return;
|
|
410
|
+
settled = true;
|
|
411
|
+
resolve();
|
|
412
|
+
};
|
|
413
|
+
view.requestAnimationFrame(finish);
|
|
414
|
+
window.setTimeout(finish, 50);
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
const CSS_PAGE_RULE = 6;
|
|
418
|
+
const CSS_STYLE_RULE = 1;
|
|
419
|
+
const CSS_MEDIA_RULE = 4;
|
|
420
|
+
const CSS_SUPPORTS_RULE = 12;
|
|
421
|
+
const DEFAULT_PAGE_SIZE_POINTS = [595.2756, 841.8898];
|
|
422
|
+
const CSS_PAGE_SIZES_POINTS = {
|
|
423
|
+
a3: [841.8898, 1190.5512],
|
|
424
|
+
a4: DEFAULT_PAGE_SIZE_POINTS,
|
|
425
|
+
a5: [419.5276, 595.2756],
|
|
426
|
+
letter: [612, 792],
|
|
427
|
+
legal: [612, 1008],
|
|
428
|
+
ledger: [1224, 792],
|
|
429
|
+
tabloid: [792, 1224],
|
|
430
|
+
};
|
|
431
|
+
const PAGE_MARGIN_BOX_NAMES = new Map([
|
|
432
|
+
["top-left-corner", "top_left_corner"], ["top-left", "top_left"], ["top-center", "top_center"],
|
|
433
|
+
["top-right", "top_right"], ["top-right-corner", "top_right_corner"], ["right-top", "right_top"],
|
|
434
|
+
["right-middle", "right_middle"], ["right-bottom", "right_bottom"],
|
|
435
|
+
["bottom-right-corner", "bottom_right_corner"], ["bottom-right", "bottom_right"],
|
|
436
|
+
["bottom-center", "bottom_center"], ["bottom-left", "bottom_left"],
|
|
437
|
+
["bottom-left-corner", "bottom_left_corner"], ["left-bottom", "left_bottom"],
|
|
438
|
+
["left-middle", "left_middle"], ["left-top", "left_top"],
|
|
439
|
+
]);
|
|
440
|
+
/**
|
|
441
|
+
* Resolves default, named, and pseudo `@page` rules while retaining CSS
|
|
442
|
+
* importance for the native page-selector cascade.
|
|
443
|
+
*/
|
|
444
|
+
function readDefaultPageStyle(document, options, diagnostics) {
|
|
445
|
+
const cascade = {};
|
|
446
|
+
const marginCascades = new Map();
|
|
447
|
+
const rawRules = [];
|
|
448
|
+
let found = false;
|
|
449
|
+
const view = document.defaultView ?? window;
|
|
450
|
+
const stylesheets = [...document.styleSheets, ...(document.adoptedStyleSheets ?? [])];
|
|
451
|
+
for (const stylesheet of stylesheets) {
|
|
452
|
+
try {
|
|
453
|
+
found = collectDefaultPageRules(stylesheet.cssRules, view, document, cascade, marginCascades, rawRules, options, diagnostics) || found;
|
|
454
|
+
}
|
|
455
|
+
catch (error) {
|
|
456
|
+
if (error instanceof UnsupportedCssError)
|
|
457
|
+
throw error;
|
|
458
|
+
// Cross-origin stylesheets cannot expose cssRules. Their normal computed
|
|
459
|
+
// declarations remain usable, but paged-media metadata is unavailable.
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
for (const style of document.querySelectorAll("style")) {
|
|
463
|
+
collectAuthoredDiscardedPageRules(style.textContent ?? "", document, view, rawRules, options, diagnostics);
|
|
464
|
+
if (marginCascades.size === 0) {
|
|
465
|
+
collectAuthoredPageMarginRules(style.textContent ?? "", document, view, marginCascades, options, diagnostics);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
const marginBoxes = materializePageMarginBoxes(marginCascades, options, diagnostics);
|
|
469
|
+
const rules = materializePageRules(rawRules, cascade, options, diagnostics);
|
|
470
|
+
if (!found)
|
|
471
|
+
return { marginBoxes, rules };
|
|
472
|
+
const size = parseCssPageSize(cascade.size?.value ?? "auto");
|
|
473
|
+
if (!size) {
|
|
474
|
+
reportUnsupportedPageValue("size", cascade.size?.value ?? "", options, diagnostics);
|
|
475
|
+
return { marginBoxes, rules };
|
|
476
|
+
}
|
|
477
|
+
const margins = ["margin-top", "margin-right", "margin-bottom", "margin-left"].map((property) => {
|
|
478
|
+
const raw = cascade[property]?.value ?? "0";
|
|
479
|
+
const value = parseCssPageLength(raw, true);
|
|
480
|
+
if (value === null)
|
|
481
|
+
reportUnsupportedPageValue(property, raw, options, diagnostics);
|
|
482
|
+
return value ?? 0;
|
|
483
|
+
});
|
|
484
|
+
if (margins[0] + margins[2] >= size[1] || margins[1] + margins[3] >= size[0]) {
|
|
485
|
+
reportUnsupportedPageValue("margin", "page margins leave no content area", options, diagnostics);
|
|
486
|
+
return { marginBoxes, rules };
|
|
487
|
+
}
|
|
488
|
+
return {
|
|
489
|
+
page: {
|
|
490
|
+
widthPoints: size[0],
|
|
491
|
+
heightPoints: size[1],
|
|
492
|
+
marginTopPoints: margins[0],
|
|
493
|
+
marginRightPoints: margins[1],
|
|
494
|
+
marginBottomPoints: margins[2],
|
|
495
|
+
marginLeftPoints: margins[3],
|
|
496
|
+
},
|
|
497
|
+
marginBoxes,
|
|
498
|
+
rules,
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
function collectDefaultPageRules(rules, view, document, cascade, marginCascades, rawRules, options, diagnostics) {
|
|
502
|
+
let found = false;
|
|
503
|
+
for (const rule of [...rules]) {
|
|
504
|
+
if (rule.type === CSS_PAGE_RULE && "style" in rule) {
|
|
505
|
+
const pageRule = rule;
|
|
506
|
+
const selector = pageRule.selectorText.trim();
|
|
507
|
+
if (selector) {
|
|
508
|
+
const parsedSelector = parsePageSelector(selector);
|
|
509
|
+
if (!parsedSelector) {
|
|
510
|
+
reportUnsupportedPageValue("@page selector", selector, options, diagnostics);
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
const ruleCascade = {};
|
|
514
|
+
const ruleMarginCascades = new Map();
|
|
515
|
+
const pageStyle = pageRule.style;
|
|
516
|
+
cascadePageDeclaration(ruleCascade, pageStyle, "size");
|
|
517
|
+
cascadePageDeclaration(ruleCascade, pageStyle, "margin-top");
|
|
518
|
+
cascadePageDeclaration(ruleCascade, pageStyle, "margin-right");
|
|
519
|
+
cascadePageDeclaration(ruleCascade, pageStyle, "margin-bottom");
|
|
520
|
+
cascadePageDeclaration(ruleCascade, pageStyle, "margin-left");
|
|
521
|
+
collectPageMarginRules(pageRule.cssText, document, ruleMarginCascades, options, diagnostics);
|
|
522
|
+
rawRules.push({ selector: parsedSelector, cascade: ruleCascade, marginCascades: ruleMarginCascades });
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
525
|
+
found = true;
|
|
526
|
+
const pageStyle = pageRule.style;
|
|
527
|
+
cascadePageDeclaration(cascade, pageStyle, "size");
|
|
528
|
+
cascadePageDeclaration(cascade, pageStyle, "margin-top");
|
|
529
|
+
cascadePageDeclaration(cascade, pageStyle, "margin-right");
|
|
530
|
+
cascadePageDeclaration(cascade, pageStyle, "margin-bottom");
|
|
531
|
+
cascadePageDeclaration(cascade, pageStyle, "margin-left");
|
|
532
|
+
collectPageMarginRules(pageRule.cssText, document, marginCascades, options, diagnostics);
|
|
533
|
+
continue;
|
|
534
|
+
}
|
|
535
|
+
if (!("cssRules" in rule) || !rule.cssRules)
|
|
536
|
+
continue;
|
|
537
|
+
if (rule.type === CSS_MEDIA_RULE && "conditionText" in rule && !view.matchMedia(String(rule.conditionText)).matches)
|
|
538
|
+
continue;
|
|
539
|
+
if (rule.type === CSS_SUPPORTS_RULE && "conditionText" in rule && !CSS.supports(String(rule.conditionText)))
|
|
540
|
+
continue;
|
|
541
|
+
found = collectDefaultPageRules(rule.cssRules, view, document, cascade, marginCascades, rawRules, options, diagnostics) || found;
|
|
542
|
+
}
|
|
543
|
+
return found;
|
|
544
|
+
}
|
|
545
|
+
function parsePageSelector(value) {
|
|
546
|
+
const selector = value.trim();
|
|
547
|
+
if (!selector || selector.includes(",") || /\s/.test(selector))
|
|
548
|
+
return null;
|
|
549
|
+
const firstColon = selector.indexOf(":");
|
|
550
|
+
const rawName = firstColon < 0 ? selector : selector.slice(0, firstColon);
|
|
551
|
+
if (rawName && (!/^[-_A-Za-z\u0080-\uFFFF][-_A-Za-z0-9\u0080-\uFFFF]*$/.test(rawName) || /^(?:auto|initial|inherit|unset|revert|revert-layer|default)$/i.test(rawName)))
|
|
552
|
+
return null;
|
|
553
|
+
const result = {};
|
|
554
|
+
if (rawName)
|
|
555
|
+
result.name = rawName;
|
|
556
|
+
const pseudos = firstColon < 0 ? "" : selector.slice(firstColon);
|
|
557
|
+
if (!pseudos && !rawName)
|
|
558
|
+
return null;
|
|
559
|
+
let cursor = 0;
|
|
560
|
+
while (cursor < pseudos.length) {
|
|
561
|
+
const match = pseudos.slice(cursor).match(/^:([A-Za-z-]+)/);
|
|
562
|
+
if (!match)
|
|
563
|
+
return null;
|
|
564
|
+
const pseudo = match[1].toLowerCase();
|
|
565
|
+
if (pseudo === "first") {
|
|
566
|
+
if (result.first)
|
|
567
|
+
return null;
|
|
568
|
+
result.first = true;
|
|
569
|
+
}
|
|
570
|
+
else if (pseudo === "left") {
|
|
571
|
+
if (result.left || result.right)
|
|
572
|
+
return null;
|
|
573
|
+
result.left = true;
|
|
574
|
+
}
|
|
575
|
+
else if (pseudo === "right") {
|
|
576
|
+
if (result.right || result.left)
|
|
577
|
+
return null;
|
|
578
|
+
result.right = true;
|
|
579
|
+
}
|
|
580
|
+
else if (pseudo === "blank") {
|
|
581
|
+
if (result.blank)
|
|
582
|
+
return null;
|
|
583
|
+
result.blank = true;
|
|
584
|
+
}
|
|
585
|
+
else
|
|
586
|
+
return null;
|
|
587
|
+
cursor += match[0].length;
|
|
588
|
+
}
|
|
589
|
+
return result;
|
|
590
|
+
}
|
|
591
|
+
function materializePageRules(rawRules, defaultCascade, options, diagnostics) {
|
|
592
|
+
const result = [];
|
|
593
|
+
for (const raw of rawRules) {
|
|
594
|
+
const rule = { ...raw.selector };
|
|
595
|
+
const size = raw.cascade.size;
|
|
596
|
+
if (size && beatsDefaultPageDeclaration(size, defaultCascade.size)) {
|
|
597
|
+
const parsed = parseCssPageSize(size.value);
|
|
598
|
+
if (!parsed) {
|
|
599
|
+
reportUnsupportedPageValue("size", size.value, options, diagnostics);
|
|
600
|
+
}
|
|
601
|
+
else {
|
|
602
|
+
rule.widthPoints = parsed[0];
|
|
603
|
+
rule.heightPoints = parsed[1];
|
|
604
|
+
if (size.important)
|
|
605
|
+
rule.sizeImportant = true;
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
for (const [property, output, importantOutput] of [
|
|
609
|
+
["margin-top", "marginTopPoints", "marginTopImportant"],
|
|
610
|
+
["margin-right", "marginRightPoints", "marginRightImportant"],
|
|
611
|
+
["margin-bottom", "marginBottomPoints", "marginBottomImportant"],
|
|
612
|
+
["margin-left", "marginLeftPoints", "marginLeftImportant"],
|
|
613
|
+
]) {
|
|
614
|
+
const declaration = raw.cascade[property];
|
|
615
|
+
if (!declaration || !beatsDefaultPageDeclaration(declaration, defaultCascade[property]))
|
|
616
|
+
continue;
|
|
617
|
+
const parsed = parseCssPageLength(declaration.value, true);
|
|
618
|
+
if (parsed === null) {
|
|
619
|
+
reportUnsupportedPageValue(property, declaration.value, options, diagnostics);
|
|
620
|
+
continue;
|
|
621
|
+
}
|
|
622
|
+
rule[output] = parsed;
|
|
623
|
+
if (declaration.important)
|
|
624
|
+
rule[importantOutput] = true;
|
|
625
|
+
}
|
|
626
|
+
const marginBoxes = materializePageMarginBoxes(raw.marginCascades, options, diagnostics);
|
|
627
|
+
if (marginBoxes.length > 0)
|
|
628
|
+
rule.marginBoxes = marginBoxes;
|
|
629
|
+
result.push(rule);
|
|
630
|
+
}
|
|
631
|
+
return result;
|
|
632
|
+
}
|
|
633
|
+
function beatsDefaultPageDeclaration(candidate, defaultValue) {
|
|
634
|
+
return !defaultValue?.important || candidate.important;
|
|
635
|
+
}
|
|
636
|
+
function cascadePageDeclaration(cascade, style, property) {
|
|
637
|
+
const value = style.getPropertyValue(property).trim();
|
|
638
|
+
if (!value)
|
|
639
|
+
return;
|
|
640
|
+
const important = style.getPropertyPriority(property) === "important";
|
|
641
|
+
const previous = cascade[property];
|
|
642
|
+
if (previous?.important && !important)
|
|
643
|
+
return;
|
|
644
|
+
cascade[property] = { value, important };
|
|
645
|
+
}
|
|
646
|
+
function collectPageMarginRules(cssText, document, cascades, options, diagnostics) {
|
|
647
|
+
const outerOpen = cssText.indexOf("{");
|
|
648
|
+
if (outerOpen < 0)
|
|
649
|
+
return;
|
|
650
|
+
const outerClose = matchingCssBrace(cssText, outerOpen);
|
|
651
|
+
if (outerClose < 0)
|
|
652
|
+
return;
|
|
653
|
+
const body = cssText.slice(outerOpen + 1, outerClose);
|
|
654
|
+
let cursor = 0;
|
|
655
|
+
while (cursor < body.length) {
|
|
656
|
+
const at = nextCssAtRule(body, cursor);
|
|
657
|
+
if (at < 0)
|
|
658
|
+
break;
|
|
659
|
+
const match = body.slice(at + 1).match(/^([\w-]+)/);
|
|
660
|
+
if (!match) {
|
|
661
|
+
cursor = at + 1;
|
|
662
|
+
continue;
|
|
663
|
+
}
|
|
664
|
+
const rawName = match[1].toLowerCase();
|
|
665
|
+
let open = at + 1 + match[0].length;
|
|
666
|
+
while (/\s/.test(body[open] ?? ""))
|
|
667
|
+
open += 1;
|
|
668
|
+
if (body[open] !== "{") {
|
|
669
|
+
cursor = open + 1;
|
|
670
|
+
continue;
|
|
671
|
+
}
|
|
672
|
+
const close = matchingCssBrace(body, open);
|
|
673
|
+
if (close < 0)
|
|
674
|
+
break;
|
|
675
|
+
const name = PAGE_MARGIN_BOX_NAMES.get(rawName);
|
|
676
|
+
if (!name) {
|
|
677
|
+
reportUnsupportedPageValue("@page margin box", `@${rawName}`, options, diagnostics);
|
|
678
|
+
cursor = close + 1;
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
const style = document.createElement("div").style;
|
|
682
|
+
style.cssText = body.slice(open + 1, close);
|
|
683
|
+
const cascade = cascades.get(name) ?? {};
|
|
684
|
+
for (const property of ["content", "font-family", "font-size", "font-weight", "font-style", "color", "text-align"]) {
|
|
685
|
+
cascadeMarginDeclaration(cascade, style, property);
|
|
686
|
+
}
|
|
687
|
+
cascades.set(name, cascade);
|
|
688
|
+
cursor = close + 1;
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
function collectAuthoredPageMarginRules(cssText, document, view, cascades, options, diagnostics) {
|
|
692
|
+
let cursor = 0;
|
|
693
|
+
while (cursor < cssText.length) {
|
|
694
|
+
const at = nextCssAtRule(cssText, cursor);
|
|
695
|
+
if (at < 0)
|
|
696
|
+
break;
|
|
697
|
+
const nameMatch = cssText.slice(at + 1).match(/^([\w-]+)/);
|
|
698
|
+
if (!nameMatch) {
|
|
699
|
+
cursor = at + 1;
|
|
700
|
+
continue;
|
|
701
|
+
}
|
|
702
|
+
let open = at + 1 + nameMatch[0].length;
|
|
703
|
+
while (open < cssText.length && cssText[open] !== "{" && cssText[open] !== ";")
|
|
704
|
+
open += 1;
|
|
705
|
+
if (cssText[open] !== "{") {
|
|
706
|
+
cursor = open + 1;
|
|
707
|
+
continue;
|
|
708
|
+
}
|
|
709
|
+
const close = matchingCssBrace(cssText, open);
|
|
710
|
+
if (close < 0)
|
|
711
|
+
break;
|
|
712
|
+
const atRuleName = nameMatch[1].toLowerCase();
|
|
713
|
+
const prelude = cssText.slice(at + 1 + nameMatch[0].length, open).trim();
|
|
714
|
+
const nested = cssText.slice(open + 1, close);
|
|
715
|
+
if (atRuleName === "page") {
|
|
716
|
+
if (!prelude) {
|
|
717
|
+
collectPageMarginRules(`@page {${nested}}`, document, cascades, options, diagnostics);
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
else if (atRuleName === "media") {
|
|
721
|
+
const viewport = options.viewport ?? { width: 1280, height: 720 };
|
|
722
|
+
if (matchesRequestedMedia(prelude, options.mediaType ?? "screen", viewport, view)) {
|
|
723
|
+
collectAuthoredPageMarginRules(nested, document, view, cascades, options, diagnostics);
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
else if (atRuleName === "supports") {
|
|
727
|
+
if (CSS.supports(prelude))
|
|
728
|
+
collectAuthoredPageMarginRules(nested, document, view, cascades, options, diagnostics);
|
|
729
|
+
}
|
|
730
|
+
else if (atRuleName === "layer") {
|
|
731
|
+
collectAuthoredPageMarginRules(nested, document, view, cascades, options, diagnostics);
|
|
732
|
+
}
|
|
733
|
+
// Unknown grouping conditions stay opaque: applying a raw @page from an
|
|
734
|
+
// inactive container/scope would be worse than omission.
|
|
735
|
+
cursor = close + 1;
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
/// Some engines discard selectors they do not implement (notably `:blank`)
|
|
739
|
+
/// from CSSOM entirely. Recover only those discarded rules from same-document
|
|
740
|
+
/// authored styles; selectors exposed by CSSOM keep their canonical ordering
|
|
741
|
+
/// and are not duplicated here.
|
|
742
|
+
function collectAuthoredDiscardedPageRules(cssText, document, view, rawRules, options, diagnostics) {
|
|
743
|
+
let cursor = 0;
|
|
744
|
+
while (cursor < cssText.length) {
|
|
745
|
+
const at = nextCssAtRule(cssText, cursor);
|
|
746
|
+
if (at < 0)
|
|
747
|
+
break;
|
|
748
|
+
const nameMatch = cssText.slice(at + 1).match(/^([\w-]+)/);
|
|
749
|
+
if (!nameMatch) {
|
|
750
|
+
cursor = at + 1;
|
|
751
|
+
continue;
|
|
752
|
+
}
|
|
753
|
+
let open = at + 1 + nameMatch[0].length;
|
|
754
|
+
while (open < cssText.length && cssText[open] !== "{" && cssText[open] !== ";")
|
|
755
|
+
open += 1;
|
|
756
|
+
if (cssText[open] !== "{") {
|
|
757
|
+
cursor = open + 1;
|
|
758
|
+
continue;
|
|
759
|
+
}
|
|
760
|
+
const close = matchingCssBrace(cssText, open);
|
|
761
|
+
if (close < 0)
|
|
762
|
+
break;
|
|
763
|
+
const atRuleName = nameMatch[1].toLowerCase();
|
|
764
|
+
const prelude = cssText.slice(at + 1 + nameMatch[0].length, open).trim();
|
|
765
|
+
const nested = cssText.slice(open + 1, close);
|
|
766
|
+
if (atRuleName === "page" && prelude) {
|
|
767
|
+
const marginCascades = new Map();
|
|
768
|
+
collectPageMarginRules(`@page {${nested}}`, document, marginCascades, options, diagnostics);
|
|
769
|
+
const recoversDiscardedGeometry = /:blank\b/i.test(prelude);
|
|
770
|
+
if (recoversDiscardedGeometry || marginCascades.size > 0) {
|
|
771
|
+
const selector = parsePageSelector(prelude);
|
|
772
|
+
if (!selector) {
|
|
773
|
+
reportUnsupportedPageValue("@page selector", prelude, options, diagnostics);
|
|
774
|
+
}
|
|
775
|
+
else {
|
|
776
|
+
const cascade = recoversDiscardedGeometry ? parseAuthoredPageCascade(document, nested) : {};
|
|
777
|
+
rawRules.push({ selector, cascade, marginCascades });
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
else if (atRuleName === "media") {
|
|
782
|
+
const viewport = options.viewport ?? { width: 1280, height: 720 };
|
|
783
|
+
if (matchesRequestedMedia(prelude, options.mediaType ?? "screen", viewport, view)) {
|
|
784
|
+
collectAuthoredDiscardedPageRules(nested, document, view, rawRules, options, diagnostics);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
else if (atRuleName === "supports") {
|
|
788
|
+
if (CSS.supports(prelude))
|
|
789
|
+
collectAuthoredDiscardedPageRules(nested, document, view, rawRules, options, diagnostics);
|
|
790
|
+
}
|
|
791
|
+
else if (atRuleName === "layer") {
|
|
792
|
+
collectAuthoredDiscardedPageRules(nested, document, view, rawRules, options, diagnostics);
|
|
793
|
+
}
|
|
794
|
+
cursor = close + 1;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
function parseAuthoredPageCascade(document, body) {
|
|
798
|
+
const styleElement = document.createElement("style");
|
|
799
|
+
styleElement.textContent = `@page {${body}}`;
|
|
800
|
+
(document.head ?? document.documentElement).append(styleElement);
|
|
801
|
+
try {
|
|
802
|
+
const rule = [...(styleElement.sheet?.cssRules ?? [])].find((candidate) => candidate.type === CSS_PAGE_RULE && "style" in candidate);
|
|
803
|
+
const cascade = {};
|
|
804
|
+
if (!rule)
|
|
805
|
+
return cascade;
|
|
806
|
+
const style = rule.style;
|
|
807
|
+
cascadePageDeclaration(cascade, style, "size");
|
|
808
|
+
cascadePageDeclaration(cascade, style, "margin-top");
|
|
809
|
+
cascadePageDeclaration(cascade, style, "margin-right");
|
|
810
|
+
cascadePageDeclaration(cascade, style, "margin-bottom");
|
|
811
|
+
cascadePageDeclaration(cascade, style, "margin-left");
|
|
812
|
+
return cascade;
|
|
813
|
+
}
|
|
814
|
+
finally {
|
|
815
|
+
styleElement.remove();
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
function cascadeMarginDeclaration(cascade, style, property) {
|
|
819
|
+
const value = style.getPropertyValue(property).trim();
|
|
820
|
+
if (!value)
|
|
821
|
+
return;
|
|
822
|
+
const important = style.getPropertyPriority(property) === "important";
|
|
823
|
+
const previous = cascade[property];
|
|
824
|
+
if (previous?.important && !important)
|
|
825
|
+
return;
|
|
826
|
+
cascade[property] = { value, important };
|
|
827
|
+
}
|
|
828
|
+
function materializePageMarginBoxes(cascades, options, diagnostics) {
|
|
829
|
+
const result = [];
|
|
830
|
+
for (const [name, cascade] of cascades) {
|
|
831
|
+
const rawContent = cascade.content?.value ?? "normal";
|
|
832
|
+
const content = parsePageMarginContent(rawContent);
|
|
833
|
+
if (content === null) {
|
|
834
|
+
reportUnsupportedPageValue(`@${name.replaceAll("_", "-")} content`, rawContent, options, diagnostics);
|
|
835
|
+
continue;
|
|
836
|
+
}
|
|
837
|
+
if (!content)
|
|
838
|
+
continue;
|
|
839
|
+
const rawSize = cascade["font-size"]?.value ?? "12px";
|
|
840
|
+
const fontSizePoints = parseCssPageLength(rawSize, false);
|
|
841
|
+
if (fontSizePoints === null) {
|
|
842
|
+
reportUnsupportedPageValue(`@${name.replaceAll("_", "-")} font-size`, rawSize, options, diagnostics);
|
|
843
|
+
continue;
|
|
844
|
+
}
|
|
845
|
+
const rawWeight = (cascade["font-weight"]?.value ?? "normal").toLowerCase();
|
|
846
|
+
const numericWeight = Number.parseInt(rawWeight, 10);
|
|
847
|
+
const fontWeight = rawWeight === "bold" || rawWeight === "bolder" || (Number.isFinite(numericWeight) && numericWeight >= 600)
|
|
848
|
+
? "bold"
|
|
849
|
+
: "normal";
|
|
850
|
+
const rawStyle = (cascade["font-style"]?.value ?? "normal").toLowerCase();
|
|
851
|
+
const fontStyle = rawStyle === "italic" || rawStyle.startsWith("oblique") ? "italic" : "normal";
|
|
852
|
+
const rawAlign = (cascade["text-align"]?.value ?? "").toLowerCase();
|
|
853
|
+
const textAlign = ["start", "end", "left", "center", "right", "justify"].includes(rawAlign)
|
|
854
|
+
? rawAlign
|
|
855
|
+
: undefined;
|
|
856
|
+
result.push({
|
|
857
|
+
name,
|
|
858
|
+
content,
|
|
859
|
+
fontFamily: cascade["font-family"]?.value ?? "Noto Sans",
|
|
860
|
+
fontSize: fontSizePoints / 0.75,
|
|
861
|
+
fontWeight,
|
|
862
|
+
fontStyle,
|
|
863
|
+
color: cascade.color?.value ?? "black",
|
|
864
|
+
...(textAlign ? { textAlign } : {}),
|
|
865
|
+
});
|
|
866
|
+
}
|
|
867
|
+
return result;
|
|
868
|
+
}
|
|
869
|
+
function parsePageMarginContent(raw) {
|
|
870
|
+
const input = raw.trim();
|
|
871
|
+
if (!input || input === "normal" || input === "none")
|
|
872
|
+
return "";
|
|
873
|
+
let output = "";
|
|
874
|
+
let cursor = 0;
|
|
875
|
+
while (cursor < input.length) {
|
|
876
|
+
while (/\s/.test(input[cursor] ?? ""))
|
|
877
|
+
cursor += 1;
|
|
878
|
+
if (cursor >= input.length)
|
|
879
|
+
break;
|
|
880
|
+
const character = input[cursor];
|
|
881
|
+
if (character === '"' || character === "'") {
|
|
882
|
+
const parsed = parseCssStringToken(input, cursor);
|
|
883
|
+
if (!parsed)
|
|
884
|
+
return null;
|
|
885
|
+
output += parsed.value;
|
|
886
|
+
cursor = parsed.end;
|
|
887
|
+
continue;
|
|
888
|
+
}
|
|
889
|
+
const counter = input.slice(cursor).match(/^counter\(\s*(page|pages)\s*(?:,\s*([\w-]+)\s*)?\)/i);
|
|
890
|
+
if (!counter)
|
|
891
|
+
return null;
|
|
892
|
+
if (counter[2] && counter[2].toLowerCase() !== "decimal")
|
|
893
|
+
return null;
|
|
894
|
+
output += counter[1].toLowerCase() === "pages" ? "{{pages}}" : "{{page}}";
|
|
895
|
+
cursor += counter[0].length;
|
|
896
|
+
}
|
|
897
|
+
return output;
|
|
898
|
+
}
|
|
899
|
+
function parseCssStringToken(input, start) {
|
|
900
|
+
const quote = input[start];
|
|
901
|
+
let value = "";
|
|
902
|
+
let cursor = start + 1;
|
|
903
|
+
while (cursor < input.length) {
|
|
904
|
+
const character = input[cursor];
|
|
905
|
+
if (character === quote)
|
|
906
|
+
return { value, end: cursor + 1 };
|
|
907
|
+
if (character !== "\\") {
|
|
908
|
+
value += character;
|
|
909
|
+
cursor += 1;
|
|
910
|
+
continue;
|
|
911
|
+
}
|
|
912
|
+
cursor += 1;
|
|
913
|
+
if (cursor >= input.length)
|
|
914
|
+
return null;
|
|
915
|
+
if (input[cursor] === "\n" || input[cursor] === "\f") {
|
|
916
|
+
cursor += 1;
|
|
917
|
+
continue;
|
|
918
|
+
}
|
|
919
|
+
if (input[cursor] === "\r") {
|
|
920
|
+
cursor += input[cursor + 1] === "\n" ? 2 : 1;
|
|
921
|
+
continue;
|
|
922
|
+
}
|
|
923
|
+
const hex = input.slice(cursor).match(/^[0-9a-fA-F]{1,6}/)?.[0];
|
|
924
|
+
if (hex) {
|
|
925
|
+
const codepoint = Number.parseInt(hex, 16);
|
|
926
|
+
value += String.fromCodePoint(codepoint === 0 || codepoint > 0x10FFFF ? 0xFFFD : codepoint);
|
|
927
|
+
cursor += hex.length;
|
|
928
|
+
if (/\s/.test(input[cursor] ?? ""))
|
|
929
|
+
cursor += 1;
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
value += input[cursor];
|
|
933
|
+
cursor += 1;
|
|
934
|
+
}
|
|
935
|
+
return null;
|
|
936
|
+
}
|
|
937
|
+
function nextCssAtRule(input, start) {
|
|
938
|
+
let quote = "";
|
|
939
|
+
let comment = false;
|
|
940
|
+
for (let index = start; index < input.length; index += 1) {
|
|
941
|
+
const character = input[index];
|
|
942
|
+
if (comment) {
|
|
943
|
+
if (character === "*" && input[index + 1] === "/") {
|
|
944
|
+
comment = false;
|
|
945
|
+
index += 1;
|
|
946
|
+
}
|
|
947
|
+
continue;
|
|
948
|
+
}
|
|
949
|
+
if (quote) {
|
|
950
|
+
if (character === "\\")
|
|
951
|
+
index += 1;
|
|
952
|
+
else if (character === quote)
|
|
953
|
+
quote = "";
|
|
954
|
+
continue;
|
|
955
|
+
}
|
|
956
|
+
if (character === "/" && input[index + 1] === "*") {
|
|
957
|
+
comment = true;
|
|
958
|
+
index += 1;
|
|
959
|
+
continue;
|
|
960
|
+
}
|
|
961
|
+
if (character === '"' || character === "'") {
|
|
962
|
+
quote = character;
|
|
963
|
+
continue;
|
|
964
|
+
}
|
|
965
|
+
if (character === "@")
|
|
966
|
+
return index;
|
|
967
|
+
}
|
|
968
|
+
return -1;
|
|
969
|
+
}
|
|
970
|
+
function matchingCssBrace(input, open) {
|
|
971
|
+
let depth = 0;
|
|
972
|
+
let quote = "";
|
|
973
|
+
let comment = false;
|
|
974
|
+
for (let index = open; index < input.length; index += 1) {
|
|
975
|
+
const character = input[index];
|
|
976
|
+
if (comment) {
|
|
977
|
+
if (character === "*" && input[index + 1] === "/") {
|
|
978
|
+
comment = false;
|
|
979
|
+
index += 1;
|
|
980
|
+
}
|
|
981
|
+
continue;
|
|
982
|
+
}
|
|
983
|
+
if (quote) {
|
|
984
|
+
if (character === "\\")
|
|
985
|
+
index += 1;
|
|
986
|
+
else if (character === quote)
|
|
987
|
+
quote = "";
|
|
988
|
+
continue;
|
|
989
|
+
}
|
|
990
|
+
if (character === "/" && input[index + 1] === "*") {
|
|
991
|
+
comment = true;
|
|
992
|
+
index += 1;
|
|
993
|
+
continue;
|
|
994
|
+
}
|
|
995
|
+
if (character === '"' || character === "'") {
|
|
996
|
+
quote = character;
|
|
997
|
+
continue;
|
|
998
|
+
}
|
|
999
|
+
if (character === "{")
|
|
1000
|
+
depth += 1;
|
|
1001
|
+
if (character === "}" && --depth === 0)
|
|
1002
|
+
return index;
|
|
1003
|
+
}
|
|
1004
|
+
return -1;
|
|
1005
|
+
}
|
|
1006
|
+
function parseCssPageSize(raw) {
|
|
1007
|
+
const tokens = raw.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
1008
|
+
let orientation = "auto";
|
|
1009
|
+
const dimensions = [];
|
|
1010
|
+
for (const token of tokens) {
|
|
1011
|
+
if (token === "portrait" || token === "landscape") {
|
|
1012
|
+
orientation = token;
|
|
1013
|
+
continue;
|
|
1014
|
+
}
|
|
1015
|
+
if (token !== "auto")
|
|
1016
|
+
dimensions.push(token);
|
|
1017
|
+
}
|
|
1018
|
+
let size;
|
|
1019
|
+
if (dimensions.length === 0) {
|
|
1020
|
+
size = [...DEFAULT_PAGE_SIZE_POINTS];
|
|
1021
|
+
}
|
|
1022
|
+
else if (dimensions.length === 1 && CSS_PAGE_SIZES_POINTS[dimensions[0]]) {
|
|
1023
|
+
size = [...CSS_PAGE_SIZES_POINTS[dimensions[0]]];
|
|
1024
|
+
}
|
|
1025
|
+
else if (dimensions.length === 1) {
|
|
1026
|
+
const edge = parseCssPageLength(dimensions[0], false);
|
|
1027
|
+
if (edge === null || edge <= 0)
|
|
1028
|
+
return null;
|
|
1029
|
+
size = [edge, edge];
|
|
1030
|
+
}
|
|
1031
|
+
else if (dimensions.length === 2) {
|
|
1032
|
+
const width = parseCssPageLength(dimensions[0], false);
|
|
1033
|
+
const height = parseCssPageLength(dimensions[1], false);
|
|
1034
|
+
if (width === null || height === null || width <= 0 || height <= 0)
|
|
1035
|
+
return null;
|
|
1036
|
+
size = [width, height];
|
|
1037
|
+
}
|
|
1038
|
+
else {
|
|
1039
|
+
return null;
|
|
1040
|
+
}
|
|
1041
|
+
if (orientation === "landscape" && size[0] < size[1])
|
|
1042
|
+
[size[0], size[1]] = [size[1], size[0]];
|
|
1043
|
+
if (orientation === "portrait" && size[0] > size[1])
|
|
1044
|
+
[size[0], size[1]] = [size[1], size[0]];
|
|
1045
|
+
return size;
|
|
1046
|
+
}
|
|
1047
|
+
function parseCssPageLength(raw, allowNegative) {
|
|
1048
|
+
const value = raw.trim().toLowerCase();
|
|
1049
|
+
if (value === "auto" || value === "0")
|
|
1050
|
+
return 0;
|
|
1051
|
+
const match = value.match(/^([+-]?(?:\d+\.?\d*|\.\d+))(px|pt|pc|in|cm|mm|q)$/);
|
|
1052
|
+
if (!match)
|
|
1053
|
+
return null;
|
|
1054
|
+
const number = Number.parseFloat(match[1]);
|
|
1055
|
+
if (!Number.isFinite(number) || (!allowNegative && number <= 0))
|
|
1056
|
+
return null;
|
|
1057
|
+
const scale = {
|
|
1058
|
+
px: 0.75,
|
|
1059
|
+
pt: 1,
|
|
1060
|
+
pc: 12,
|
|
1061
|
+
in: 72,
|
|
1062
|
+
cm: 72 / 2.54,
|
|
1063
|
+
mm: 72 / 25.4,
|
|
1064
|
+
q: 72 / 101.6,
|
|
1065
|
+
}[match[2]];
|
|
1066
|
+
return number * scale;
|
|
1067
|
+
}
|
|
1068
|
+
function reportUnsupportedPageValue(property, value, options, diagnostics) {
|
|
1069
|
+
const policy = options.unsupportedCss ?? (options.strict || options.cssProfile === "strict" ? "error" : "warn");
|
|
1070
|
+
if (policy === "error")
|
|
1071
|
+
throw new UnsupportedCssError(`${property}:${value} is outside the supported paged-media profile`);
|
|
1072
|
+
if (policy === "ignore")
|
|
1073
|
+
return;
|
|
1074
|
+
if (diagnostics.some((diagnostic) => diagnostic.code === "UNSUPPORTED_PAGED_MEDIA" && diagnostic.property === property))
|
|
1075
|
+
return;
|
|
1076
|
+
diagnostics.push({
|
|
1077
|
+
code: "UNSUPPORTED_PAGED_MEDIA",
|
|
1078
|
+
severity: "warning",
|
|
1079
|
+
message: `Unsupported paged-media value was ignored: ${property}: ${value}`,
|
|
1080
|
+
property,
|
|
1081
|
+
phase: "fragmentation",
|
|
1082
|
+
});
|
|
1083
|
+
}
|
|
1084
|
+
function freezeDynamicStyles(document) {
|
|
1085
|
+
const style = document.createElement("style");
|
|
1086
|
+
style.dataset.html2realpdfFreeze = "";
|
|
1087
|
+
style.textContent = "*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important}";
|
|
1088
|
+
document.documentElement.append(style);
|
|
1089
|
+
}
|
|
1090
|
+
function copySafeAttributes(source, target) {
|
|
1091
|
+
for (const attribute of [...target.attributes])
|
|
1092
|
+
target.removeAttribute(attribute.name);
|
|
1093
|
+
for (const attribute of source.attributes) {
|
|
1094
|
+
if (!attribute.name.toLowerCase().startsWith("on"))
|
|
1095
|
+
target.setAttribute(attribute.name, attribute.value);
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
function serializeAccessibleStylesheets(source) {
|
|
1099
|
+
const output = [];
|
|
1100
|
+
const sheets = [...source.styleSheets, ...(source.adoptedStyleSheets ?? [])];
|
|
1101
|
+
for (const sheet of sheets) {
|
|
1102
|
+
try {
|
|
1103
|
+
output.push([...sheet.cssRules].map((rule) => rule.cssText).join("\n"));
|
|
1104
|
+
}
|
|
1105
|
+
catch {
|
|
1106
|
+
// Cross-origin stylesheets cannot expose CSSOM. Callers that need a
|
|
1107
|
+
// deterministic alternate environment should provide those resources
|
|
1108
|
+
// through an HTML-string snapshot and resourceResolver.
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
return output.join("\n");
|
|
1112
|
+
}
|
|
1113
|
+
/**
|
|
1114
|
+
* Mirrors the authored `page` property before computed styles erase whether a
|
|
1115
|
+
* named page was explicitly selected. The returned cleanup restores inline CSS.
|
|
1116
|
+
*/
|
|
1117
|
+
function installAuthoredPageMirror(document) {
|
|
1118
|
+
const view = document.defaultView ?? window;
|
|
1119
|
+
const rules = [`*{${AUTHORED_PAGE_MIRROR}:auto}`];
|
|
1120
|
+
for (const sheet of [...document.styleSheets, ...(document.adoptedStyleSheets ?? [])]) {
|
|
1121
|
+
try {
|
|
1122
|
+
collectAuthoredPageMirrorRules(sheet.cssRules, view, rules);
|
|
1123
|
+
}
|
|
1124
|
+
catch {
|
|
1125
|
+
// Cross-origin rules have the same authored-value limitation as the
|
|
1126
|
+
// existing computed-style snapshot boundary.
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
const styleElement = document.createElement("style");
|
|
1130
|
+
styleElement.dataset.html2realpdfPageMirror = "";
|
|
1131
|
+
styleElement.textContent = rules.join("\n");
|
|
1132
|
+
(document.head ?? document.documentElement).append(styleElement);
|
|
1133
|
+
const restorations = [];
|
|
1134
|
+
for (const element of document.querySelectorAll("[style]")) {
|
|
1135
|
+
if (!("style" in element))
|
|
1136
|
+
continue;
|
|
1137
|
+
const style = element.style;
|
|
1138
|
+
const page = style.getPropertyValue("page").trim();
|
|
1139
|
+
if (!page)
|
|
1140
|
+
continue;
|
|
1141
|
+
restorations.push({
|
|
1142
|
+
style,
|
|
1143
|
+
value: style.getPropertyValue(AUTHORED_PAGE_MIRROR),
|
|
1144
|
+
priority: style.getPropertyPriority(AUTHORED_PAGE_MIRROR),
|
|
1145
|
+
});
|
|
1146
|
+
style.setProperty(AUTHORED_PAGE_MIRROR, page, style.getPropertyPriority("page"));
|
|
1147
|
+
}
|
|
1148
|
+
return () => {
|
|
1149
|
+
for (const restoration of restorations) {
|
|
1150
|
+
if (restoration.value)
|
|
1151
|
+
restoration.style.setProperty(AUTHORED_PAGE_MIRROR, restoration.value, restoration.priority);
|
|
1152
|
+
else
|
|
1153
|
+
restoration.style.removeProperty(AUTHORED_PAGE_MIRROR);
|
|
1154
|
+
}
|
|
1155
|
+
styleElement.remove();
|
|
1156
|
+
};
|
|
1157
|
+
}
|
|
1158
|
+
function collectAuthoredPageMirrorRules(rules, view, output) {
|
|
1159
|
+
for (const rule of [...rules]) {
|
|
1160
|
+
if (rule.type === CSS_STYLE_RULE && "style" in rule && "selectorText" in rule) {
|
|
1161
|
+
const styleRule = rule;
|
|
1162
|
+
const page = styleRule.style.getPropertyValue("page").trim();
|
|
1163
|
+
if (!page || styleRule.selectorText.includes("::"))
|
|
1164
|
+
continue;
|
|
1165
|
+
const important = styleRule.style.getPropertyPriority("page") === "important" ? "!important" : "";
|
|
1166
|
+
output.push(`${styleRule.selectorText}{${AUTHORED_PAGE_MIRROR}:${page}${important}}`);
|
|
1167
|
+
continue;
|
|
1168
|
+
}
|
|
1169
|
+
if (!("cssRules" in rule) || !rule.cssRules)
|
|
1170
|
+
continue;
|
|
1171
|
+
if (rule.type === CSS_MEDIA_RULE && "conditionText" in rule && !view.matchMedia(String(rule.conditionText)).matches)
|
|
1172
|
+
continue;
|
|
1173
|
+
if (rule.type === CSS_SUPPORTS_RULE && "conditionText" in rule && !CSS.supports(String(rule.conditionText)))
|
|
1174
|
+
continue;
|
|
1175
|
+
collectAuthoredPageMirrorRules(rule.cssRules, view, output);
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
/**
|
|
1179
|
+
* Preserves normal-flow dimensions and auto margins before browser used values
|
|
1180
|
+
* erase the authored page-relative intent.
|
|
1181
|
+
*/
|
|
1182
|
+
function installAuthoredFlowMirrors(document) {
|
|
1183
|
+
const view = document.defaultView ?? window;
|
|
1184
|
+
const reset = Object.values(AUTHORED_FLOW_MIRRORS)
|
|
1185
|
+
.map((property) => `${property}:initial`)
|
|
1186
|
+
.join(";");
|
|
1187
|
+
const rules = [`*{${reset}}`];
|
|
1188
|
+
for (const sheet of [...document.styleSheets, ...(document.adoptedStyleSheets ?? [])]) {
|
|
1189
|
+
try {
|
|
1190
|
+
collectAuthoredFlowMirrorRules(sheet.cssRules, view, rules);
|
|
1191
|
+
}
|
|
1192
|
+
catch {
|
|
1193
|
+
// Cross-origin declarations fall back to their computed dimensions.
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
const styleElement = document.createElement("style");
|
|
1197
|
+
styleElement.dataset.html2realpdfFlowDimensionMirror = "";
|
|
1198
|
+
styleElement.textContent = rules.join("\n");
|
|
1199
|
+
(document.head ?? document.documentElement).append(styleElement);
|
|
1200
|
+
const restorations = [];
|
|
1201
|
+
for (const element of document.querySelectorAll("[style]")) {
|
|
1202
|
+
if (!("style" in element))
|
|
1203
|
+
continue;
|
|
1204
|
+
const style = element.style;
|
|
1205
|
+
for (const [property, mirror] of Object.entries(AUTHORED_FLOW_MIRRORS)) {
|
|
1206
|
+
const value = style.getPropertyValue(property).trim();
|
|
1207
|
+
if (!value)
|
|
1208
|
+
continue;
|
|
1209
|
+
restorations.push({
|
|
1210
|
+
style,
|
|
1211
|
+
property: mirror,
|
|
1212
|
+
value: style.getPropertyValue(mirror),
|
|
1213
|
+
priority: style.getPropertyPriority(mirror),
|
|
1214
|
+
});
|
|
1215
|
+
style.setProperty(mirror, value, style.getPropertyPriority(property));
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
return () => {
|
|
1219
|
+
for (const restoration of restorations) {
|
|
1220
|
+
if (restoration.value)
|
|
1221
|
+
restoration.style.setProperty(restoration.property, restoration.value, restoration.priority);
|
|
1222
|
+
else
|
|
1223
|
+
restoration.style.removeProperty(restoration.property);
|
|
1224
|
+
}
|
|
1225
|
+
styleElement.remove();
|
|
1226
|
+
};
|
|
1227
|
+
}
|
|
1228
|
+
function collectAuthoredFlowMirrorRules(rules, view, output) {
|
|
1229
|
+
for (const rule of [...rules]) {
|
|
1230
|
+
if (rule.type === CSS_STYLE_RULE && "style" in rule && "selectorText" in rule) {
|
|
1231
|
+
const styleRule = rule;
|
|
1232
|
+
if (styleRule.selectorText.includes("::"))
|
|
1233
|
+
continue;
|
|
1234
|
+
const declarations = [];
|
|
1235
|
+
for (const [property, mirror] of Object.entries(AUTHORED_FLOW_MIRRORS)) {
|
|
1236
|
+
const value = styleRule.style.getPropertyValue(property).trim();
|
|
1237
|
+
if (!value)
|
|
1238
|
+
continue;
|
|
1239
|
+
const important = styleRule.style.getPropertyPriority(property) === "important" ? "!important" : "";
|
|
1240
|
+
declarations.push(`${mirror}:${value}${important}`);
|
|
1241
|
+
}
|
|
1242
|
+
if (declarations.length > 0)
|
|
1243
|
+
output.push(`${styleRule.selectorText}{${declarations.join(";")}}`);
|
|
1244
|
+
continue;
|
|
1245
|
+
}
|
|
1246
|
+
if (!("cssRules" in rule) || !rule.cssRules)
|
|
1247
|
+
continue;
|
|
1248
|
+
if (rule.type === CSS_MEDIA_RULE && "conditionText" in rule && !view.matchMedia(String(rule.conditionText)).matches)
|
|
1249
|
+
continue;
|
|
1250
|
+
if (rule.type === CSS_SUPPORTS_RULE && "conditionText" in rule && !CSS.supports(String(rule.conditionText)))
|
|
1251
|
+
continue;
|
|
1252
|
+
collectAuthoredFlowMirrorRules(rule.cssRules, view, output);
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
function cloneEnvironmentNode(source, targetDocument, canvasOrigins) {
|
|
1256
|
+
if (source.nodeType === Node.TEXT_NODE)
|
|
1257
|
+
return targetDocument.createTextNode(source.textContent ?? "");
|
|
1258
|
+
if (source.nodeType !== Node.ELEMENT_NODE)
|
|
1259
|
+
return targetDocument.createDocumentFragment();
|
|
1260
|
+
const original = source;
|
|
1261
|
+
const clone = targetDocument.importNode(original.cloneNode(false), false);
|
|
1262
|
+
removeEventHandlers(clone);
|
|
1263
|
+
for (const child of original.childNodes)
|
|
1264
|
+
clone.append(cloneEnvironmentNode(child, targetDocument, canvasOrigins));
|
|
1265
|
+
if (original.shadowRoot && "attachShadow" in clone) {
|
|
1266
|
+
const shadow = clone.attachShadow({ mode: "open" });
|
|
1267
|
+
for (const child of original.shadowRoot.childNodes)
|
|
1268
|
+
shadow.append(cloneEnvironmentNode(child, targetDocument, canvasOrigins));
|
|
1269
|
+
}
|
|
1270
|
+
synchronizeEnvironmentState(original, clone);
|
|
1271
|
+
if (original.localName === "canvas" && clone.localName === "canvas") {
|
|
1272
|
+
canvasOrigins.set(clone, original);
|
|
1273
|
+
}
|
|
1274
|
+
return clone;
|
|
1275
|
+
}
|
|
1276
|
+
function synchronizeEnvironmentState(original, clone) {
|
|
1277
|
+
if (original.localName === "input") {
|
|
1278
|
+
clone.value = original.value;
|
|
1279
|
+
clone.checked = original.checked;
|
|
1280
|
+
}
|
|
1281
|
+
else if (original.localName === "textarea") {
|
|
1282
|
+
clone.value = original.value;
|
|
1283
|
+
}
|
|
1284
|
+
else if (original.localName === "select") {
|
|
1285
|
+
clone.selectedIndex = original.selectedIndex;
|
|
1286
|
+
}
|
|
1287
|
+
else if (original.localName === "details") {
|
|
1288
|
+
clone.open = original.open;
|
|
1289
|
+
}
|
|
1290
|
+
else if (original.localName === "canvas") {
|
|
1291
|
+
const sourceCanvas = original;
|
|
1292
|
+
const targetCanvas = clone;
|
|
1293
|
+
targetCanvas.width = sourceCanvas.width;
|
|
1294
|
+
targetCanvas.height = sourceCanvas.height;
|
|
1295
|
+
targetCanvas.getContext("2d")?.drawImage(sourceCanvas, 0, 0);
|
|
1296
|
+
}
|
|
1297
|
+
else if (original.localName === "img" && original.currentSrc) {
|
|
1298
|
+
clone.src = original.currentSrc;
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
/**
|
|
1302
|
+
* Clones one mounted subtree without mutating it, then materializes browser-only
|
|
1303
|
+
* state and resources in stable document order.
|
|
1304
|
+
*/
|
|
1305
|
+
async function snapshotElement(element, options, canvasOrigins) {
|
|
1306
|
+
const diagnostics = [];
|
|
1307
|
+
const removePageMirror = installAuthoredPageMirror(element.ownerDocument);
|
|
1308
|
+
const removeFlowMirrors = installAuthoredFlowMirrors(element.ownerDocument);
|
|
1309
|
+
try {
|
|
1310
|
+
inspectAuthoredCss(element, options, diagnostics);
|
|
1311
|
+
const computedStyles = new SnapshotStyleCache();
|
|
1312
|
+
const counters = CounterState.forSnapshotRoot(element, options.includeShadowDom === true, computedStyles);
|
|
1313
|
+
const canvases = [];
|
|
1314
|
+
let clone = cloneSnapshotElement(element, options, diagnostics, true, counters, computedStyles, canvases, canvasOrigins);
|
|
1315
|
+
clone = await materializeCanvases(clone, canvases, options, diagnostics);
|
|
1316
|
+
for (const active of clone.matches(ACTIVE_ELEMENTS) ? [clone] : clone.querySelectorAll(ACTIVE_ELEMENTS)) {
|
|
1317
|
+
active.remove();
|
|
1318
|
+
}
|
|
1319
|
+
if (options.enableLinks === false)
|
|
1320
|
+
for (const anchor of clone.querySelectorAll("a[href]"))
|
|
1321
|
+
anchor.removeAttribute("href");
|
|
1322
|
+
const materializedInlineSvgs = await materializeInlineSvgs(clone, options, diagnostics);
|
|
1323
|
+
await materializeBackgroundImages(clone, options, diagnostics);
|
|
1324
|
+
await materializeImages(clone, options, diagnostics, materializedInlineSvgs);
|
|
1325
|
+
const pageStyle = readDefaultPageStyle(element.ownerDocument, options, diagnostics);
|
|
1326
|
+
return {
|
|
1327
|
+
clone,
|
|
1328
|
+
diagnostics,
|
|
1329
|
+
...(pageStyle.page ? { page: pageStyle.page } : {}),
|
|
1330
|
+
...(pageStyle.marginBoxes.length > 0 ? { pageMarginBoxes: pageStyle.marginBoxes } : {}),
|
|
1331
|
+
...(pageStyle.rules.length > 0 ? { pageRules: pageStyle.rules } : {}),
|
|
1332
|
+
};
|
|
1333
|
+
}
|
|
1334
|
+
finally {
|
|
1335
|
+
removeFlowMirrors();
|
|
1336
|
+
removePageMirror();
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
/**
|
|
1340
|
+
* Evaluates HTML strings in a CSP-restricted inert document where external
|
|
1341
|
+
* stylesheets are available only through the explicit resource resolver.
|
|
1342
|
+
*/
|
|
1343
|
+
async function snapshotHtmlString(source, options) {
|
|
1344
|
+
const template = document.createElement("template");
|
|
1345
|
+
template.innerHTML = source;
|
|
1346
|
+
const diagnostics = [];
|
|
1347
|
+
for (const input of template.content.querySelectorAll("input")) {
|
|
1348
|
+
const text = input.type === "checkbox" || input.type === "radio"
|
|
1349
|
+
? input.checked ? "☑" : "☐"
|
|
1350
|
+
: input.type === "password" ? "•".repeat(input.value.length) : input.value;
|
|
1351
|
+
replaceFormControl(input, text);
|
|
1352
|
+
}
|
|
1353
|
+
for (const textarea of template.content.querySelectorAll("textarea"))
|
|
1354
|
+
replaceFormControl(textarea, textarea.value, true);
|
|
1355
|
+
for (const select of template.content.querySelectorAll("select")) {
|
|
1356
|
+
replaceFormControl(select, [...select.selectedOptions].map((option) => option.text).join(", "));
|
|
1357
|
+
}
|
|
1358
|
+
for (const active of template.content.querySelectorAll(ACTIVE_ELEMENTS))
|
|
1359
|
+
active.remove();
|
|
1360
|
+
for (const refresh of template.content.querySelectorAll('meta[http-equiv="refresh" i]'))
|
|
1361
|
+
refresh.remove();
|
|
1362
|
+
for (const element of template.content.querySelectorAll("*"))
|
|
1363
|
+
removeEventHandlers(element);
|
|
1364
|
+
if (options.enableLinks === false)
|
|
1365
|
+
for (const anchor of template.content.querySelectorAll("a[href]"))
|
|
1366
|
+
anchor.removeAttribute("href");
|
|
1367
|
+
await materializeExternalStylesheets(template.content, options, diagnostics);
|
|
1368
|
+
const viewport = options.viewport ?? { width: 1280, height: 720 };
|
|
1369
|
+
const iframe = createSnapshotFrame(viewport);
|
|
1370
|
+
const csp = "default-src 'none'; script-src 'none'; style-src 'unsafe-inline'; img-src data: blob:; font-src data: blob:";
|
|
1371
|
+
iframe.srcdoc = `<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="${csp}"></head><body>${template.innerHTML}</body></html>`;
|
|
1372
|
+
document.body.append(iframe);
|
|
1373
|
+
try {
|
|
1374
|
+
await waitForSnapshotFrame(iframe);
|
|
1375
|
+
const body = iframe.contentDocument?.body;
|
|
1376
|
+
if (!body)
|
|
1377
|
+
throw new InvalidSourceError("The inert HTML snapshot document has no body");
|
|
1378
|
+
freezeDynamicStyles(body.ownerDocument);
|
|
1379
|
+
await waitForStyleResolution(body.ownerDocument.defaultView);
|
|
1380
|
+
forceRequestedMedia(body.ownerDocument, options.mediaType ?? "screen", viewport);
|
|
1381
|
+
const snapshot = await snapshotElement(body, options);
|
|
1382
|
+
return {
|
|
1383
|
+
html: snapshot.clone.innerHTML,
|
|
1384
|
+
diagnostics: [...diagnostics, ...snapshot.diagnostics],
|
|
1385
|
+
...(snapshot.page ? { page: snapshot.page } : {}),
|
|
1386
|
+
...(snapshot.pageMarginBoxes ? { pageMarginBoxes: snapshot.pageMarginBoxes } : {}),
|
|
1387
|
+
...(snapshot.pageRules ? { pageRules: snapshot.pageRules } : {}),
|
|
1388
|
+
};
|
|
1389
|
+
}
|
|
1390
|
+
finally {
|
|
1391
|
+
iframe.remove();
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
/** Replaces external stylesheet links with resolver-provided inline CSS. */
|
|
1395
|
+
async function materializeExternalStylesheets(root, options, diagnostics) {
|
|
1396
|
+
for (const link of root.querySelectorAll('link[rel~="stylesheet" i][href]')) {
|
|
1397
|
+
const source = link.getAttribute("href") ?? "";
|
|
1398
|
+
try {
|
|
1399
|
+
const url = new URL(source, options.baseUrl ?? document.baseURI);
|
|
1400
|
+
const resolved = await options.resourceResolver?.({ kind: "stylesheet", url });
|
|
1401
|
+
if (resolved === null || resolved === undefined)
|
|
1402
|
+
throw new Error("No stylesheet resource was returned by resourceResolver");
|
|
1403
|
+
const css = resolved instanceof Blob ? await resolved.text() : resolved;
|
|
1404
|
+
const style = link.ownerDocument.createElement("style");
|
|
1405
|
+
style.dataset.html2realpdfResolvedFrom = url.href;
|
|
1406
|
+
style.textContent = css;
|
|
1407
|
+
link.replaceWith(style);
|
|
1408
|
+
}
|
|
1409
|
+
catch (error) {
|
|
1410
|
+
if (options.resourcePolicy === "error")
|
|
1411
|
+
throw new ResourceLoadError(source, { cause: error });
|
|
1412
|
+
link.remove();
|
|
1413
|
+
diagnostics.push({
|
|
1414
|
+
code: "RESOURCE_OMITTED",
|
|
1415
|
+
severity: "warning",
|
|
1416
|
+
message: `Stylesheet resource was omitted: ${source}`,
|
|
1417
|
+
phase: "snapshot",
|
|
1418
|
+
});
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
/** Recursively clones DOM state, pseudo-content, counters, and open Shadow DOM. */
|
|
1423
|
+
function cloneSnapshotElement(original, options, diagnostics, isSnapshotRoot, counters, computedStyles, canvases, canvasOrigins, inheritedStyle) {
|
|
1424
|
+
const leaveCounterScope = counters.enter(original);
|
|
1425
|
+
const target = original.cloneNode(false);
|
|
1426
|
+
try {
|
|
1427
|
+
const computed = computedStyles.forElement(original);
|
|
1428
|
+
materializeComputedStyle(original, target, options, diagnostics, isSnapshotRoot, computed, true, inheritedStyle);
|
|
1429
|
+
materializePseudoElement(original, target, "::before", options, diagnostics, counters, computedStyles);
|
|
1430
|
+
const childRoot = options.includeShadowDom && original.shadowRoot ? original.shadowRoot : original;
|
|
1431
|
+
for (const child of childRoot.childNodes)
|
|
1432
|
+
appendSnapshotNode(target, child, options, diagnostics, counters, computedStyles, canvases, canvasOrigins, computed);
|
|
1433
|
+
materializePseudoElement(original, target, "::after", options, diagnostics, counters, computedStyles);
|
|
1434
|
+
const materialized = materializeLiveState(original, target);
|
|
1435
|
+
if (original.localName === "canvas" && materialized.localName === "canvas") {
|
|
1436
|
+
canvases.push({
|
|
1437
|
+
source: canvasOrigins?.get(original) ?? original,
|
|
1438
|
+
target: materialized,
|
|
1439
|
+
});
|
|
1440
|
+
}
|
|
1441
|
+
removeEventHandlers(materialized);
|
|
1442
|
+
if (childRoot !== original)
|
|
1443
|
+
materialized.setAttribute("data-html2realpdf-shadow-host", "open");
|
|
1444
|
+
return materialized;
|
|
1445
|
+
}
|
|
1446
|
+
finally {
|
|
1447
|
+
leaveCounterScope();
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
function appendSnapshotNode(parent, source, options, diagnostics, counters, computedStyles, canvases, canvasOrigins, inheritedStyle) {
|
|
1451
|
+
if (source.nodeType === Node.TEXT_NODE) {
|
|
1452
|
+
parent.append(parent.ownerDocument.createTextNode(source.textContent ?? ""));
|
|
1453
|
+
return;
|
|
1454
|
+
}
|
|
1455
|
+
if (source.nodeType !== Node.ELEMENT_NODE)
|
|
1456
|
+
return;
|
|
1457
|
+
const element = source;
|
|
1458
|
+
if (options.includeShadowDom && element.localName === "slot") {
|
|
1459
|
+
const slot = element;
|
|
1460
|
+
const assigned = slot.assignedNodes({ flatten: true });
|
|
1461
|
+
const nodes = assigned.length > 0 ? assigned : [...slot.childNodes];
|
|
1462
|
+
for (const node of nodes)
|
|
1463
|
+
appendSnapshotNode(parent, node, options, diagnostics, counters, computedStyles, canvases, canvasOrigins, inheritedStyle);
|
|
1464
|
+
return;
|
|
1465
|
+
}
|
|
1466
|
+
parent.append(cloneSnapshotElement(element, options, diagnostics, false, counters, computedStyles, canvases, canvasOrigins, inheritedStyle));
|
|
1467
|
+
}
|
|
1468
|
+
function forceRequestedMedia(document, mediaType, viewport) {
|
|
1469
|
+
const view = document.defaultView ?? window;
|
|
1470
|
+
for (const stylesheet of document.styleSheets) {
|
|
1471
|
+
try {
|
|
1472
|
+
forceMediaRules(stylesheet.cssRules, mediaType, viewport, view);
|
|
1473
|
+
}
|
|
1474
|
+
catch {
|
|
1475
|
+
// CSP prevents remote stylesheets in inert snapshots. If a browser still
|
|
1476
|
+
// exposes a cross-origin sheet, computed styles remain available for the
|
|
1477
|
+
// declarations the browser was allowed to load.
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
function forceShadowMediaRules(root, mediaType, viewport) {
|
|
1482
|
+
const visit = (element) => {
|
|
1483
|
+
const shadow = element.shadowRoot;
|
|
1484
|
+
if (shadow) {
|
|
1485
|
+
const view = shadow.ownerDocument.defaultView ?? window;
|
|
1486
|
+
for (const style of shadow.querySelectorAll("style")) {
|
|
1487
|
+
if (style.sheet)
|
|
1488
|
+
forceMediaRules(style.sheet.cssRules, mediaType, viewport, view);
|
|
1489
|
+
}
|
|
1490
|
+
for (const sheet of shadow.adoptedStyleSheets ?? [])
|
|
1491
|
+
forceMediaRules(sheet.cssRules, mediaType, viewport, view);
|
|
1492
|
+
for (const child of shadow.children)
|
|
1493
|
+
visit(child);
|
|
1494
|
+
}
|
|
1495
|
+
for (const child of element.children)
|
|
1496
|
+
visit(child);
|
|
1497
|
+
};
|
|
1498
|
+
visit(root);
|
|
1499
|
+
}
|
|
1500
|
+
function forceMediaRules(rules, mediaType, viewport, view) {
|
|
1501
|
+
// CSSRuleList is live. Firefox can skip a following @media rule when the
|
|
1502
|
+
// current MediaList is mutated during iteration, so walk a stable snapshot.
|
|
1503
|
+
for (const rule of [...rules]) {
|
|
1504
|
+
if ("media" in rule && "conditionText" in rule) {
|
|
1505
|
+
const mediaRule = rule;
|
|
1506
|
+
const matches = matchesRequestedMedia(String(mediaRule.conditionText), mediaType, viewport, view);
|
|
1507
|
+
mediaRule.media.mediaText = matches ? "all" : "not all";
|
|
1508
|
+
if (matches)
|
|
1509
|
+
forceMediaRules(mediaRule.cssRules, mediaType, viewport, view);
|
|
1510
|
+
continue;
|
|
1511
|
+
}
|
|
1512
|
+
if ("cssRules" in rule && rule.cssRules) {
|
|
1513
|
+
forceMediaRules(rule.cssRules, mediaType, viewport, view);
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
function matchesRequestedMedia(queryList, mediaType, viewport, view) {
|
|
1518
|
+
return splitMediaQueries(queryList).some((query) => matchesSingleMediaQuery(query, mediaType, viewport, view));
|
|
1519
|
+
}
|
|
1520
|
+
function splitMediaQueries(input) {
|
|
1521
|
+
const queries = [];
|
|
1522
|
+
let depth = 0;
|
|
1523
|
+
let start = 0;
|
|
1524
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
1525
|
+
if (input[index] === "(")
|
|
1526
|
+
depth += 1;
|
|
1527
|
+
else if (input[index] === ")")
|
|
1528
|
+
depth = Math.max(depth - 1, 0);
|
|
1529
|
+
else if (input[index] === "," && depth === 0) {
|
|
1530
|
+
queries.push(input.slice(start, index));
|
|
1531
|
+
start = index + 1;
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
queries.push(input.slice(start));
|
|
1535
|
+
return queries;
|
|
1536
|
+
}
|
|
1537
|
+
function matchesSingleMediaQuery(input, mediaType, viewport, view) {
|
|
1538
|
+
let query = input.trim().toLowerCase();
|
|
1539
|
+
if (!query)
|
|
1540
|
+
return false;
|
|
1541
|
+
let negate = false;
|
|
1542
|
+
if (query.startsWith("not ")) {
|
|
1543
|
+
negate = true;
|
|
1544
|
+
query = query.slice(4).trim();
|
|
1545
|
+
}
|
|
1546
|
+
else if (query.startsWith("only ")) {
|
|
1547
|
+
query = query.slice(5).trim();
|
|
1548
|
+
}
|
|
1549
|
+
const typeMatch = query.match(/^(all|screen|print)\b/);
|
|
1550
|
+
if (!typeMatch)
|
|
1551
|
+
return matchesViewportMediaFeatures(input, viewport) ?? view.matchMedia(input).matches;
|
|
1552
|
+
const requestedTypeMatches = typeMatch[1] === "all" || typeMatch[1] === mediaType;
|
|
1553
|
+
let remainder = query.slice(typeMatch[0].length).trim();
|
|
1554
|
+
if (remainder.startsWith("and "))
|
|
1555
|
+
remainder = remainder.slice(4).trim();
|
|
1556
|
+
const featureMatches = !remainder || (matchesViewportMediaFeatures(remainder, viewport) ?? view.matchMedia(remainder).matches);
|
|
1557
|
+
const matches = requestedTypeMatches && featureMatches;
|
|
1558
|
+
return negate ? !matches : matches;
|
|
1559
|
+
}
|
|
1560
|
+
function matchesViewportMediaFeatures(input, viewport) {
|
|
1561
|
+
const conditions = input.toLowerCase().split(/\s+and\s+/).map((condition) => condition.trim()).filter(Boolean);
|
|
1562
|
+
if (conditions.length === 0)
|
|
1563
|
+
return true;
|
|
1564
|
+
for (const condition of conditions) {
|
|
1565
|
+
const dimension = condition.match(/^\((min|max)-(width|height)\s*:\s*([+-]?(?:\d+\.?\d*|\.\d+))(px|em|rem)\)$/);
|
|
1566
|
+
if (dimension) {
|
|
1567
|
+
const factor = dimension[4] === "px" ? 1 : 16;
|
|
1568
|
+
const expected = Number.parseFloat(dimension[3] ?? "0") * factor;
|
|
1569
|
+
const actual = dimension[2] === "width" ? viewport.width : viewport.height;
|
|
1570
|
+
if (dimension[1] === "min" ? actual < expected : actual > expected)
|
|
1571
|
+
return false;
|
|
1572
|
+
continue;
|
|
1573
|
+
}
|
|
1574
|
+
const orientation = condition.match(/^\(orientation\s*:\s*(portrait|landscape)\)$/);
|
|
1575
|
+
if (orientation) {
|
|
1576
|
+
const actual = viewport.width > viewport.height ? "landscape" : "portrait";
|
|
1577
|
+
if (actual !== orientation[1])
|
|
1578
|
+
return false;
|
|
1579
|
+
continue;
|
|
1580
|
+
}
|
|
1581
|
+
return null;
|
|
1582
|
+
}
|
|
1583
|
+
return true;
|
|
1584
|
+
}
|
|
1585
|
+
function isRefLike(source) {
|
|
1586
|
+
return !(source instanceof Element) && "current" in source;
|
|
1587
|
+
}
|
|
1588
|
+
/** Reuses stable computed declarations across counter and clone traversals. */
|
|
1589
|
+
class SnapshotStyleCache {
|
|
1590
|
+
#elements = new Map();
|
|
1591
|
+
#pseudos = new Map();
|
|
1592
|
+
forElement(element) {
|
|
1593
|
+
const cached = this.#elements.get(element);
|
|
1594
|
+
if (cached)
|
|
1595
|
+
return cached;
|
|
1596
|
+
const computed = (element.ownerDocument.defaultView ?? window).getComputedStyle(element);
|
|
1597
|
+
this.#elements.set(element, computed);
|
|
1598
|
+
return computed;
|
|
1599
|
+
}
|
|
1600
|
+
forPseudo(element, pseudo) {
|
|
1601
|
+
const cached = this.#pseudos.get(element)?.[pseudo];
|
|
1602
|
+
if (cached)
|
|
1603
|
+
return cached;
|
|
1604
|
+
const computed = (element.ownerDocument.defaultView ?? window).getComputedStyle(element, pseudo);
|
|
1605
|
+
const pseudos = this.#pseudos.get(element) ?? {};
|
|
1606
|
+
pseudos[pseudo] = computed;
|
|
1607
|
+
this.#pseudos.set(element, pseudos);
|
|
1608
|
+
return computed;
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
/**
|
|
1612
|
+
* Models CSS counter scope over the live tree before pseudo-elements become
|
|
1613
|
+
* synthetic text nodes in the flat renderer input.
|
|
1614
|
+
*/
|
|
1615
|
+
class CounterState {
|
|
1616
|
+
computedStyles;
|
|
1617
|
+
#elements = new Map();
|
|
1618
|
+
#pseudos = new Map();
|
|
1619
|
+
#active = [];
|
|
1620
|
+
#lastNode = null;
|
|
1621
|
+
static forSnapshotRoot(root, includeShadowDom, computedStyles) {
|
|
1622
|
+
const state = new CounterState(computedStyles);
|
|
1623
|
+
const treeRoot = root.ownerDocument.documentElement;
|
|
1624
|
+
if (treeRoot?.contains(root))
|
|
1625
|
+
state.buildElement(treeRoot, null, null, includeShadowDom, false);
|
|
1626
|
+
else
|
|
1627
|
+
state.buildElement(root, null, null, includeShadowDom, false);
|
|
1628
|
+
return state;
|
|
1629
|
+
}
|
|
1630
|
+
constructor(computedStyles) {
|
|
1631
|
+
this.computedStyles = computedStyles;
|
|
1632
|
+
}
|
|
1633
|
+
enter(element) {
|
|
1634
|
+
const previous = this.#active;
|
|
1635
|
+
this.#active = this.#elements.get(element)?.counters ?? [];
|
|
1636
|
+
return () => {
|
|
1637
|
+
this.#active = previous;
|
|
1638
|
+
};
|
|
1639
|
+
}
|
|
1640
|
+
enterPseudo(element, pseudo) {
|
|
1641
|
+
const previous = this.#active;
|
|
1642
|
+
this.#active = this.#pseudos.get(element)?.[pseudo]?.counters ?? previous;
|
|
1643
|
+
return () => {
|
|
1644
|
+
this.#active = previous;
|
|
1645
|
+
};
|
|
1646
|
+
}
|
|
1647
|
+
current(name) {
|
|
1648
|
+
return findInnermostCounter(this.#active, name)?.value ?? 0;
|
|
1649
|
+
}
|
|
1650
|
+
values(name) {
|
|
1651
|
+
const values = this.#active.filter((counter) => counter.name === name).map((counter) => counter.value);
|
|
1652
|
+
return values.length ? values : [0];
|
|
1653
|
+
}
|
|
1654
|
+
buildElement(element, parent, previousSibling, includeShadowDom, suppressed) {
|
|
1655
|
+
const node = this.createNode(parent, previousSibling);
|
|
1656
|
+
this.#elements.set(element, node);
|
|
1657
|
+
const computed = this.computedStyles.forElement(element);
|
|
1658
|
+
const hidden = suppressed || computed.getPropertyValue("display") === "none";
|
|
1659
|
+
if (!hidden)
|
|
1660
|
+
applyCounterProperties(node, computed);
|
|
1661
|
+
this.#lastNode = node;
|
|
1662
|
+
let childSibling = null;
|
|
1663
|
+
const before = this.buildPseudo(element, "::before", node, childSibling, hidden);
|
|
1664
|
+
if (before)
|
|
1665
|
+
childSibling = before;
|
|
1666
|
+
for (const child of counterChildren(element, includeShadowDom)) {
|
|
1667
|
+
childSibling = this.buildElement(child, node, childSibling, includeShadowDom, hidden);
|
|
1668
|
+
}
|
|
1669
|
+
this.buildPseudo(element, "::after", node, childSibling, hidden);
|
|
1670
|
+
return node;
|
|
1671
|
+
}
|
|
1672
|
+
buildPseudo(element, pseudo, parent, previousSibling, suppressed) {
|
|
1673
|
+
if (suppressed || isReplacedOrControl(element))
|
|
1674
|
+
return null;
|
|
1675
|
+
const computed = this.computedStyles.forPseudo(element, pseudo);
|
|
1676
|
+
const content = computed.getPropertyValue("content").trim();
|
|
1677
|
+
if (!content || content === "none" || content === "normal" || computed.getPropertyValue("display") === "none")
|
|
1678
|
+
return null;
|
|
1679
|
+
const node = this.createNode(parent, previousSibling);
|
|
1680
|
+
applyCounterProperties(node, computed);
|
|
1681
|
+
const pseudos = this.#pseudos.get(element) ?? {};
|
|
1682
|
+
pseudos[pseudo] = node;
|
|
1683
|
+
this.#pseudos.set(element, pseudos);
|
|
1684
|
+
this.#lastNode = node;
|
|
1685
|
+
return node;
|
|
1686
|
+
}
|
|
1687
|
+
createNode(parent, previousSibling) {
|
|
1688
|
+
const counters = parent ? cloneCounters(parent.counters) : [];
|
|
1689
|
+
if (previousSibling) {
|
|
1690
|
+
for (const counter of previousSibling.counters) {
|
|
1691
|
+
if (!counters.some((candidate) => candidate.name === counter.name))
|
|
1692
|
+
counters.push({ ...counter });
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
if (this.#lastNode) {
|
|
1696
|
+
for (const source of this.#lastNode.counters) {
|
|
1697
|
+
const target = counters.find((candidate) => candidate.name === source.name && candidate.creator === source.creator);
|
|
1698
|
+
if (target)
|
|
1699
|
+
target.value = source.value;
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
return { parent, previousSibling, counters };
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
function counterChildren(element, includeShadowDom) {
|
|
1706
|
+
if (includeShadowDom && element.localName === "slot") {
|
|
1707
|
+
const assigned = element.assignedElements({ flatten: true });
|
|
1708
|
+
return assigned.length ? assigned : [...element.children];
|
|
1709
|
+
}
|
|
1710
|
+
if (includeShadowDom && element.shadowRoot)
|
|
1711
|
+
return [...element.shadowRoot.children];
|
|
1712
|
+
return [...element.children];
|
|
1713
|
+
}
|
|
1714
|
+
function cloneCounters(counters) {
|
|
1715
|
+
return counters.map((counter) => ({ ...counter }));
|
|
1716
|
+
}
|
|
1717
|
+
function findInnermostCounter(counters, name) {
|
|
1718
|
+
for (let index = counters.length - 1; index >= 0; index -= 1) {
|
|
1719
|
+
if (counters[index]?.name === name)
|
|
1720
|
+
return counters[index];
|
|
1721
|
+
}
|
|
1722
|
+
return undefined;
|
|
1723
|
+
}
|
|
1724
|
+
function applyCounterProperties(node, computed) {
|
|
1725
|
+
const resets = parseCounterOperations(computed.getPropertyValue("counter-reset"), 0);
|
|
1726
|
+
for (let index = 0; index < resets.length; index += 1) {
|
|
1727
|
+
const operation = resets[index];
|
|
1728
|
+
if (!operation || resets.slice(index + 1).some((candidate) => candidate.name === operation.name))
|
|
1729
|
+
continue;
|
|
1730
|
+
instantiateCounter(node, operation.name, operation.value);
|
|
1731
|
+
}
|
|
1732
|
+
for (const operation of parseCounterOperations(computed.getPropertyValue("counter-increment"), 1)) {
|
|
1733
|
+
const counter = findInnermostCounter(node.counters, operation.name) ?? instantiateCounter(node, operation.name, 0);
|
|
1734
|
+
counter.value += operation.value;
|
|
1735
|
+
}
|
|
1736
|
+
for (const operation of parseCounterOperations(computed.getPropertyValue("counter-set"), 0)) {
|
|
1737
|
+
const counter = findInnermostCounter(node.counters, operation.name) ?? instantiateCounter(node, operation.name, 0);
|
|
1738
|
+
counter.value = operation.value;
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
function instantiateCounter(node, name, value) {
|
|
1742
|
+
const innermost = findInnermostCounter(node.counters, name);
|
|
1743
|
+
if (innermost && (innermost.creator === node || innermost.creator.parent === node.parent)) {
|
|
1744
|
+
node.counters.splice(node.counters.indexOf(innermost), 1);
|
|
1745
|
+
}
|
|
1746
|
+
const counter = { name, creator: node, value };
|
|
1747
|
+
node.counters.push(counter);
|
|
1748
|
+
return counter;
|
|
1749
|
+
}
|
|
1750
|
+
function parseCounterOperations(value, defaultValue) {
|
|
1751
|
+
const normalized = value.trim();
|
|
1752
|
+
if (!normalized || normalized === "none")
|
|
1753
|
+
return [];
|
|
1754
|
+
const tokens = normalized.split(/\s+/);
|
|
1755
|
+
const operations = [];
|
|
1756
|
+
for (let index = 0; index < tokens.length;) {
|
|
1757
|
+
const name = tokens[index++];
|
|
1758
|
+
if (!name || name.startsWith("reversed(") || name === "none")
|
|
1759
|
+
return [];
|
|
1760
|
+
let counterValue = defaultValue;
|
|
1761
|
+
const explicitValue = tokens[index];
|
|
1762
|
+
if (explicitValue && /^[+-]?\d+$/.test(explicitValue)) {
|
|
1763
|
+
counterValue = Number.parseInt(explicitValue, 10);
|
|
1764
|
+
index += 1;
|
|
1765
|
+
}
|
|
1766
|
+
operations.push({ name, value: counterValue });
|
|
1767
|
+
}
|
|
1768
|
+
return operations;
|
|
1769
|
+
}
|
|
1770
|
+
/**
|
|
1771
|
+
* Freezes the supported computed-style subset while retaining authored values
|
|
1772
|
+
* needed later for paged and positioned layout decisions.
|
|
1773
|
+
*/
|
|
1774
|
+
function materializeComputedStyle(original, target, options, diagnostics, isSnapshotRoot, computedStyle, preserveAuthoredInsets = false, inheritedStyle) {
|
|
1775
|
+
const view = original.ownerDocument.defaultView ?? window;
|
|
1776
|
+
const computed = computedStyle ?? view.getComputedStyle(original);
|
|
1777
|
+
const display = normalizeComputedDisplay(original, computed.getPropertyValue("display"));
|
|
1778
|
+
const position = computed.getPropertyValue("position");
|
|
1779
|
+
const floatValue = computed.getPropertyValue("float");
|
|
1780
|
+
if (!SUPPORTED_DISPLAY.has(display) || (["flex", "inline-flex", "grid", "inline-grid"].includes(display) && !usesWebLayout(options))) {
|
|
1781
|
+
throw new UnsupportedCssError(`display:${display} is outside the document/report layout profile`);
|
|
1782
|
+
}
|
|
1783
|
+
if (position !== "static" && !usesWebLayout(options)) {
|
|
1784
|
+
throw new UnsupportedCssError(`position:${position} is outside the document/report layout profile`);
|
|
1785
|
+
}
|
|
1786
|
+
if (floatValue !== "none" && !usesWebLayout(options)) {
|
|
1787
|
+
throw new UnsupportedCssError(`float:${floatValue} is outside the document/report layout profile`);
|
|
1788
|
+
}
|
|
1789
|
+
const transformValue = computed.getPropertyValue("transform");
|
|
1790
|
+
if (transformValue && transformValue !== "none" && !usesWebLayout(options)) {
|
|
1791
|
+
reportUnsupportedCss("transform", options, diagnostics);
|
|
1792
|
+
}
|
|
1793
|
+
else if (transformValue.startsWith("matrix3d(")) {
|
|
1794
|
+
reportUnsupportedCss("transform", options, diagnostics);
|
|
1795
|
+
}
|
|
1796
|
+
if (!isSvgElement(original)) {
|
|
1797
|
+
const unsupportedComputed = [
|
|
1798
|
+
["filter", computed.getPropertyValue("filter"), "none", false],
|
|
1799
|
+
["background-image", computed.getPropertyValue("background-image"), "none", true],
|
|
1800
|
+
["box-shadow", computed.getPropertyValue("box-shadow"), "none", true],
|
|
1801
|
+
["text-shadow", computed.getPropertyValue("text-shadow"), "none", true],
|
|
1802
|
+
];
|
|
1803
|
+
for (const [property, value, initial, webSupported] of unsupportedComputed) {
|
|
1804
|
+
if (value && value !== initial && (!webSupported || !usesWebLayout(options)) && !/^0px(?: 0px){0,3}$/.test(value)) {
|
|
1805
|
+
reportUnsupportedCss(property, options, diagnostics);
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
const declarations = [];
|
|
1810
|
+
const authoredInsets = preserveAuthoredInsets && position !== "static"
|
|
1811
|
+
? authoredInsetOverrides(original, computed, view)
|
|
1812
|
+
: undefined;
|
|
1813
|
+
const properties = isSvgElement(original)
|
|
1814
|
+
? [...SUPPORTED_COMPUTED_PROPERTIES, ...SVG_COMPUTED_PROPERTIES]
|
|
1815
|
+
: SUPPORTED_COMPUTED_PROPERTIES;
|
|
1816
|
+
for (const property of properties) {
|
|
1817
|
+
const nativePage = property === "page" ? computed.getPropertyValue("page").trim() : "";
|
|
1818
|
+
const mirroredPage = property === "page" ? computed.getPropertyValue(AUTHORED_PAGE_MIRROR).trim() : "";
|
|
1819
|
+
const authoredFlowDimension = isFlowDimension(property)
|
|
1820
|
+
? computed.getPropertyValue(AUTHORED_FLOW_DIMENSION_MIRRORS[property]).trim()
|
|
1821
|
+
: "";
|
|
1822
|
+
const authoredAutoMargin = isAutoMargin(property)
|
|
1823
|
+
? computed.getPropertyValue(AUTHORED_AUTO_MARGIN_MIRRORS[property]).trim()
|
|
1824
|
+
: "";
|
|
1825
|
+
const value = property === "display"
|
|
1826
|
+
? display
|
|
1827
|
+
: property === "page"
|
|
1828
|
+
? nativePage && nativePage !== "auto" ? nativePage : mirroredPage || nativePage
|
|
1829
|
+
: options.layoutContext === "page" && authoredAutoMargin === "auto"
|
|
1830
|
+
? "auto"
|
|
1831
|
+
: authoredFlowDimension.endsWith("%")
|
|
1832
|
+
? authoredFlowDimension
|
|
1833
|
+
: authoredInsets && property in authoredInsets
|
|
1834
|
+
? authoredInsets[property]
|
|
1835
|
+
: computed.getPropertyValue(property);
|
|
1836
|
+
if (isFlowDimension(property)) {
|
|
1837
|
+
if (authoredFlowDimension === "auto" || !shouldMaterializeFlowDimension(original, property, isSnapshotRoot, options.layoutContext))
|
|
1838
|
+
continue;
|
|
1839
|
+
}
|
|
1840
|
+
// A fully transparent background has no paint effect. Omitting it keeps
|
|
1841
|
+
// the display list compact while semi-transparent colors retain real PDF
|
|
1842
|
+
// alpha through ExtGState.
|
|
1843
|
+
if (property === "background-color" && isFullyTransparentColor(value))
|
|
1844
|
+
continue;
|
|
1845
|
+
if (!isFlowDimension(property) && isRedundantComputedValue(original, property, value, inheritedStyle))
|
|
1846
|
+
continue;
|
|
1847
|
+
if (value)
|
|
1848
|
+
declarations.push(`${property}:${value}`);
|
|
1849
|
+
}
|
|
1850
|
+
target.setAttribute("style", declarations.join(";"));
|
|
1851
|
+
}
|
|
1852
|
+
function authoredInsetOverrides(element, computed, view) {
|
|
1853
|
+
const authored = new Set();
|
|
1854
|
+
if ("style" in element)
|
|
1855
|
+
collectInsetDeclarations(element.style, authored);
|
|
1856
|
+
const stylesheets = [...element.ownerDocument.styleSheets, ...(element.ownerDocument.adoptedStyleSheets ?? [])];
|
|
1857
|
+
for (const stylesheet of stylesheets) {
|
|
1858
|
+
try {
|
|
1859
|
+
collectMatchedInsetRules(element, stylesheet.cssRules, view, authored);
|
|
1860
|
+
}
|
|
1861
|
+
catch {
|
|
1862
|
+
// Cross-origin sheets do not expose their rules. The computed fallback
|
|
1863
|
+
// remains available, but authored-side recovery cannot inspect them.
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
const result = {};
|
|
1867
|
+
if (authored.has("top") || authored.has("bottom")) {
|
|
1868
|
+
result.top = authored.has("top") ? computed.getPropertyValue("top") : "auto";
|
|
1869
|
+
result.bottom = authored.has("bottom") ? computed.getPropertyValue("bottom") : "auto";
|
|
1870
|
+
}
|
|
1871
|
+
if (authored.has("left") || authored.has("right")) {
|
|
1872
|
+
result.left = authored.has("left") ? computed.getPropertyValue("left") : "auto";
|
|
1873
|
+
result.right = authored.has("right") ? computed.getPropertyValue("right") : "auto";
|
|
1874
|
+
}
|
|
1875
|
+
return Object.keys(result).length > 0 ? result : undefined;
|
|
1876
|
+
}
|
|
1877
|
+
function collectMatchedInsetRules(element, rules, view, authored) {
|
|
1878
|
+
for (const rule of [...rules]) {
|
|
1879
|
+
if (rule.type === CSS_STYLE_RULE && "selectorText" in rule && "style" in rule) {
|
|
1880
|
+
try {
|
|
1881
|
+
if (element.matches(String(rule.selectorText))) {
|
|
1882
|
+
collectInsetDeclarations(rule.style, authored);
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
catch {
|
|
1886
|
+
// A selector unsupported by Element.matches cannot contribute to the
|
|
1887
|
+
// browser's matched rule set for this snapshot element.
|
|
1888
|
+
}
|
|
1889
|
+
continue;
|
|
1890
|
+
}
|
|
1891
|
+
if (!("cssRules" in rule) || !rule.cssRules)
|
|
1892
|
+
continue;
|
|
1893
|
+
if (rule.type === CSS_MEDIA_RULE && "conditionText" in rule && !view.matchMedia(String(rule.conditionText)).matches)
|
|
1894
|
+
continue;
|
|
1895
|
+
if (rule.type === CSS_SUPPORTS_RULE && "conditionText" in rule && !CSS.supports(String(rule.conditionText)))
|
|
1896
|
+
continue;
|
|
1897
|
+
collectMatchedInsetRules(element, rule.cssRules, view, authored);
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1900
|
+
function collectInsetDeclarations(style, authored) {
|
|
1901
|
+
for (const property of ["top", "right", "bottom", "left"]) {
|
|
1902
|
+
if (style.getPropertyValue(property).trim())
|
|
1903
|
+
authored.add(property);
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
function materializePseudoElement(original, target, pseudo, options, diagnostics, counters, computedStyles) {
|
|
1907
|
+
if (isReplacedOrControl(original))
|
|
1908
|
+
return;
|
|
1909
|
+
const computed = computedStyles.forPseudo(original, pseudo);
|
|
1910
|
+
const rawContent = computed.getPropertyValue("content").trim();
|
|
1911
|
+
if (!rawContent || rawContent === "none" || rawContent === "normal")
|
|
1912
|
+
return;
|
|
1913
|
+
const leaveCounterScope = counters.enterPseudo(original, pseudo);
|
|
1914
|
+
try {
|
|
1915
|
+
const content = resolveGeneratedContent(rawContent, original, counters);
|
|
1916
|
+
if (content === null) {
|
|
1917
|
+
reportUnsupportedCss(`content:${rawContent}`, options, diagnostics);
|
|
1918
|
+
return;
|
|
1919
|
+
}
|
|
1920
|
+
const synthetic = target.ownerDocument.createElement("span");
|
|
1921
|
+
synthetic.dataset.html2realpdfPseudo = pseudo.slice(2);
|
|
1922
|
+
synthetic.textContent = content;
|
|
1923
|
+
materializeComputedStyle(original, synthetic, options, diagnostics, false, computed, false, computedStyles.forElement(original));
|
|
1924
|
+
target.append(synthetic);
|
|
1925
|
+
}
|
|
1926
|
+
finally {
|
|
1927
|
+
leaveCounterScope();
|
|
1928
|
+
}
|
|
1929
|
+
}
|
|
1930
|
+
function resolveGeneratedContent(value, original, counters) {
|
|
1931
|
+
let output = "";
|
|
1932
|
+
let index = 0;
|
|
1933
|
+
while (index < value.length) {
|
|
1934
|
+
while (/\s/.test(value[index] ?? ""))
|
|
1935
|
+
index += 1;
|
|
1936
|
+
if (index >= value.length)
|
|
1937
|
+
break;
|
|
1938
|
+
const quote = value[index];
|
|
1939
|
+
if (quote === '"' || quote === "'") {
|
|
1940
|
+
const parsed = consumeCssString(value, index, quote);
|
|
1941
|
+
if (!parsed)
|
|
1942
|
+
return null;
|
|
1943
|
+
output += parsed.value;
|
|
1944
|
+
index = parsed.next;
|
|
1945
|
+
continue;
|
|
1946
|
+
}
|
|
1947
|
+
if (value.startsWith("attr(", index)) {
|
|
1948
|
+
const parsed = consumeCssFunction(value, index, "attr");
|
|
1949
|
+
if (!parsed)
|
|
1950
|
+
return null;
|
|
1951
|
+
const name = parsed.value.trim().split(/\s+/)[0];
|
|
1952
|
+
if (!name)
|
|
1953
|
+
return null;
|
|
1954
|
+
output += original.getAttribute(name) ?? "";
|
|
1955
|
+
index = parsed.next;
|
|
1956
|
+
continue;
|
|
1957
|
+
}
|
|
1958
|
+
if (value.startsWith("counter(", index) || value.startsWith("counters(", index)) {
|
|
1959
|
+
const plural = value.startsWith("counters(", index);
|
|
1960
|
+
const parsed = consumeCssFunction(value, index, plural ? "counters" : "counter");
|
|
1961
|
+
if (!parsed)
|
|
1962
|
+
return null;
|
|
1963
|
+
const formatted = resolveCounterFunction(parsed.value, plural, counters);
|
|
1964
|
+
if (formatted === null)
|
|
1965
|
+
return null;
|
|
1966
|
+
output += formatted;
|
|
1967
|
+
index = parsed.next;
|
|
1968
|
+
continue;
|
|
1969
|
+
}
|
|
1970
|
+
if (value.startsWith("open-quote", index) || value.startsWith("close-quote", index)) {
|
|
1971
|
+
output += value.startsWith("open-quote", index) ? "\u201c" : "\u201d";
|
|
1972
|
+
index += value.startsWith("open-quote", index) ? 10 : 11;
|
|
1973
|
+
continue;
|
|
1974
|
+
}
|
|
1975
|
+
if (value.startsWith("no-open-quote", index)) {
|
|
1976
|
+
index += 13;
|
|
1977
|
+
continue;
|
|
1978
|
+
}
|
|
1979
|
+
if (value.startsWith("no-close-quote", index)) {
|
|
1980
|
+
index += 14;
|
|
1981
|
+
continue;
|
|
1982
|
+
}
|
|
1983
|
+
return null;
|
|
1984
|
+
}
|
|
1985
|
+
return output;
|
|
1986
|
+
}
|
|
1987
|
+
function consumeCssFunction(source, start, name) {
|
|
1988
|
+
const prefix = `${name}(`;
|
|
1989
|
+
if (!source.startsWith(prefix, start))
|
|
1990
|
+
return null;
|
|
1991
|
+
const valueStart = start + prefix.length;
|
|
1992
|
+
let depth = 1;
|
|
1993
|
+
let index = valueStart;
|
|
1994
|
+
while (index < source.length) {
|
|
1995
|
+
const character = source[index];
|
|
1996
|
+
if (character === '"' || character === "'") {
|
|
1997
|
+
const parsed = consumeCssString(source, index, character);
|
|
1998
|
+
if (!parsed)
|
|
1999
|
+
return null;
|
|
2000
|
+
index = parsed.next;
|
|
2001
|
+
continue;
|
|
2002
|
+
}
|
|
2003
|
+
if (character === "\\") {
|
|
2004
|
+
index = Math.min(index + 2, source.length);
|
|
2005
|
+
continue;
|
|
2006
|
+
}
|
|
2007
|
+
if (character === "(")
|
|
2008
|
+
depth += 1;
|
|
2009
|
+
else if (character === ")") {
|
|
2010
|
+
depth -= 1;
|
|
2011
|
+
if (depth === 0)
|
|
2012
|
+
return { value: source.slice(valueStart, index), next: index + 1 };
|
|
2013
|
+
}
|
|
2014
|
+
index += 1;
|
|
2015
|
+
}
|
|
2016
|
+
return null;
|
|
2017
|
+
}
|
|
2018
|
+
function resolveCounterFunction(value, plural, counters) {
|
|
2019
|
+
const argumentsList = splitCssFunctionArguments(value);
|
|
2020
|
+
const name = argumentsList[0]?.trim();
|
|
2021
|
+
if (!name)
|
|
2022
|
+
return null;
|
|
2023
|
+
const separator = plural ? parseCssStringArgument(argumentsList[1] ?? "") : "";
|
|
2024
|
+
if (plural && separator === null)
|
|
2025
|
+
return null;
|
|
2026
|
+
const styleIndex = plural ? 2 : 1;
|
|
2027
|
+
const style = argumentsList[styleIndex]?.trim() || "decimal";
|
|
2028
|
+
const values = plural ? counters.values(name) : [counters.current(name)];
|
|
2029
|
+
const formatted = values.map((counterValue) => formatCounterValue(counterValue, style));
|
|
2030
|
+
if (formatted.some((counterValue) => counterValue === null))
|
|
2031
|
+
return null;
|
|
2032
|
+
return formatted.join(separator ?? "");
|
|
2033
|
+
}
|
|
2034
|
+
function splitCssFunctionArguments(value) {
|
|
2035
|
+
const argumentsList = [];
|
|
2036
|
+
let depth = 0;
|
|
2037
|
+
let start = 0;
|
|
2038
|
+
let index = 0;
|
|
2039
|
+
while (index < value.length) {
|
|
2040
|
+
const character = value[index];
|
|
2041
|
+
if (character === '"' || character === "'") {
|
|
2042
|
+
const parsed = consumeCssString(value, index, character);
|
|
2043
|
+
if (!parsed)
|
|
2044
|
+
return [];
|
|
2045
|
+
index = parsed.next;
|
|
2046
|
+
continue;
|
|
2047
|
+
}
|
|
2048
|
+
if (character === "(")
|
|
2049
|
+
depth += 1;
|
|
2050
|
+
else if (character === ")")
|
|
2051
|
+
depth = Math.max(depth - 1, 0);
|
|
2052
|
+
else if (character === "," && depth === 0) {
|
|
2053
|
+
argumentsList.push(value.slice(start, index));
|
|
2054
|
+
start = index + 1;
|
|
2055
|
+
}
|
|
2056
|
+
index += 1;
|
|
2057
|
+
}
|
|
2058
|
+
argumentsList.push(value.slice(start));
|
|
2059
|
+
return argumentsList;
|
|
2060
|
+
}
|
|
2061
|
+
function parseCssStringArgument(value) {
|
|
2062
|
+
const normalized = value.trim();
|
|
2063
|
+
const quote = normalized[0];
|
|
2064
|
+
if (quote !== '"' && quote !== "'")
|
|
2065
|
+
return null;
|
|
2066
|
+
const parsed = consumeCssString(normalized, 0, quote);
|
|
2067
|
+
return parsed && normalized.slice(parsed.next).trim() === "" ? parsed.value : null;
|
|
2068
|
+
}
|
|
2069
|
+
function formatCounterValue(value, style) {
|
|
2070
|
+
switch (style.toLowerCase()) {
|
|
2071
|
+
case "decimal":
|
|
2072
|
+
return String(value);
|
|
2073
|
+
case "decimal-leading-zero": {
|
|
2074
|
+
const sign = value < 0 ? "-" : "";
|
|
2075
|
+
return `${sign}${String(Math.abs(value)).padStart(2, "0")}`;
|
|
2076
|
+
}
|
|
2077
|
+
case "lower-alpha":
|
|
2078
|
+
case "lower-latin":
|
|
2079
|
+
return formatAlphabeticCounter(value, false);
|
|
2080
|
+
case "upper-alpha":
|
|
2081
|
+
case "upper-latin":
|
|
2082
|
+
return formatAlphabeticCounter(value, true);
|
|
2083
|
+
case "lower-roman":
|
|
2084
|
+
return formatRomanCounter(value, false);
|
|
2085
|
+
case "upper-roman":
|
|
2086
|
+
return formatRomanCounter(value, true);
|
|
2087
|
+
default:
|
|
2088
|
+
return null;
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
function formatAlphabeticCounter(value, uppercase) {
|
|
2092
|
+
if (value <= 0)
|
|
2093
|
+
return String(value);
|
|
2094
|
+
let output = "";
|
|
2095
|
+
let remaining = value;
|
|
2096
|
+
while (remaining > 0) {
|
|
2097
|
+
remaining -= 1;
|
|
2098
|
+
output = String.fromCharCode((uppercase ? 65 : 97) + remaining % 26) + output;
|
|
2099
|
+
remaining = Math.floor(remaining / 26);
|
|
2100
|
+
}
|
|
2101
|
+
return output;
|
|
2102
|
+
}
|
|
2103
|
+
function formatRomanCounter(value, uppercase) {
|
|
2104
|
+
if (value <= 0 || value >= 4000)
|
|
2105
|
+
return String(value);
|
|
2106
|
+
const symbols = [
|
|
2107
|
+
[1000, "M"], [900, "CM"], [500, "D"], [400, "CD"], [100, "C"], [90, "XC"], [50, "L"],
|
|
2108
|
+
[40, "XL"], [10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"],
|
|
2109
|
+
];
|
|
2110
|
+
let output = "";
|
|
2111
|
+
let remaining = value;
|
|
2112
|
+
for (const [amount, symbol] of symbols) {
|
|
2113
|
+
while (remaining >= amount) {
|
|
2114
|
+
output += symbol;
|
|
2115
|
+
remaining -= amount;
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
return uppercase ? output : output.toLowerCase();
|
|
2119
|
+
}
|
|
2120
|
+
function consumeCssString(source, start, quote) {
|
|
2121
|
+
let value = "";
|
|
2122
|
+
let index = start + 1;
|
|
2123
|
+
while (index < source.length) {
|
|
2124
|
+
const character = source[index];
|
|
2125
|
+
if (character === quote)
|
|
2126
|
+
return { value, next: index + 1 };
|
|
2127
|
+
if (character !== "\\") {
|
|
2128
|
+
value += character;
|
|
2129
|
+
index += 1;
|
|
2130
|
+
continue;
|
|
2131
|
+
}
|
|
2132
|
+
index += 1;
|
|
2133
|
+
const hex = source.slice(index).match(/^[0-9a-fA-F]{1,6}/)?.[0];
|
|
2134
|
+
if (hex) {
|
|
2135
|
+
value += String.fromCodePoint(Number.parseInt(hex, 16));
|
|
2136
|
+
index += hex.length;
|
|
2137
|
+
if (/\s/.test(source[index] ?? ""))
|
|
2138
|
+
index += 1;
|
|
2139
|
+
}
|
|
2140
|
+
else if (index < source.length) {
|
|
2141
|
+
value += source[index];
|
|
2142
|
+
index += 1;
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
return null;
|
|
2146
|
+
}
|
|
2147
|
+
function isFlowDimension(property) {
|
|
2148
|
+
return property in AUTHORED_FLOW_DIMENSION_MIRRORS;
|
|
2149
|
+
}
|
|
2150
|
+
function isAutoMargin(property) {
|
|
2151
|
+
return property in AUTHORED_AUTO_MARGIN_MIRRORS;
|
|
2152
|
+
}
|
|
2153
|
+
function shouldMaterializeFlowDimension(original, property, isSnapshotRoot, layoutContext) {
|
|
2154
|
+
if (property === "width" && isSnapshotRoot && layoutContext !== "page")
|
|
2155
|
+
return true;
|
|
2156
|
+
if (isReplacedOrControl(original))
|
|
2157
|
+
return true;
|
|
2158
|
+
return hasAuthoredProperty(original, property);
|
|
2159
|
+
}
|
|
2160
|
+
function isReplacedOrControl(original) {
|
|
2161
|
+
return isSvgElement(original) || new Set([
|
|
2162
|
+
"img", "canvas", "input", "textarea", "select", "button", "progress", "meter",
|
|
2163
|
+
]).has(original.localName);
|
|
2164
|
+
}
|
|
2165
|
+
function hasAuthoredProperty(element, property) {
|
|
2166
|
+
const inlineStyle = element.style;
|
|
2167
|
+
if (inlineStyle?.getPropertyValue(property))
|
|
2168
|
+
return true;
|
|
2169
|
+
const root = element.getRootNode();
|
|
2170
|
+
if (root.nodeType === Node.DOCUMENT_FRAGMENT_NODE && "host" in root) {
|
|
2171
|
+
const shadowRoot = root;
|
|
2172
|
+
for (const style of shadowRoot.querySelectorAll("style")) {
|
|
2173
|
+
try {
|
|
2174
|
+
if (style.sheet && rulesAuthorProperty(style.sheet.cssRules, element, property))
|
|
2175
|
+
return true;
|
|
2176
|
+
}
|
|
2177
|
+
catch {
|
|
2178
|
+
// A malformed shadow stylesheet does not invalidate the snapshot.
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
2181
|
+
for (const sheet of shadowRoot.adoptedStyleSheets ?? []) {
|
|
2182
|
+
try {
|
|
2183
|
+
if (rulesAuthorProperty(sheet.cssRules, element, property))
|
|
2184
|
+
return true;
|
|
2185
|
+
}
|
|
2186
|
+
catch {
|
|
2187
|
+
// Keep inspecting other authored sources.
|
|
2188
|
+
}
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
for (const sheet of element.ownerDocument.styleSheets) {
|
|
2192
|
+
try {
|
|
2193
|
+
if (rulesAuthorProperty(sheet.cssRules, element, property))
|
|
2194
|
+
return true;
|
|
2195
|
+
}
|
|
2196
|
+
catch {
|
|
2197
|
+
// Cross-origin stylesheets cannot expose cssRules. The computed snapshot
|
|
2198
|
+
// remains usable; only an authored fixed flow dimension may be omitted.
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
return false;
|
|
2202
|
+
}
|
|
2203
|
+
function rulesAuthorProperty(rules, element, property) {
|
|
2204
|
+
for (const rule of rules) {
|
|
2205
|
+
if ("selectorText" in rule && "style" in rule) {
|
|
2206
|
+
const styleRule = rule;
|
|
2207
|
+
try {
|
|
2208
|
+
if (styleRule.style.getPropertyValue(property) && element.matches(styleRule.selectorText))
|
|
2209
|
+
return true;
|
|
2210
|
+
}
|
|
2211
|
+
catch {
|
|
2212
|
+
// Ignore selectors that Element.matches cannot evaluate in this context.
|
|
2213
|
+
}
|
|
2214
|
+
continue;
|
|
2215
|
+
}
|
|
2216
|
+
if ("cssRules" in rule && rule.cssRules) {
|
|
2217
|
+
const nestedRules = rule.cssRules;
|
|
2218
|
+
const condition = "conditionText" in rule ? String(rule.conditionText) : "";
|
|
2219
|
+
const view = element.ownerDocument.defaultView ?? window;
|
|
2220
|
+
if (condition && !view.matchMedia(condition).matches)
|
|
2221
|
+
continue;
|
|
2222
|
+
if (rulesAuthorProperty(nestedRules, element, property))
|
|
2223
|
+
return true;
|
|
2224
|
+
}
|
|
2225
|
+
}
|
|
2226
|
+
return false;
|
|
2227
|
+
}
|
|
2228
|
+
function normalizeComputedDisplay(original, display) {
|
|
2229
|
+
switch (display) {
|
|
2230
|
+
case "flow-root":
|
|
2231
|
+
return original.localName === "button" ? "inline-block" : "block";
|
|
2232
|
+
default:
|
|
2233
|
+
return display;
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
function isFullyTransparentColor(value) {
|
|
2237
|
+
const normalized = value.replace(/\s+/g, "").toLowerCase();
|
|
2238
|
+
return normalized === "transparent" || /^rgba\([^,]+,[^,]+,[^,]+,0(?:\.0+)?\)$/.test(normalized);
|
|
2239
|
+
}
|
|
2240
|
+
function isRedundantComputedValue(element, property, value, inheritedStyle) {
|
|
2241
|
+
const normalized = value.trim();
|
|
2242
|
+
if (!normalized)
|
|
2243
|
+
return true;
|
|
2244
|
+
if (hasNativeUserAgentDefault(element, property))
|
|
2245
|
+
return false;
|
|
2246
|
+
if (inheritedStyle && INHERITED_SNAPSHOT_ELISION.has(property)) {
|
|
2247
|
+
if (normalized === inheritedStyle.getPropertyValue(property).trim())
|
|
2248
|
+
return true;
|
|
2249
|
+
}
|
|
2250
|
+
return NATIVE_INITIAL_COMPUTED_VALUES[property]?.includes(normalized) === true;
|
|
2251
|
+
}
|
|
2252
|
+
/** Keeps browser resets that override the renderer's intentional HTML defaults. */
|
|
2253
|
+
function hasNativeUserAgentDefault(element, property) {
|
|
2254
|
+
const tag = element.localName;
|
|
2255
|
+
if ((property === "margin-top" || property === "margin-bottom") && /^(?:h[1-6]|p|ul|ol)$/.test(tag))
|
|
2256
|
+
return true;
|
|
2257
|
+
if (property === "font-size" && /^h[1-6]$/.test(tag))
|
|
2258
|
+
return true;
|
|
2259
|
+
if (property === "font-weight" && tag === "strong")
|
|
2260
|
+
return true;
|
|
2261
|
+
if (property === "font-style" && tag === "em")
|
|
2262
|
+
return true;
|
|
2263
|
+
if (property === "color" && tag === "a")
|
|
2264
|
+
return true;
|
|
2265
|
+
return property === "padding-left" && (tag === "ul" || tag === "ol");
|
|
2266
|
+
}
|
|
2267
|
+
/** Preserves supported inline SVG as vector resources or applies scoped fallback. */
|
|
2268
|
+
async function materializeInlineSvgs(root, options, diagnostics) {
|
|
2269
|
+
const replacements = new Set();
|
|
2270
|
+
const svgs = [...root.querySelectorAll("svg")];
|
|
2271
|
+
if (root.nodeType === Node.ELEMENT_NODE && isSvgElement(root) && root.localName === "svg") {
|
|
2272
|
+
svgs.unshift(root);
|
|
2273
|
+
}
|
|
2274
|
+
for (const svg of svgs) {
|
|
2275
|
+
if (!svg.isConnected && !svg.parentNode && svg !== root)
|
|
2276
|
+
continue;
|
|
2277
|
+
try {
|
|
2278
|
+
if (!svg.hasAttribute("xmlns"))
|
|
2279
|
+
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
|
|
2280
|
+
const unsupportedReason = vectorSvgUnsupportedReason(svg);
|
|
2281
|
+
const source = serializeVectorSvg(svg);
|
|
2282
|
+
const replacement = svg.ownerDocument.createElement("img");
|
|
2283
|
+
for (const attribute of svg.attributes) {
|
|
2284
|
+
if (attribute.name === "style") {
|
|
2285
|
+
replacement.setAttribute("style", stripStyleProperties(attribute.value, SVG_COMPUTED_PROPERTIES));
|
|
2286
|
+
}
|
|
2287
|
+
else if (attribute.name !== "xmlns") {
|
|
2288
|
+
replacement.setAttribute(attribute.name, attribute.value);
|
|
2289
|
+
}
|
|
2290
|
+
}
|
|
2291
|
+
setSvgIntrinsicSize(svg, replacement);
|
|
2292
|
+
if (unsupportedReason === null) {
|
|
2293
|
+
replacement.src = await blobToDataUrl(new Blob([source], { type: "image/svg+xml" }));
|
|
2294
|
+
}
|
|
2295
|
+
else {
|
|
2296
|
+
if (options.fallback === "error") {
|
|
2297
|
+
throw new UnsupportedCssError(`Inline SVG requires subtree rasterization: ${unsupportedReason}`);
|
|
2298
|
+
}
|
|
2299
|
+
replacement.src = await rasterizeBlobToPng(new Blob([source], { type: "image/svg+xml" }));
|
|
2300
|
+
diagnostics.push({
|
|
2301
|
+
code: "CSS_SUBTREE_RASTERIZED",
|
|
2302
|
+
severity: "warning",
|
|
2303
|
+
message: `Inline SVG was rasterized because native vector paint does not support ${unsupportedReason}`,
|
|
2304
|
+
nodePath: snapshotNodePath(svg, root),
|
|
2305
|
+
phase: "paint",
|
|
2306
|
+
fallback: "rasterized-subtree",
|
|
2307
|
+
});
|
|
2308
|
+
}
|
|
2309
|
+
replacement.alt = svg.getAttribute("aria-label") ?? "";
|
|
2310
|
+
svg.replaceWith(replacement);
|
|
2311
|
+
replacements.add(replacement);
|
|
2312
|
+
}
|
|
2313
|
+
catch (error) {
|
|
2314
|
+
if (error instanceof UnsupportedCssError)
|
|
2315
|
+
throw error;
|
|
2316
|
+
if (options.resourcePolicy === "error")
|
|
2317
|
+
throw new ResourceLoadError("inline SVG", { cause: error });
|
|
2318
|
+
svg.remove();
|
|
2319
|
+
diagnostics.push({
|
|
2320
|
+
code: "RESOURCE_OMITTED",
|
|
2321
|
+
severity: "warning",
|
|
2322
|
+
message: "Inline SVG resource was omitted",
|
|
2323
|
+
});
|
|
2324
|
+
}
|
|
2325
|
+
}
|
|
2326
|
+
return replacements;
|
|
2327
|
+
}
|
|
2328
|
+
function serializeVectorSvg(source) {
|
|
2329
|
+
const svg = source.cloneNode(true);
|
|
2330
|
+
for (const element of [svg, ...svg.querySelectorAll("*")]) {
|
|
2331
|
+
const style = element.getAttribute("style");
|
|
2332
|
+
if (!style)
|
|
2333
|
+
continue;
|
|
2334
|
+
const declarations = style.split(";").filter((declaration) => {
|
|
2335
|
+
const colon = declaration.indexOf(":");
|
|
2336
|
+
return colon >= 0 && SVG_SERIALIZED_STYLE_PROPERTIES.has(declaration.slice(0, colon).trim().toLowerCase());
|
|
2337
|
+
});
|
|
2338
|
+
if (declarations.length > 0)
|
|
2339
|
+
element.setAttribute("style", declarations.join(";"));
|
|
2340
|
+
else
|
|
2341
|
+
element.removeAttribute("style");
|
|
2342
|
+
}
|
|
2343
|
+
return new XMLSerializer().serializeToString(svg).replace(/url\(\s*(?:"|')(#[A-Za-z_][\w:.-]*)(?:"|')\s*\)/gi, "url($1)");
|
|
2344
|
+
}
|
|
2345
|
+
function stripStyleProperties(style, properties) {
|
|
2346
|
+
const omitted = new Set(properties);
|
|
2347
|
+
return style.split(";").filter((declaration) => {
|
|
2348
|
+
const colon = declaration.indexOf(":");
|
|
2349
|
+
return colon < 0 || !omitted.has(declaration.slice(0, colon).trim().toLowerCase());
|
|
2350
|
+
}).join(";");
|
|
2351
|
+
}
|
|
2352
|
+
/** Returns the first feature that prevents SVG-native PDF emission. */
|
|
2353
|
+
function vectorSvgUnsupportedReason(svg) {
|
|
2354
|
+
const elements = [svg, ...svg.querySelectorAll("*")];
|
|
2355
|
+
for (const element of elements) {
|
|
2356
|
+
if (!isSvgElement(element) || !VECTOR_SVG_ELEMENTS.has(element.localName))
|
|
2357
|
+
return `<${element.localName}>`;
|
|
2358
|
+
if (element !== svg && element.localName === "svg")
|
|
2359
|
+
return "nested <svg> viewport";
|
|
2360
|
+
if (element.localName === "title" || element.localName === "desc")
|
|
2361
|
+
continue;
|
|
2362
|
+
if (element.localName === "linearGradient" || element.localName === "radialGradient") {
|
|
2363
|
+
if (element.hasAttribute("href") || element.hasAttribute("xlink:href"))
|
|
2364
|
+
return "gradient href inheritance";
|
|
2365
|
+
const spread = element.getAttribute("spreadMethod") ?? "pad";
|
|
2366
|
+
if (spread !== "pad")
|
|
2367
|
+
return `gradient spreadMethod=${spread}`;
|
|
2368
|
+
if (element.querySelectorAll(":scope > stop").length > 16)
|
|
2369
|
+
return "more than 16 gradient stops";
|
|
2370
|
+
}
|
|
2371
|
+
if (element.localName === "text" || element.localName === "tspan") {
|
|
2372
|
+
if (element.hasAttribute("textLength") || element.hasAttribute("lengthAdjust"))
|
|
2373
|
+
return "SVG textLength";
|
|
2374
|
+
if (element.hasAttribute("rotate"))
|
|
2375
|
+
return "per-glyph SVG rotation";
|
|
2376
|
+
for (const property of ["x", "y", "dx", "dy"]) {
|
|
2377
|
+
const value = element.getAttribute(property)?.trim() ?? "";
|
|
2378
|
+
if (value && /[\s,]/.test(value))
|
|
2379
|
+
return `SVG ${property} coordinate list`;
|
|
2380
|
+
}
|
|
2381
|
+
}
|
|
2382
|
+
const style = element.style;
|
|
2383
|
+
for (const property of VECTOR_SVG_UNSUPPORTED_PROPERTIES) {
|
|
2384
|
+
const authored = element.getAttribute(property);
|
|
2385
|
+
const computed = style.getPropertyValue(property);
|
|
2386
|
+
if ((authored && svgUnsupportedPropertyIsActive(property, authored)) || (computed && svgUnsupportedPropertyIsActive(property, computed)))
|
|
2387
|
+
return property;
|
|
2388
|
+
}
|
|
2389
|
+
const clipPath = style.getPropertyValue("clip-path") || element.getAttribute("clip-path") || "";
|
|
2390
|
+
if (clipPath && clipPath !== "none" && !isLocalSvgUrlReference(clipPath))
|
|
2391
|
+
return "external clip-path";
|
|
2392
|
+
for (const property of ["fill", "stroke"]) {
|
|
2393
|
+
const paint = style.getPropertyValue(property) || element.getAttribute(property) || "";
|
|
2394
|
+
if (/url\s*\(/i.test(paint)) {
|
|
2395
|
+
if (!isLocalSvgUrlReference(paint))
|
|
2396
|
+
return `external ${property} paint server`;
|
|
2397
|
+
if (property === "stroke")
|
|
2398
|
+
return "gradient stroke";
|
|
2399
|
+
if (element.localName === "text" || element.localName === "tspan")
|
|
2400
|
+
return "gradient SVG text";
|
|
2401
|
+
}
|
|
2402
|
+
}
|
|
2403
|
+
for (const property of ["opacity", "fill-opacity", "stroke-opacity"]) {
|
|
2404
|
+
const raw = style.getPropertyValue(property) || element.getAttribute(property) || "1";
|
|
2405
|
+
const value = Number.parseFloat(raw);
|
|
2406
|
+
if (!Number.isFinite(value) || value < 0 || value > 1)
|
|
2407
|
+
return property;
|
|
2408
|
+
if (property === "opacity" && element.localName === "g" && value < 0.9999)
|
|
2409
|
+
return "group opacity";
|
|
2410
|
+
}
|
|
2411
|
+
const transform = style.getPropertyValue("transform");
|
|
2412
|
+
if (transform.startsWith("matrix3d("))
|
|
2413
|
+
return "3D transform";
|
|
2414
|
+
const transformOrigin = style.getPropertyValue("transform-origin");
|
|
2415
|
+
if (element !== svg && transform && transform !== "none" && transformOrigin && !isZeroSvgTransformOrigin(transformOrigin))
|
|
2416
|
+
return "transform-origin";
|
|
2417
|
+
}
|
|
2418
|
+
return null;
|
|
2419
|
+
}
|
|
2420
|
+
function isLocalSvgUrlReference(raw) {
|
|
2421
|
+
return /^url\(\s*(?:["']\s*)?#[A-Za-z_][\w:.-]*(?:\s*["'])?\s*\)$/i.test(raw.trim());
|
|
2422
|
+
}
|
|
2423
|
+
function svgUnsupportedPropertyIsActive(property, raw) {
|
|
2424
|
+
const value = raw.trim().toLowerCase();
|
|
2425
|
+
if (!value || value === "none" || value === "auto")
|
|
2426
|
+
return false;
|
|
2427
|
+
if ((property === "mix-blend-mode" || property === "paint-order") && value === "normal")
|
|
2428
|
+
return false;
|
|
2429
|
+
return true;
|
|
2430
|
+
}
|
|
2431
|
+
function svgPaintIsTranslucent(raw) {
|
|
2432
|
+
const value = raw.trim().toLowerCase();
|
|
2433
|
+
if (!value || value === "none")
|
|
2434
|
+
return false;
|
|
2435
|
+
if (value === "transparent")
|
|
2436
|
+
return true;
|
|
2437
|
+
const hex = value.match(/^#(?:[0-9a-f]{4}|[0-9a-f]{8})$/i);
|
|
2438
|
+
if (hex)
|
|
2439
|
+
return value.length === 5 ? value[4] !== "f" : value.slice(7, 9) !== "ff";
|
|
2440
|
+
const commaAlpha = value.match(/^rgba\([^)]*,\s*([+-]?(?:\d+\.?\d*|\.\d+)%?)\s*\)$/);
|
|
2441
|
+
if (commaAlpha)
|
|
2442
|
+
return cssAlphaValue(commaAlpha[1]) < 0.9999;
|
|
2443
|
+
const slashAlpha = value.match(/\/\s*([+-]?(?:\d+\.?\d*|\.\d+)%?)\s*\)$/);
|
|
2444
|
+
return slashAlpha ? cssAlphaValue(slashAlpha[1]) < 0.9999 : false;
|
|
2445
|
+
}
|
|
2446
|
+
function cssAlphaValue(raw) {
|
|
2447
|
+
const value = Number.parseFloat(raw);
|
|
2448
|
+
return raw.endsWith("%") ? value / 100 : value;
|
|
2449
|
+
}
|
|
2450
|
+
function isZeroSvgTransformOrigin(raw) {
|
|
2451
|
+
const tokens = raw.trim().split(/\s+/);
|
|
2452
|
+
return tokens.length >= 2 && tokens.every((token) => /^0(?:px)?$/i.test(token));
|
|
2453
|
+
}
|
|
2454
|
+
function setSvgIntrinsicSize(svg, replacement) {
|
|
2455
|
+
const viewBox = parseSvgViewBox(svg.getAttribute("viewBox"));
|
|
2456
|
+
let width = parseSvgPixelLength(svg.getAttribute("width")) ?? parseSvgPixelLength(svg.style.width);
|
|
2457
|
+
let height = parseSvgPixelLength(svg.getAttribute("height")) ?? parseSvgPixelLength(svg.style.height);
|
|
2458
|
+
if (viewBox && width === null && height === null) {
|
|
2459
|
+
width = viewBox.width;
|
|
2460
|
+
height = viewBox.height;
|
|
2461
|
+
}
|
|
2462
|
+
else if (viewBox && width !== null && height === null && viewBox.width > 0) {
|
|
2463
|
+
height = width * viewBox.height / viewBox.width;
|
|
2464
|
+
}
|
|
2465
|
+
else if (viewBox && height !== null && width === null && viewBox.height > 0) {
|
|
2466
|
+
width = height * viewBox.width / viewBox.height;
|
|
2467
|
+
}
|
|
2468
|
+
if (width !== null && width > 0)
|
|
2469
|
+
replacement.dataset.html2realpdfIntrinsicWidth = String(width);
|
|
2470
|
+
if (height !== null && height > 0)
|
|
2471
|
+
replacement.dataset.html2realpdfIntrinsicHeight = String(height);
|
|
2472
|
+
}
|
|
2473
|
+
function parseSvgViewBox(raw) {
|
|
2474
|
+
if (!raw)
|
|
2475
|
+
return null;
|
|
2476
|
+
const values = raw.trim().split(/[\s,]+/).map(Number);
|
|
2477
|
+
if (values.length !== 4 || values.some((value) => !Number.isFinite(value)) || values[2] <= 0 || values[3] <= 0)
|
|
2478
|
+
return null;
|
|
2479
|
+
return { width: values[2], height: values[3] };
|
|
2480
|
+
}
|
|
2481
|
+
function parseSvgPixelLength(raw) {
|
|
2482
|
+
if (!raw)
|
|
2483
|
+
return null;
|
|
2484
|
+
const match = raw.trim().match(/^([+-]?(?:\d+\.?\d*|\.\d+))(?:px)?$/i);
|
|
2485
|
+
if (!match)
|
|
2486
|
+
return null;
|
|
2487
|
+
const value = Number.parseFloat(match[1]);
|
|
2488
|
+
return Number.isFinite(value) && value > 0 ? value : null;
|
|
2489
|
+
}
|
|
2490
|
+
function snapshotNodePath(element, root) {
|
|
2491
|
+
const parts = [];
|
|
2492
|
+
let current = element;
|
|
2493
|
+
while (current) {
|
|
2494
|
+
if (current.id) {
|
|
2495
|
+
parts.unshift(`#${CSS.escape(current.id)}`);
|
|
2496
|
+
break;
|
|
2497
|
+
}
|
|
2498
|
+
let part = current.localName;
|
|
2499
|
+
const classes = [...current.classList].slice(0, 2);
|
|
2500
|
+
if (classes.length > 0)
|
|
2501
|
+
part += classes.map((name) => `.${CSS.escape(name)}`).join("");
|
|
2502
|
+
if (current.parentElement) {
|
|
2503
|
+
const siblings = [...current.parentElement.children].filter((candidate) => candidate.localName === current.localName);
|
|
2504
|
+
if (siblings.length > 1)
|
|
2505
|
+
part += `:nth-of-type(${siblings.indexOf(current) + 1})`;
|
|
2506
|
+
}
|
|
2507
|
+
parts.unshift(part);
|
|
2508
|
+
if (current === root || current.parentNode === root)
|
|
2509
|
+
break;
|
|
2510
|
+
current = current.parentElement;
|
|
2511
|
+
}
|
|
2512
|
+
return parts.join(" > ");
|
|
2513
|
+
}
|
|
2514
|
+
/**
|
|
2515
|
+
* Replaces cloned canvases with PNG or adapter-provided SVG while invoking
|
|
2516
|
+
* adapters against the corresponding original live canvas.
|
|
2517
|
+
*/
|
|
2518
|
+
async function materializeCanvases(root, canvases, options, diagnostics) {
|
|
2519
|
+
let materializedRoot = root;
|
|
2520
|
+
for (const { source, target } of canvases) {
|
|
2521
|
+
const nodePath = snapshotNodePath(target, root);
|
|
2522
|
+
let replacement;
|
|
2523
|
+
if (!options.canvasToSvg) {
|
|
2524
|
+
replacement = canvasImageReplacement(target, source, canvasToPng(source));
|
|
2525
|
+
}
|
|
2526
|
+
else {
|
|
2527
|
+
let vectorSource;
|
|
2528
|
+
try {
|
|
2529
|
+
vectorSource = await options.canvasToSvg({
|
|
2530
|
+
canvas: source,
|
|
2531
|
+
nodePath,
|
|
2532
|
+
cssWidth: source.clientWidth,
|
|
2533
|
+
cssHeight: source.clientHeight,
|
|
2534
|
+
bitmapWidth: source.width,
|
|
2535
|
+
bitmapHeight: source.height,
|
|
2536
|
+
});
|
|
2537
|
+
}
|
|
2538
|
+
catch (error) {
|
|
2539
|
+
throw new CanvasToSvgError("Canvas-to-SVG callback failed", nodePath, { cause: error });
|
|
2540
|
+
}
|
|
2541
|
+
if (vectorSource === null) {
|
|
2542
|
+
if ((options.canvasFallback ?? "error") !== "rasterize") {
|
|
2543
|
+
throw new CanvasToSvgError("Canvas-to-SVG callback returned null", nodePath);
|
|
2544
|
+
}
|
|
2545
|
+
replacement = rasterizedCanvasReplacement(target, source, nodePath, "the callback returned null", diagnostics);
|
|
2546
|
+
}
|
|
2547
|
+
else {
|
|
2548
|
+
let normalized;
|
|
2549
|
+
try {
|
|
2550
|
+
normalized = await normalizeCanvasSvgSource(vectorSource);
|
|
2551
|
+
}
|
|
2552
|
+
catch (error) {
|
|
2553
|
+
throw new CanvasToSvgError("Canvas-to-SVG callback returned invalid SVG", nodePath, { cause: error });
|
|
2554
|
+
}
|
|
2555
|
+
if (normalized.unsupportedReason !== null) {
|
|
2556
|
+
if (options.fallback !== "rasterize-subtree") {
|
|
2557
|
+
throw new UnsupportedCssError(`Canvas SVG requires subtree rasterization: ${normalized.unsupportedReason} (${nodePath})`);
|
|
2558
|
+
}
|
|
2559
|
+
replacement = rasterizedCanvasReplacement(target, source, nodePath, normalized.unsupportedReason, diagnostics);
|
|
2560
|
+
}
|
|
2561
|
+
else {
|
|
2562
|
+
replacement = canvasImageReplacement(target, source, normalized.dataUrl);
|
|
2563
|
+
}
|
|
2564
|
+
}
|
|
2565
|
+
}
|
|
2566
|
+
if (target === materializedRoot)
|
|
2567
|
+
materializedRoot = replacement;
|
|
2568
|
+
else
|
|
2569
|
+
target.replaceWith(replacement);
|
|
2570
|
+
}
|
|
2571
|
+
return materializedRoot;
|
|
2572
|
+
}
|
|
2573
|
+
async function normalizeCanvasSvgSource(source) {
|
|
2574
|
+
let xml;
|
|
2575
|
+
if (typeof source === "string") {
|
|
2576
|
+
xml = source;
|
|
2577
|
+
}
|
|
2578
|
+
else if (source instanceof Blob) {
|
|
2579
|
+
if (source.type.split(";", 1)[0]?.trim().toLowerCase() !== "image/svg+xml") {
|
|
2580
|
+
throw new Error("Canvas SVG Blob must use image/svg+xml");
|
|
2581
|
+
}
|
|
2582
|
+
xml = await source.text();
|
|
2583
|
+
}
|
|
2584
|
+
else if (source instanceof Element && isSvgElement(source) && source.localName === "svg") {
|
|
2585
|
+
xml = new XMLSerializer().serializeToString(source);
|
|
2586
|
+
}
|
|
2587
|
+
else {
|
|
2588
|
+
throw new Error("Canvas SVG result must be SVG markup, an image/svg+xml Blob, or SVGSVGElement");
|
|
2589
|
+
}
|
|
2590
|
+
const parsed = new DOMParser().parseFromString(xml, "image/svg+xml");
|
|
2591
|
+
if (parsed.querySelector("parsererror") || !isSvgElement(parsed.documentElement) || parsed.documentElement.localName !== "svg") {
|
|
2592
|
+
throw new Error("Canvas SVG result is not a complete SVG document");
|
|
2593
|
+
}
|
|
2594
|
+
const svg = parsed.documentElement;
|
|
2595
|
+
if (!svg.hasAttribute("xmlns"))
|
|
2596
|
+
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
|
|
2597
|
+
const normalized = new XMLSerializer().serializeToString(svg);
|
|
2598
|
+
return {
|
|
2599
|
+
dataUrl: await blobToDataUrl(new Blob([normalized], { type: "image/svg+xml" })),
|
|
2600
|
+
unsupportedReason: vectorSvgUnsupportedReason(svg),
|
|
2601
|
+
};
|
|
2602
|
+
}
|
|
2603
|
+
function canvasImageReplacement(target, source, dataUrl) {
|
|
2604
|
+
const replacement = target.ownerDocument.createElement("img");
|
|
2605
|
+
for (const attribute of target.attributes)
|
|
2606
|
+
replacement.setAttribute(attribute.name, attribute.value);
|
|
2607
|
+
replacement.src = dataUrl;
|
|
2608
|
+
replacement.alt = target.getAttribute("aria-label") ?? "";
|
|
2609
|
+
replacement.dataset.html2realpdfIntrinsicWidth = String(Math.max(source.width, 1));
|
|
2610
|
+
replacement.dataset.html2realpdfIntrinsicHeight = String(Math.max(source.height, 1));
|
|
2611
|
+
return replacement;
|
|
2612
|
+
}
|
|
2613
|
+
function rasterizedCanvasReplacement(target, source, nodePath, reason, diagnostics) {
|
|
2614
|
+
diagnostics.push({
|
|
2615
|
+
code: "CANVAS_SUBTREE_RASTERIZED",
|
|
2616
|
+
severity: "warning",
|
|
2617
|
+
message: `Canvas was rasterized because ${reason}`,
|
|
2618
|
+
nodePath,
|
|
2619
|
+
phase: "snapshot",
|
|
2620
|
+
fallback: "rasterized-subtree",
|
|
2621
|
+
});
|
|
2622
|
+
return canvasImageReplacement(target, source, canvasToPng(source));
|
|
2623
|
+
}
|
|
2624
|
+
function materializeLiveState(original, target) {
|
|
2625
|
+
if (original.localName === "input" && target.localName === "input") {
|
|
2626
|
+
const input = original;
|
|
2627
|
+
const text = input.type === "checkbox" || input.type === "radio"
|
|
2628
|
+
? input.checked ? "☑" : "☐"
|
|
2629
|
+
: input.type === "password" ? "•".repeat(input.value.length) : input.value;
|
|
2630
|
+
return replaceFormControl(target, text);
|
|
2631
|
+
}
|
|
2632
|
+
else if (original.localName === "textarea" && target.localName === "textarea") {
|
|
2633
|
+
return replaceFormControl(target, original.value, true);
|
|
2634
|
+
}
|
|
2635
|
+
else if (original.localName === "select" && target.localName === "select") {
|
|
2636
|
+
return replaceFormControl(target, [...original.selectedOptions].map((option) => option.text).join(", "));
|
|
2637
|
+
}
|
|
2638
|
+
else if (original.localName === "button" && target.localName === "button") {
|
|
2639
|
+
return replaceFormControl(target, original.innerText);
|
|
2640
|
+
}
|
|
2641
|
+
else if (original.localName === "progress" && target.localName === "progress") {
|
|
2642
|
+
return replaceFormControl(target, `${Math.round(original.position * 100)}%`);
|
|
2643
|
+
}
|
|
2644
|
+
else if (original.localName === "meter" && target.localName === "meter") {
|
|
2645
|
+
return replaceFormControl(target, String(original.value));
|
|
2646
|
+
}
|
|
2647
|
+
else if (original.localName === "details" && target.localName === "details" && !original.open) {
|
|
2648
|
+
for (const child of [...target.children]) {
|
|
2649
|
+
if (child.localName !== "summary")
|
|
2650
|
+
child.remove();
|
|
2651
|
+
}
|
|
2652
|
+
}
|
|
2653
|
+
else if (original.localName === "img" && target.localName === "img") {
|
|
2654
|
+
const source = original;
|
|
2655
|
+
const image = target;
|
|
2656
|
+
if (source.currentSrc)
|
|
2657
|
+
image.src = source.currentSrc;
|
|
2658
|
+
if (source.naturalWidth > 0 && source.naturalHeight > 0) {
|
|
2659
|
+
image.dataset.html2realpdfIntrinsicWidth = String(source.naturalWidth);
|
|
2660
|
+
image.dataset.html2realpdfIntrinsicHeight = String(source.naturalHeight);
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
return target;
|
|
2664
|
+
}
|
|
2665
|
+
function replaceFormControl(target, text, preserveWhitespace = false) {
|
|
2666
|
+
const replacement = target.ownerDocument.createElement("span");
|
|
2667
|
+
for (const attribute of target.attributes)
|
|
2668
|
+
replacement.setAttribute(attribute.name, attribute.value);
|
|
2669
|
+
if (!replacement.style.display)
|
|
2670
|
+
replacement.style.display = "inline-block";
|
|
2671
|
+
if (preserveWhitespace)
|
|
2672
|
+
replacement.style.whiteSpace = "pre-wrap";
|
|
2673
|
+
replacement.textContent = text;
|
|
2674
|
+
target.replaceWith(replacement);
|
|
2675
|
+
return replacement;
|
|
2676
|
+
}
|
|
2677
|
+
/** Resolves image elements into self-contained JPEG, PNG, or validated SVG data. */
|
|
2678
|
+
async function materializeImages(root, options, diagnostics, alreadyMaterialized = new Set()) {
|
|
2679
|
+
const images = [...root.querySelectorAll("img")];
|
|
2680
|
+
if (root.nodeType === Node.ELEMENT_NODE && root.localName === "img")
|
|
2681
|
+
images.unshift(root);
|
|
2682
|
+
for (const image of images) {
|
|
2683
|
+
if (alreadyMaterialized.has(image))
|
|
2684
|
+
continue;
|
|
2685
|
+
const source = image.currentSrc || image.getAttribute("src") || "";
|
|
2686
|
+
if (!source)
|
|
2687
|
+
continue;
|
|
2688
|
+
if (/^data:image\/svg\+xml;/i.test(source)) {
|
|
2689
|
+
try {
|
|
2690
|
+
const response = await fetch(source);
|
|
2691
|
+
await materializeSvgImageBlob(image, await response.blob(), options, diagnostics, root);
|
|
2692
|
+
}
|
|
2693
|
+
catch (error) {
|
|
2694
|
+
if (error instanceof UnsupportedCssError)
|
|
2695
|
+
throw error;
|
|
2696
|
+
if (options.resourcePolicy === "error")
|
|
2697
|
+
throw new ResourceLoadError(source, { cause: error });
|
|
2698
|
+
image.remove();
|
|
2699
|
+
diagnostics.push({
|
|
2700
|
+
code: "RESOURCE_OMITTED",
|
|
2701
|
+
severity: "warning",
|
|
2702
|
+
message: "SVG image resource was omitted",
|
|
2703
|
+
phase: "snapshot",
|
|
2704
|
+
});
|
|
2705
|
+
}
|
|
2706
|
+
continue;
|
|
2707
|
+
}
|
|
2708
|
+
if (/^data:image\/(?:jpeg|jpg|png);/i.test(source))
|
|
2709
|
+
continue;
|
|
2710
|
+
try {
|
|
2711
|
+
const url = new URL(source, options.baseUrl ?? image.ownerDocument.baseURI);
|
|
2712
|
+
const resolved = await options.resourceResolver?.({ kind: "image", url });
|
|
2713
|
+
if (typeof resolved === "string" && /^data:image\/(?:jpeg|jpg|png);/i.test(resolved)) {
|
|
2714
|
+
image.src = resolved;
|
|
2715
|
+
continue;
|
|
2716
|
+
}
|
|
2717
|
+
const blob = resolved instanceof Blob ? resolved : await fetchImageBlob(typeof resolved === "string" ? new URL(resolved, url) : url);
|
|
2718
|
+
if (blob.type === "image/svg+xml") {
|
|
2719
|
+
await materializeSvgImageBlob(image, blob, options, diagnostics, root);
|
|
2720
|
+
continue;
|
|
2721
|
+
}
|
|
2722
|
+
image.src = blob.type === "image/jpeg" ? await blobToDataUrl(blob) : await rasterizeBlobToPng(blob);
|
|
2723
|
+
}
|
|
2724
|
+
catch (error) {
|
|
2725
|
+
if (error instanceof UnsupportedCssError)
|
|
2726
|
+
throw error;
|
|
2727
|
+
if (options.resourcePolicy === "error")
|
|
2728
|
+
throw new ResourceLoadError(source, { cause: error });
|
|
2729
|
+
image.remove();
|
|
2730
|
+
diagnostics.push({
|
|
2731
|
+
code: "RESOURCE_OMITTED",
|
|
2732
|
+
severity: "warning",
|
|
2733
|
+
message: `Image resource was omitted: ${source}`,
|
|
2734
|
+
});
|
|
2735
|
+
}
|
|
2736
|
+
}
|
|
2737
|
+
}
|
|
2738
|
+
async function materializeSvgImageBlob(image, blob, options, diagnostics, snapshotRoot) {
|
|
2739
|
+
image.src = await materializeSvgResourceBlob(blob, options, diagnostics, image, snapshotRoot, "SVG image");
|
|
2740
|
+
}
|
|
2741
|
+
async function materializeSvgResourceBlob(blob, options, diagnostics, target, snapshotRoot, label) {
|
|
2742
|
+
const source = await blob.text();
|
|
2743
|
+
const parsed = new DOMParser().parseFromString(source, "image/svg+xml");
|
|
2744
|
+
if (parsed.querySelector("parsererror") || !isSvgElement(parsed.documentElement) || parsed.documentElement.localName !== "svg") {
|
|
2745
|
+
throw new Error("Invalid SVG image resource");
|
|
2746
|
+
}
|
|
2747
|
+
const svg = parsed.documentElement;
|
|
2748
|
+
if (!svg.hasAttribute("xmlns"))
|
|
2749
|
+
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
|
|
2750
|
+
const normalized = new XMLSerializer().serializeToString(svg);
|
|
2751
|
+
const normalizedBlob = new Blob([normalized], { type: "image/svg+xml" });
|
|
2752
|
+
const unsupportedReason = vectorSvgUnsupportedReason(svg);
|
|
2753
|
+
if (unsupportedReason === null) {
|
|
2754
|
+
return blobToDataUrl(normalizedBlob);
|
|
2755
|
+
}
|
|
2756
|
+
if (options.fallback === "error") {
|
|
2757
|
+
throw new UnsupportedCssError(`${label} requires subtree rasterization: ${unsupportedReason}`);
|
|
2758
|
+
}
|
|
2759
|
+
diagnostics.push({
|
|
2760
|
+
code: "CSS_SUBTREE_RASTERIZED",
|
|
2761
|
+
severity: "warning",
|
|
2762
|
+
message: `${label} was rasterized because native vector paint does not support ${unsupportedReason}`,
|
|
2763
|
+
nodePath: snapshotNodePath(target, snapshotRoot),
|
|
2764
|
+
phase: "paint",
|
|
2765
|
+
fallback: "rasterized-subtree",
|
|
2766
|
+
});
|
|
2767
|
+
return rasterizeBlobToPng(normalizedBlob);
|
|
2768
|
+
}
|
|
2769
|
+
/** Resolves each authored background URL without disturbing native gradients. */
|
|
2770
|
+
async function materializeBackgroundImages(root, options, diagnostics) {
|
|
2771
|
+
const elements = [...root.querySelectorAll("[style]")];
|
|
2772
|
+
if (root.nodeType === Node.ELEMENT_NODE && root.hasAttribute("style"))
|
|
2773
|
+
elements.unshift(root);
|
|
2774
|
+
for (const element of elements) {
|
|
2775
|
+
const backgroundImage = element.style.getPropertyValue("background-image");
|
|
2776
|
+
if (!backgroundImage || backgroundImage === "none")
|
|
2777
|
+
continue;
|
|
2778
|
+
let materialized = backgroundImage;
|
|
2779
|
+
const matches = [...backgroundImage.matchAll(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*?))\s*\)/gi)];
|
|
2780
|
+
for (const match of matches) {
|
|
2781
|
+
const source = (match[1] ?? match[2] ?? match[3] ?? "").trim();
|
|
2782
|
+
if (!source || /^data:image\/(?:jpeg|jpg|png);/i.test(source))
|
|
2783
|
+
continue;
|
|
2784
|
+
try {
|
|
2785
|
+
const url = new URL(source, options.baseUrl ?? element.ownerDocument.baseURI);
|
|
2786
|
+
const resolved = await options.resourceResolver?.({ kind: "image", url });
|
|
2787
|
+
let dataUrl;
|
|
2788
|
+
if (typeof resolved === "string" && /^data:image\/(?:jpeg|jpg|png);/i.test(resolved)) {
|
|
2789
|
+
dataUrl = resolved;
|
|
2790
|
+
}
|
|
2791
|
+
else {
|
|
2792
|
+
const blob = resolved instanceof Blob ? resolved : await fetchImageBlob(typeof resolved === "string" ? new URL(resolved, url) : url);
|
|
2793
|
+
dataUrl = blob.type === "image/svg+xml"
|
|
2794
|
+
? await materializeSvgResourceBlob(blob, options, diagnostics, element, root, "Background SVG")
|
|
2795
|
+
: blob.type === "image/jpeg" ? await blobToDataUrl(blob) : await rasterizeBlobToPng(blob);
|
|
2796
|
+
}
|
|
2797
|
+
materialized = materialized.replace(match[0], `url("${dataUrl}")`);
|
|
2798
|
+
}
|
|
2799
|
+
catch (error) {
|
|
2800
|
+
if (error instanceof UnsupportedCssError)
|
|
2801
|
+
throw error;
|
|
2802
|
+
if (options.resourcePolicy === "error")
|
|
2803
|
+
throw new ResourceLoadError(source, { cause: error });
|
|
2804
|
+
materialized = materialized.replace(match[0], "none");
|
|
2805
|
+
diagnostics.push({
|
|
2806
|
+
code: "RESOURCE_OMITTED",
|
|
2807
|
+
severity: "warning",
|
|
2808
|
+
message: `Background image resource was omitted: ${source}`,
|
|
2809
|
+
phase: "snapshot",
|
|
2810
|
+
});
|
|
2811
|
+
}
|
|
2812
|
+
}
|
|
2813
|
+
element.style.setProperty("background-image", materialized);
|
|
2814
|
+
}
|
|
2815
|
+
}
|
|
2816
|
+
async function fetchImageBlob(url) {
|
|
2817
|
+
const response = await fetch(url, { mode: "cors" });
|
|
2818
|
+
if (!response.ok)
|
|
2819
|
+
throw new Error(`HTTP ${response.status}`);
|
|
2820
|
+
return response.blob();
|
|
2821
|
+
}
|
|
2822
|
+
/** Applies the selected unsupported-CSS policy to authored declarations. */
|
|
2823
|
+
function inspectAuthoredCss(root, options, diagnostics) {
|
|
2824
|
+
const elements = [...root.querySelectorAll("[style],style")];
|
|
2825
|
+
if (root instanceof Element && (root.hasAttribute("style") || root.localName === "style"))
|
|
2826
|
+
elements.unshift(root);
|
|
2827
|
+
for (const element of elements) {
|
|
2828
|
+
const css = element.localName === "style" ? stripPageRuleBlocks(element.textContent ?? "") : element.getAttribute("style") ?? "";
|
|
2829
|
+
for (const match of css.matchAll(/(?:^|[;{])\s*([\w-]+)\s*:\s*([^;}]+)/g)) {
|
|
2830
|
+
const property = match[1]?.toLowerCase();
|
|
2831
|
+
const value = (match[2]?.trim().toLowerCase() ?? "").replace(/\s*!important\s*$/, "");
|
|
2832
|
+
if (!property || property.startsWith("--"))
|
|
2833
|
+
continue;
|
|
2834
|
+
// WebKit may serialize the supported `font` shorthand as these no-op
|
|
2835
|
+
// longhands when HTML is moved into the isolated print environment.
|
|
2836
|
+
if (NO_OP_SERIALIZED_FONT_LONGHANDS[property]?.includes(value))
|
|
2837
|
+
continue;
|
|
2838
|
+
validateAuthoredLayout(property, value, options);
|
|
2839
|
+
if (property === "background" && !usesWebLayout(options) && /(?:url|(?:repeating-)?(?:linear|radial|conic)-gradient)\s*\(/.test(value)) {
|
|
2840
|
+
reportUnsupportedCss("background-image", options, diagnostics);
|
|
2841
|
+
}
|
|
2842
|
+
if (SUPPORTED_CSS_PROPERTIES.has(property))
|
|
2843
|
+
continue;
|
|
2844
|
+
reportUnsupportedCss(property, options, diagnostics);
|
|
2845
|
+
}
|
|
2846
|
+
}
|
|
2847
|
+
}
|
|
2848
|
+
function stripPageRuleBlocks(css) {
|
|
2849
|
+
const lower = css.toLowerCase();
|
|
2850
|
+
let output = "";
|
|
2851
|
+
let cursor = 0;
|
|
2852
|
+
while (cursor < css.length) {
|
|
2853
|
+
const start = lower.indexOf("@page", cursor);
|
|
2854
|
+
if (start < 0)
|
|
2855
|
+
return output + css.slice(cursor);
|
|
2856
|
+
const boundary = lower[start + 5];
|
|
2857
|
+
if (boundary && /[\w-]/.test(boundary)) {
|
|
2858
|
+
output += css.slice(cursor, start + 5);
|
|
2859
|
+
cursor = start + 5;
|
|
2860
|
+
continue;
|
|
2861
|
+
}
|
|
2862
|
+
const open = css.indexOf("{", start + 5);
|
|
2863
|
+
if (open < 0)
|
|
2864
|
+
return output + css.slice(cursor, start);
|
|
2865
|
+
output += css.slice(cursor, start);
|
|
2866
|
+
let depth = 1;
|
|
2867
|
+
let quote = "";
|
|
2868
|
+
let index = open + 1;
|
|
2869
|
+
while (index < css.length && depth > 0) {
|
|
2870
|
+
const character = css[index];
|
|
2871
|
+
if (quote) {
|
|
2872
|
+
if (character === "\\")
|
|
2873
|
+
index += 1;
|
|
2874
|
+
else if (character === quote)
|
|
2875
|
+
quote = "";
|
|
2876
|
+
}
|
|
2877
|
+
else if (character === '"' || character === "'") {
|
|
2878
|
+
quote = character;
|
|
2879
|
+
}
|
|
2880
|
+
else if (character === "/" && css[index + 1] === "*") {
|
|
2881
|
+
const commentEnd = css.indexOf("*/", index + 2);
|
|
2882
|
+
index = commentEnd < 0 ? css.length : commentEnd + 1;
|
|
2883
|
+
}
|
|
2884
|
+
else if (character === "{") {
|
|
2885
|
+
depth += 1;
|
|
2886
|
+
}
|
|
2887
|
+
else if (character === "}") {
|
|
2888
|
+
depth -= 1;
|
|
2889
|
+
}
|
|
2890
|
+
index += 1;
|
|
2891
|
+
}
|
|
2892
|
+
cursor = index;
|
|
2893
|
+
}
|
|
2894
|
+
return output;
|
|
2895
|
+
}
|
|
2896
|
+
function validateAuthoredLayout(property, value, options) {
|
|
2897
|
+
if (property === "display" && (!SUPPORTED_DISPLAY.has(value) || (["flex", "inline-flex", "grid", "inline-grid"].includes(value) && !usesWebLayout(options)))) {
|
|
2898
|
+
throw new UnsupportedCssError(`display:${value} is outside the document/report layout profile`);
|
|
2899
|
+
}
|
|
2900
|
+
if (property === "position" && value !== "static" && !usesWebLayout(options)) {
|
|
2901
|
+
throw new UnsupportedCssError(`position:${value} is outside the document/report layout profile`);
|
|
2902
|
+
}
|
|
2903
|
+
if (property === "float" && value !== "none" && !usesWebLayout(options)) {
|
|
2904
|
+
throw new UnsupportedCssError(`float:${value} is outside the document/report layout profile`);
|
|
2905
|
+
}
|
|
2906
|
+
}
|
|
2907
|
+
function usesWebLayout(options) {
|
|
2908
|
+
return options.cssProfile === "web" || options.cssProfile === "strict";
|
|
2909
|
+
}
|
|
2910
|
+
function reportUnsupportedCss(property, options, diagnostics) {
|
|
2911
|
+
const policy = options.unsupportedCss ?? (options.strict || options.cssProfile === "strict" ? "error" : "warn");
|
|
2912
|
+
if (policy === "error")
|
|
2913
|
+
throw new UnsupportedCssError(`${property} is outside the ${options.cssProfile ?? "document"} CSS profile`);
|
|
2914
|
+
if (policy === "ignore")
|
|
2915
|
+
return;
|
|
2916
|
+
if (diagnostics.some((diagnostic) => diagnostic.code === "UNSUPPORTED_CSS_PROPERTY" && diagnostic.message.includes(property)))
|
|
2917
|
+
return;
|
|
2918
|
+
diagnostics.push({
|
|
2919
|
+
code: "UNSUPPORTED_CSS_PROPERTY",
|
|
2920
|
+
severity: "warning",
|
|
2921
|
+
message: `Unsupported CSS property was omitted: ${property}`,
|
|
2922
|
+
property,
|
|
2923
|
+
phase: "snapshot",
|
|
2924
|
+
});
|
|
2925
|
+
}
|
|
2926
|
+
function canvasToPng(source) {
|
|
2927
|
+
const canvas = document.createElement("canvas");
|
|
2928
|
+
canvas.width = Math.max(source.width, 1);
|
|
2929
|
+
canvas.height = Math.max(source.height, 1);
|
|
2930
|
+
const context = canvas.getContext("2d");
|
|
2931
|
+
if (!context)
|
|
2932
|
+
throw new ResourceLoadError("canvas");
|
|
2933
|
+
context.drawImage(source, 0, 0);
|
|
2934
|
+
return canvas.toDataURL("image/png");
|
|
2935
|
+
}
|
|
2936
|
+
async function rasterizeBlobToPng(blob) {
|
|
2937
|
+
const objectUrl = URL.createObjectURL(blob);
|
|
2938
|
+
try {
|
|
2939
|
+
const image = new Image();
|
|
2940
|
+
image.src = objectUrl;
|
|
2941
|
+
await image.decode();
|
|
2942
|
+
const canvas = document.createElement("canvas");
|
|
2943
|
+
canvas.width = Math.max(image.naturalWidth, 1);
|
|
2944
|
+
canvas.height = Math.max(image.naturalHeight, 1);
|
|
2945
|
+
const context = canvas.getContext("2d");
|
|
2946
|
+
if (!context)
|
|
2947
|
+
throw new Error("Canvas 2D context is unavailable");
|
|
2948
|
+
context.drawImage(image, 0, 0);
|
|
2949
|
+
return canvas.toDataURL("image/png");
|
|
2950
|
+
}
|
|
2951
|
+
finally {
|
|
2952
|
+
URL.revokeObjectURL(objectUrl);
|
|
2953
|
+
}
|
|
2954
|
+
}
|
|
2955
|
+
function blobToDataUrl(blob) {
|
|
2956
|
+
return new Promise((resolve, reject) => {
|
|
2957
|
+
const reader = new FileReader();
|
|
2958
|
+
reader.addEventListener("load", () => resolve(String(reader.result)), { once: true });
|
|
2959
|
+
reader.addEventListener("error", () => reject(reader.error), { once: true });
|
|
2960
|
+
reader.readAsDataURL(blob);
|
|
2961
|
+
});
|
|
2962
|
+
}
|
|
2963
|
+
function removeEventHandlers(element) {
|
|
2964
|
+
for (const attribute of [...element.attributes]) {
|
|
2965
|
+
if (attribute.name.toLowerCase().startsWith("on"))
|
|
2966
|
+
element.removeAttribute(attribute.name);
|
|
2967
|
+
}
|
|
2968
|
+
}
|
|
2969
|
+
function isSvgElement(element) {
|
|
2970
|
+
return element.namespaceURI === "http://www.w3.org/2000/svg";
|
|
2971
|
+
}
|
|
2972
|
+
//# sourceMappingURL=snapshot.js.map
|