uiport 0.0.0-bootstrap.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,307 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { chromium } from "playwright-core";
4
+ import { parseFragment, serialize } from "parse5";
5
+ import parseSrcset from "parse-srcset";
6
+ import { extractSection } from "./dom.mjs";
7
+ import { resources } from "./resources.mjs";
8
+ import { browserResources } from "./browser-resources.mjs";
9
+ import { contextualCss } from "./css-context.mjs";
10
+ import {
11
+ inspectOutput,
12
+ stageOutput,
13
+ escapeHtml,
14
+ jsonForInlineScript,
15
+ launchChromium,
16
+ limitation,
17
+ lifecycle,
18
+ log,
19
+ redactedUrl,
20
+ scrollForLazyContent,
21
+ serializeAttributes,
22
+ waitForPageStable,
23
+ } from "./lib.mjs";
24
+
25
+ export async function capture(options) {
26
+ const { sourceUrl, selector, viewports, settleMs, locale, colorScheme } =
27
+ options;
28
+ await inspectOutput(options.directory);
29
+ const life = lifecycle(options.timeoutMs);
30
+ const limitations = [];
31
+ const captures = [];
32
+ let stage;
33
+ try {
34
+ const { browser, selected, close } = await launchChromium(chromium, life);
35
+ life.check();
36
+ const context = await browser.newContext({
37
+ viewport: viewports[0],
38
+ deviceScaleFactor: 1,
39
+ locale,
40
+ colorScheme,
41
+ serviceWorkers: "block",
42
+ });
43
+ const page = await context.newPage();
44
+ const cache = browserResources(page, options, life.signal);
45
+ life.add(async () => cache.dispose());
46
+ stage = await stageOutput(options.directory);
47
+ await fs.mkdir(path.join(stage.directory, "assets"));
48
+ const assets = resources(
49
+ stage.directory,
50
+ options,
51
+ life.signal,
52
+ limitations,
53
+ cache,
54
+ );
55
+ let cssContext;
56
+ page.setDefaultTimeout(Math.min(10000, options.timeoutMs));
57
+ page.on("pageerror", () =>
58
+ limitation(
59
+ limitations,
60
+ "SOURCE_SCRIPT_ERROR",
61
+ "The source page raised a JavaScript error",
62
+ ),
63
+ );
64
+ // Keep diagnostics bounded and omit URL queries, page content and form values.
65
+ page.on("requestfailed", () =>
66
+ limitation(
67
+ limitations,
68
+ "SOURCE_REQUEST_FAILED",
69
+ "At least one source request failed",
70
+ ),
71
+ );
72
+ for (const viewport of viewports) {
73
+ life.check();
74
+ log(`Capturing ${viewport.name}…`);
75
+ await page.setViewportSize(viewport);
76
+ await page.goto(sourceUrl, {
77
+ waitUntil: "domcontentloaded",
78
+ timeout: Math.min(60000, options.timeoutMs),
79
+ });
80
+ await waitForPageStable(page, settleMs);
81
+ if (await scrollForLazyContent(page, options.maxScrollSteps))
82
+ limitation(
83
+ limitations,
84
+ "SCROLL_LIMIT",
85
+ "Lazy-loading scroll reached its configured limit",
86
+ );
87
+ await waitForPageStable(page, settleMs);
88
+ const root = page.locator(selector);
89
+ const count = await root.count();
90
+ if (count !== 1)
91
+ throw new Error(
92
+ `Selector must resolve to exactly one element; found ${count}`,
93
+ );
94
+ await root.scrollIntoViewIfNeeded();
95
+ const snapshot = await page.evaluate(extractSection, {
96
+ selector,
97
+ omitScripts: options.omitScripts,
98
+ });
99
+ captures.push(snapshot);
100
+ await cache.settle();
101
+ if (!cssContext) {
102
+ const cssParts = [];
103
+ for (const sheet of snapshot.stylesheets.filter((s) => !s.disabled)) {
104
+ life.check();
105
+ const resource =
106
+ sheet.text === null && sheet.href
107
+ ? await assets.download(sheet.href)
108
+ : null;
109
+ const text = sheet.text ?? resource?.body.toString("utf8");
110
+ if (text == null) {
111
+ limitation(
112
+ limitations,
113
+ "STYLESHEET_UNAVAILABLE",
114
+ "An original stylesheet could not be read",
115
+ );
116
+ continue;
117
+ }
118
+ const css = await assets.css(text, resource?.url || sheet.baseUrl);
119
+ cssParts.push(
120
+ sheet.media ? `@media ${sheet.media} {\n${css}\n}` : css,
121
+ );
122
+ }
123
+ cssContext = contextualCss(cssParts);
124
+ }
125
+ await cssContext.observe(page, snapshot);
126
+ }
127
+ await cache.settle();
128
+ await close();
129
+ life.check();
130
+ const primary = captures[0];
131
+ if (captures.some((c) => c.structure !== primary.structure))
132
+ limitation(
133
+ limitations,
134
+ "RESPONSIVE_DOM_CHANGED",
135
+ "The element structure changes across viewports; output uses the first DOM",
136
+ );
137
+ if (captures.some((c) => c.sourceScripts || c.removedExecutable))
138
+ limitation(
139
+ limitations,
140
+ options.omitScripts
141
+ ? "SOURCE_RUNTIME_OMITTED"
142
+ : "SOURCE_RUNTIME_UNVERIFIED",
143
+ options.omitScripts
144
+ ? "Source scripts and executable attributes are omitted by request"
145
+ : "Source scripts and inline handlers are retained where captured; external initialization and runtime dependencies still require manual validation",
146
+ );
147
+ if (captures.some((c) => c.featureCounts.canvas))
148
+ limitation(
149
+ limitations,
150
+ "CANVAS_STATIC",
151
+ "Canvas is captured only as an observed static frame when readable",
152
+ );
153
+ if (captures.some((c) => c.canvasFailures))
154
+ limitation(
155
+ limitations,
156
+ "CANVAS_UNREADABLE",
157
+ "At least one canvas frame could not be read",
158
+ );
159
+ if (captures.some((c) => c.featureCounts.iframe))
160
+ limitation(
161
+ limitations,
162
+ "EMBED_OMITTED",
163
+ "Embedded documents are disabled in the output",
164
+ );
165
+ const parts = cssContext.render();
166
+ const ancestorOpen = primary.ancestors
167
+ .map((a) => `<${a.tag}${serializeAttributes(a.attributes)}>`)
168
+ .join("\n");
169
+ const ancestorClose = [...primary.ancestors]
170
+ .reverse()
171
+ .map((a) => `</${a.tag}>`)
172
+ .join("\n");
173
+ const fragment = parseFragment(ancestorOpen + primary.html + ancestorClose);
174
+ const runtimeHtml = primary.runtimeScripts
175
+ .map((script) => {
176
+ const attrs = [
177
+ { name: "src", value: script.src },
178
+ ...(script.type ? [{ name: "type", value: script.type }] : []),
179
+ ...(script.async ? [{ name: "async", value: "" }] : []),
180
+ ...(script.defer ? [{ name: "defer", value: "" }] : []),
181
+ ...(script.noModule ? [{ name: "nomodule", value: "" }] : []),
182
+ ];
183
+ return `<script${serializeAttributes(attrs)}></script>`;
184
+ })
185
+ .join("\n");
186
+ const head = parseFragment(runtimeHtml + primary.headHtml);
187
+ async function rewrite(node) {
188
+ if (node.attrs) {
189
+ for (const attr of node.attrs) {
190
+ if (
191
+ ["src", "poster", "data-src", "data-background-image"].includes(
192
+ attr.name,
193
+ ) ||
194
+ (["use", "image"].includes(node.tagName) &&
195
+ ["href", "xlink:href"].includes(attr.name))
196
+ )
197
+ attr.value = await assets.localize(
198
+ attr.value,
199
+ primary.baseUrl,
200
+ node.tagName === "script" && attr.name === "src"
201
+ ? "script"
202
+ : undefined,
203
+ );
204
+ if (attr.name === "srcset") {
205
+ const candidates = [];
206
+ for (const item of parseSrcset(attr.value))
207
+ candidates.push(
208
+ `${await assets.localize(item.url, primary.baseUrl)}${item.w ? ` ${item.w}w` : item.d ? ` ${item.d}x` : ""}`,
209
+ );
210
+ attr.value = candidates.join(", ");
211
+ }
212
+ if (attr.name === "style")
213
+ attr.value = await assets.cssValue(attr.value, primary.baseUrl);
214
+ }
215
+ }
216
+ if (node.tagName === "style")
217
+ for (const child of node.childNodes || [])
218
+ if (child.nodeName === "#text")
219
+ child.value = await assets.css(child.value, primary.baseUrl);
220
+ for (const child of node.childNodes || []) await rewrite(child);
221
+ if (node.content) await rewrite(node.content);
222
+ }
223
+ await rewrite(fragment);
224
+ await rewrite(head);
225
+ await rewrite({ attrs: primary.htmlAttributes });
226
+ await rewrite({ attrs: primary.bodyAttributes });
227
+ // Context-dependent custom properties retain their original conditions;
228
+ // ordinary inherited/responsive variables are never frozen to one viewport.
229
+ const animations = primary.animations.filter(
230
+ (a) =>
231
+ a.kind === "Animation" &&
232
+ a.targetId &&
233
+ a.keyframes?.length &&
234
+ (!a.timeline || a.timeline === "DocumentTimeline"),
235
+ );
236
+ if (
237
+ primary.animations.some(
238
+ (a) => a.kind === "Animation" && !animations.includes(a),
239
+ )
240
+ )
241
+ limitation(
242
+ limitations,
243
+ "ANIMATION_UNSUPPORTED",
244
+ "Some observed animations cannot be replayed on DocumentTimeline",
245
+ );
246
+ const metadata = {
247
+ limitations,
248
+ behavior: "not-tested",
249
+ source: redactedUrl(sourceUrl),
250
+ };
251
+ const html = `<!doctype html>
252
+ <html lang="${escapeHtml(locale)}"${serializeAttributes(primary.htmlAttributes)}>
253
+ <head>
254
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
255
+ <title>${escapeHtml(primary.title || "UIport — extracted section")}</title>
256
+ <style>${parts.join("\n").replaceAll("</style", "<\\/style")}</style>
257
+ ${serialize(head)}
258
+ </head>
259
+ <body${serializeAttributes(primary.bodyAttributes)}>
260
+ ${serialize(fragment)}
261
+ <script type="application/json" id="uiport-metadata">${jsonForInlineScript(metadata)}</script>
262
+ <script type="application/json" id="uiport-animations">${jsonForInlineScript(animations)}</script>
263
+ <script>
264
+ (() => {
265
+ const find = (id, root = document) => {
266
+ const direct = root.querySelector('[data-uiport-id="' + CSS.escape(id) + '"]');
267
+ if (direct) return direct;
268
+ for (const element of root.querySelectorAll('*')) if (element.shadowRoot) { const found = find(id, element.shadowRoot); if (found) return found; }
269
+ return null;
270
+ };
271
+ for (const record of JSON.parse(document.getElementById('uiport-animations').textContent)) {
272
+ const target = find(record.targetId);
273
+ if (!target) continue;
274
+ try {
275
+ const timing = { ...record.timing, iterations: record.timing.iterations === 'Infinity' ? Infinity : record.timing.iterations };
276
+ if (record.pseudoElement) timing.pseudoElement = record.pseudoElement;
277
+ const animation = new Animation(new KeyframeEffect(target, record.keyframes, timing), document.timeline);
278
+ animation.playbackRate = record.playbackRate ?? 1;
279
+ animation.play();
280
+ if (record.currentTime != null) animation.currentTime = record.currentTime;
281
+ if (record.playState === 'paused') animation.pause();
282
+ } catch (error) { console.error('UIport animation replay failed:', error.message); }
283
+ }
284
+ document.addEventListener('submit', event => event.preventDefault(), true);
285
+ })();
286
+ </script>
287
+ </body></html>`;
288
+ life.check();
289
+ await fs.writeFile(path.join(stage.directory, "index.html"), html);
290
+ life.check();
291
+ await stage.commit();
292
+ return {
293
+ command: "capture",
294
+ status: limitations.length ? "partial" : "complete",
295
+ outputDirectory: options.directory,
296
+ browser: { selected, version: browser.version() },
297
+ ...assets.stats(),
298
+ elements: primary.featureCounts.elements,
299
+ animationsReplayed: animations.length,
300
+ behavior: "not-tested",
301
+ limitations,
302
+ };
303
+ } finally {
304
+ await life.close();
305
+ await stage?.cleanup();
306
+ }
307
+ }
@@ -0,0 +1,174 @@
1
+ import postcss from "postcss";
2
+ import { randomUUID } from "node:crypto";
3
+
4
+ // Inspect only selector context. No stylesheet or script is executed in this
5
+ // detached document. Keep original declarations, specificity and enclosing
6
+ // media/supports/container/layer rules rather than freezing computed values.
7
+ function missingSelectors({ snapshot, rules }) {
8
+ const copy = document.implementation.createHTMLDocument("");
9
+ for (const { name, value } of snapshot.htmlAttributes)
10
+ copy.documentElement.setAttribute(name, value);
11
+ for (const { name, value } of snapshot.bodyAttributes)
12
+ copy.body.setAttribute(name, value);
13
+ let container = copy.body;
14
+ for (const ancestor of snapshot.ancestors) {
15
+ const el = copy.createElement(ancestor.tag);
16
+ for (const { name, value } of ancestor.attributes)
17
+ el.setAttribute(name, value);
18
+ container.append(el);
19
+ container = el;
20
+ }
21
+ container.innerHTML = snapshot.html;
22
+ const clones = new Map(
23
+ [...copy.querySelectorAll("[data-uiport-id]")].map((element) => [
24
+ element.getAttribute("data-uiport-id"),
25
+ element,
26
+ ]),
27
+ );
28
+ const result = [];
29
+ for (const rule of rules) {
30
+ for (const selector of rule.selectors) {
31
+ try {
32
+ for (const element of document.querySelectorAll(selector)) {
33
+ const id = element.getAttribute("data-uiport-id");
34
+ const cloned = clones.get(id);
35
+ if (cloned && !cloned.matches(selector))
36
+ result.push({ rule: rule.id, selector, id });
37
+ }
38
+ } catch {
39
+ // Browser-specific selectors may not be queryable.
40
+ }
41
+ }
42
+ }
43
+ return result;
44
+ }
45
+
46
+ // CSS nesting uses the maximum specificity of the parent's selector list.
47
+ // Expand nesting tokens only outside strings/attributes and preserve escapes.
48
+ function resolveSelector(selector, parent) {
49
+ let result = "",
50
+ quote = "",
51
+ brackets = 0,
52
+ nested = false;
53
+ for (let i = 0; i < selector.length; i++) {
54
+ const char = selector[i];
55
+ if (char === "\\") {
56
+ result += char + (selector[++i] || "");
57
+ continue;
58
+ }
59
+ if (quote) {
60
+ if (char === quote) quote = "";
61
+ } else if (char === '"' || char === "'") quote = char;
62
+ else if (char === "[") brackets++;
63
+ else if (char === "]") brackets--;
64
+ else if (char === "&" && brackets === 0) {
65
+ result += parent;
66
+ nested = true;
67
+ continue;
68
+ }
69
+ result += char;
70
+ }
71
+ return nested ? result : `${parent} ${result}`;
72
+ }
73
+ function selectorsFor(rule) {
74
+ let parent = rule.parent;
75
+ while (parent && parent.type !== "rule") parent = parent.parent;
76
+ if (!parent) return rule.selectors;
77
+ const context = `:is(${selectorsFor(parent).join(", ")})`;
78
+ return rule.selectors.map((selector) => resolveSelector(selector, context));
79
+ }
80
+
81
+ export function contextualCss(stylesheets) {
82
+ const roots = stylesheets.map((text) => postcss.parse(text));
83
+ const rules = [];
84
+ const descriptors = [];
85
+ function visit(container, owner) {
86
+ if (container.type === "rule") owner = container;
87
+ let declarations = [];
88
+ const flush = () => {
89
+ if (owner && declarations.length) {
90
+ const id = rules.length;
91
+ rules.push({ container, declarations });
92
+ descriptors.push({ id, selectors: selectorsFor(owner) });
93
+ }
94
+ declarations = [];
95
+ };
96
+ // Preserve declaration order around nested rules. A conditional at-rule
97
+ // may contain declarations applying implicitly to its enclosing selector.
98
+ for (const node of container.nodes || []) {
99
+ if (node.type === "decl" && node.prop.startsWith("--"))
100
+ declarations.push(node);
101
+ else if (node.nodes) {
102
+ flush();
103
+ visit(node, owner);
104
+ }
105
+ }
106
+ flush();
107
+ }
108
+ for (const root of roots) visit(root, null);
109
+ const missing = new Map();
110
+ return {
111
+ async observe(page, snapshot) {
112
+ const result = await page.evaluate(missingSelectors, {
113
+ snapshot,
114
+ rules: descriptors,
115
+ });
116
+ for (const item of result)
117
+ missing.set(`${item.rule}|${item.selector}|${item.id}`, item);
118
+ },
119
+ render() {
120
+ const anchorFor = (container) => {
121
+ let anchor = container;
122
+ for (let parent = container.parent; parent; parent = parent.parent)
123
+ if (parent.type === "rule") anchor = parent;
124
+ return anchor;
125
+ };
126
+ const affected = new Set(
127
+ [...missing.values()].map((item) =>
128
+ anchorFor(rules[item.rule].container),
129
+ ),
130
+ );
131
+ const tails = new Map();
132
+ // Replay every custom declaration of an affected style block, including
133
+ // selectors that still match. Otherwise hoisting only a missing selector
134
+ // would incorrectly override a later nested rule of equal specificity.
135
+ for (const [
136
+ id,
137
+ { container: original, declarations },
138
+ ] of rules.entries()) {
139
+ const anchor = anchorFor(original);
140
+ if (!affected.has(anchor)) continue;
141
+ const selectors = descriptors[id].selectors.map((selector) => {
142
+ const elements = [...missing.values()].filter(
143
+ (item) => item.rule === id && item.selector === selector,
144
+ );
145
+ return elements.length
146
+ ? `:is(${selector}, :where(${elements.map((item) => `[data-uiport-id="${item.id}"]`).join(", ")}))`
147
+ : selector;
148
+ });
149
+ let fallback = postcss.rule({ selector: selectors.join(", ") });
150
+ for (const node of declarations) fallback.append(node.clone());
151
+ // Keep conditional/group rules while removing style ancestors already
152
+ // represented in the resolved selectors.
153
+ for (
154
+ let parent = original.type === "atrule" ? original : original.parent;
155
+ parent && parent !== anchor.parent;
156
+ parent = parent.parent
157
+ )
158
+ if (parent.type === "atrule") {
159
+ // Reopening an anonymous layer would create a different, later
160
+ // layer. Give this original layer a shared private identity first.
161
+ if (parent.name.toLowerCase() === "layer" && !parent.params.trim())
162
+ parent.params = `uiport-context-${randomUUID()}`;
163
+ const wrapper = parent.clone({ nodes: [] });
164
+ wrapper.append(fallback);
165
+ fallback = wrapper;
166
+ }
167
+ const tail = tails.get(anchor) || anchor;
168
+ tail.after(fallback);
169
+ tails.set(anchor, fallback);
170
+ }
171
+ return roots.map((root) => root.toString());
172
+ },
173
+ };
174
+ }