uiport 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +41 -0
- package/README.md +10 -7
- package/README.pt-BR.md +10 -7
- package/SECURITY.md +1 -1
- package/bin/cli.mjs +34 -8
- package/docs/architecture.md +1 -1
- package/docs/support.md +17 -3
- package/package.json +1 -1
- package/scripts/capture.mjs +171 -36
- package/scripts/contract.mjs +14 -0
- package/scripts/css-context.mjs +18 -10
- package/scripts/diff.mjs +149 -0
- package/scripts/dom.mjs +59 -94
- package/scripts/errors.mjs +53 -0
- package/scripts/examples.mjs +37 -0
- package/scripts/inspect.mjs +50 -0
- package/scripts/lib.mjs +20 -19
- package/scripts/options.mjs +52 -12
- package/scripts/report.mjs +119 -0
- package/scripts/resources.mjs +130 -70
- package/scripts/srcset.mjs +14 -0
- package/scripts/stdout.mjs +13 -0
- package/scripts/validate.mjs +73 -41
- package/skills/uiport/SKILL.md +39 -8
- package/uiport.md +13 -4
package/scripts/css-context.mjs
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import postcss from "postcss";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { ID_ATTR } from "./contract.mjs";
|
|
3
4
|
|
|
4
5
|
// Inspect only selector context. No stylesheet or script is executed in this
|
|
5
6
|
// detached document. Keep original declarations, specificity and enclosing
|
|
6
7
|
// media/supports/container/layer rules rather than freezing computed values.
|
|
7
|
-
function missingSelectors({ snapshot, rules }) {
|
|
8
|
+
function missingSelectors({ snapshot, rules, idAttribute }) {
|
|
8
9
|
const copy = document.implementation.createHTMLDocument("");
|
|
9
10
|
for (const { name, value } of snapshot.htmlAttributes)
|
|
10
11
|
copy.documentElement.setAttribute(name, value);
|
|
@@ -20,8 +21,8 @@ function missingSelectors({ snapshot, rules }) {
|
|
|
20
21
|
}
|
|
21
22
|
container.innerHTML = snapshot.html;
|
|
22
23
|
const clones = new Map(
|
|
23
|
-
[...copy.querySelectorAll(
|
|
24
|
-
element.getAttribute(
|
|
24
|
+
[...copy.querySelectorAll(`[${idAttribute}]`)].map((element) => [
|
|
25
|
+
element.getAttribute(idAttribute),
|
|
25
26
|
element,
|
|
26
27
|
]),
|
|
27
28
|
);
|
|
@@ -30,7 +31,7 @@ function missingSelectors({ snapshot, rules }) {
|
|
|
30
31
|
for (const selector of rule.selectors) {
|
|
31
32
|
try {
|
|
32
33
|
for (const element of document.querySelectorAll(selector)) {
|
|
33
|
-
const id = element.getAttribute(
|
|
34
|
+
const id = element.getAttribute(idAttribute);
|
|
34
35
|
const cloned = clones.get(id);
|
|
35
36
|
if (cloned && !cloned.matches(selector))
|
|
36
37
|
result.push({ rule: rule.id, selector, id });
|
|
@@ -106,15 +107,24 @@ export function contextualCss(stylesheets) {
|
|
|
106
107
|
flush();
|
|
107
108
|
}
|
|
108
109
|
for (const root of roots) visit(root, null);
|
|
110
|
+
// The index is keyed by rule and selector so that rendering does not
|
|
111
|
+
// rescan every observation for each selector.
|
|
109
112
|
const missing = new Map();
|
|
113
|
+
const observations = new Map();
|
|
110
114
|
return {
|
|
111
115
|
async observe(page, snapshot) {
|
|
112
116
|
const result = await page.evaluate(missingSelectors, {
|
|
113
117
|
snapshot,
|
|
114
118
|
rules: descriptors,
|
|
119
|
+
idAttribute: ID_ATTR,
|
|
115
120
|
});
|
|
116
|
-
for (const item of result)
|
|
121
|
+
for (const item of result) {
|
|
117
122
|
missing.set(`${item.rule}|${item.selector}|${item.id}`, item);
|
|
123
|
+
const key = `${item.rule}|${item.selector}`;
|
|
124
|
+
const ids = observations.get(key) || new Set();
|
|
125
|
+
ids.add(item.id);
|
|
126
|
+
observations.set(key, ids);
|
|
127
|
+
}
|
|
118
128
|
},
|
|
119
129
|
render() {
|
|
120
130
|
const anchorFor = (container) => {
|
|
@@ -139,11 +149,9 @@ export function contextualCss(stylesheets) {
|
|
|
139
149
|
const anchor = anchorFor(original);
|
|
140
150
|
if (!affected.has(anchor)) continue;
|
|
141
151
|
const selectors = descriptors[id].selectors.map((selector) => {
|
|
142
|
-
const
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
return elements.length
|
|
146
|
-
? `:is(${selector}, :where(${elements.map((item) => `[data-uiport-id="${item.id}"]`).join(", ")}))`
|
|
152
|
+
const ids = observations.get(`${id}|${selector}`);
|
|
153
|
+
return ids?.size
|
|
154
|
+
? `:is(${selector}, :where(${[...ids].map((elementId) => `[data-uiport-id="${elementId}"]`).join(", ")}))`
|
|
147
155
|
: selector;
|
|
148
156
|
});
|
|
149
157
|
let fallback = postcss.rule({ selector: selectors.join(", ") });
|
package/scripts/diff.mjs
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import pixelmatch from "pixelmatch";
|
|
4
|
+
import { PNG } from "pngjs";
|
|
5
|
+
import { chromium } from "playwright-core";
|
|
6
|
+
import {
|
|
7
|
+
launchChromium,
|
|
8
|
+
lifecycle,
|
|
9
|
+
log,
|
|
10
|
+
startStaticServer,
|
|
11
|
+
waitForPageStable,
|
|
12
|
+
} from "./lib.mjs";
|
|
13
|
+
import {
|
|
14
|
+
BEHAVIOR,
|
|
15
|
+
LEGACY_ROOT_ATTR,
|
|
16
|
+
METADATA_ID,
|
|
17
|
+
ROOT_ATTR,
|
|
18
|
+
ROOT_VALUE,
|
|
19
|
+
} from "./contract.mjs";
|
|
20
|
+
|
|
21
|
+
async function readMetadata(directory) {
|
|
22
|
+
try {
|
|
23
|
+
const html = await fs.readFile(path.join(directory, "index.html"), "utf8");
|
|
24
|
+
const match = html.match(
|
|
25
|
+
new RegExp(
|
|
26
|
+
`<script type="application/json" id="${METADATA_ID}">([\\s\\S]*?)</script>`,
|
|
27
|
+
),
|
|
28
|
+
);
|
|
29
|
+
if (!match) return null;
|
|
30
|
+
return JSON.parse(match[1]);
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const rootSelector = `[${ROOT_ATTR}="${ROOT_VALUE}"]`;
|
|
37
|
+
const legacyRootSelector = `[${LEGACY_ROOT_ATTR}="${ROOT_VALUE}"]`;
|
|
38
|
+
|
|
39
|
+
/** Compares two exported sections: the pixels they render and what they report. */
|
|
40
|
+
export async function diff(options) {
|
|
41
|
+
const before = path.resolve(options.before);
|
|
42
|
+
const after = path.resolve(options.after);
|
|
43
|
+
for (const directory of [before, after])
|
|
44
|
+
await fs.access(path.join(directory, "index.html"));
|
|
45
|
+
const life = lifecycle(options.timeoutMs);
|
|
46
|
+
try {
|
|
47
|
+
const beforeServer = await startStaticServer(before);
|
|
48
|
+
const afterServer = await startStaticServer(after);
|
|
49
|
+
life.add(beforeServer.close);
|
|
50
|
+
life.add(afterServer.close);
|
|
51
|
+
const { browser, selected } = await launchChromium(chromium, life);
|
|
52
|
+
const results = [];
|
|
53
|
+
for (const viewport of options.viewports) {
|
|
54
|
+
life.check();
|
|
55
|
+
log(`Comparing ${viewport.name}…`);
|
|
56
|
+
const context = await browser.newContext({
|
|
57
|
+
viewport,
|
|
58
|
+
deviceScaleFactor: 1,
|
|
59
|
+
locale: options.locale,
|
|
60
|
+
colorScheme: options.colorScheme,
|
|
61
|
+
serviceWorkers: "block",
|
|
62
|
+
});
|
|
63
|
+
try {
|
|
64
|
+
const page = await context.newPage();
|
|
65
|
+
const shots = [];
|
|
66
|
+
for (const server of [beforeServer, afterServer]) {
|
|
67
|
+
await page.goto(`${server.url}/index.html`, {
|
|
68
|
+
waitUntil: "domcontentloaded",
|
|
69
|
+
});
|
|
70
|
+
await waitForPageStable(page, options.settleMs);
|
|
71
|
+
const root = page.locator(
|
|
72
|
+
(await page.locator(rootSelector).count())
|
|
73
|
+
? rootSelector
|
|
74
|
+
: legacyRootSelector,
|
|
75
|
+
);
|
|
76
|
+
if ((await root.count()) !== 1)
|
|
77
|
+
throw new Error(
|
|
78
|
+
"An exported section is missing its extraction root",
|
|
79
|
+
);
|
|
80
|
+
shots.push(await root.screenshot({ animations: "disabled" }));
|
|
81
|
+
}
|
|
82
|
+
const left = PNG.sync.read(shots[0]);
|
|
83
|
+
const right = PNG.sync.read(shots[1]);
|
|
84
|
+
const width = Math.max(left.width, right.width);
|
|
85
|
+
const height = Math.max(left.height, right.height);
|
|
86
|
+
if (width * height > 20_000_000)
|
|
87
|
+
throw new Error("Comparison exceeds screenshot limit");
|
|
88
|
+
const sameSize =
|
|
89
|
+
left.width === right.width && left.height === right.height;
|
|
90
|
+
const buffer = (source) => {
|
|
91
|
+
if (sameSize) return source.data;
|
|
92
|
+
const target = new Uint8Array(width * height * 4);
|
|
93
|
+
const rowBytes = source.width * 4;
|
|
94
|
+
for (let y = 0; y < source.height; y += 1)
|
|
95
|
+
source.data.copy(
|
|
96
|
+
target,
|
|
97
|
+
y * width * 4,
|
|
98
|
+
y * rowBytes,
|
|
99
|
+
y * rowBytes + rowBytes,
|
|
100
|
+
);
|
|
101
|
+
return target;
|
|
102
|
+
};
|
|
103
|
+
const differentPixels = pixelmatch(
|
|
104
|
+
buffer(left),
|
|
105
|
+
buffer(right),
|
|
106
|
+
null,
|
|
107
|
+
width,
|
|
108
|
+
height,
|
|
109
|
+
{ threshold: 0.1, includeAA: false },
|
|
110
|
+
);
|
|
111
|
+
const ratio = differentPixels / (width * height);
|
|
112
|
+
results.push({
|
|
113
|
+
viewport: viewport.name,
|
|
114
|
+
identical: ratio === 0,
|
|
115
|
+
differentPixels,
|
|
116
|
+
differenceRatio: ratio,
|
|
117
|
+
dimensionsMatch:
|
|
118
|
+
left.width === right.width && left.height === right.height,
|
|
119
|
+
});
|
|
120
|
+
} finally {
|
|
121
|
+
await context.close();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const beforeMetadata = await readMetadata(before);
|
|
125
|
+
const afterMetadata = await readMetadata(after);
|
|
126
|
+
const codes = (metadata) =>
|
|
127
|
+
(metadata?.limitations || []).map((entry) => entry.code).sort();
|
|
128
|
+
const added = codes(afterMetadata).filter(
|
|
129
|
+
(code) => !codes(beforeMetadata).includes(code),
|
|
130
|
+
);
|
|
131
|
+
const removed = codes(beforeMetadata).filter(
|
|
132
|
+
(code) => !codes(afterMetadata).includes(code),
|
|
133
|
+
);
|
|
134
|
+
const changed = results.some((entry) => !entry.identical);
|
|
135
|
+
return {
|
|
136
|
+
command: "diff",
|
|
137
|
+
status: changed || added.length ? "partial" : "complete",
|
|
138
|
+
before,
|
|
139
|
+
after,
|
|
140
|
+
browser: { selected, version: browser.version() },
|
|
141
|
+
identical: !changed,
|
|
142
|
+
results,
|
|
143
|
+
limitations: { added, removed },
|
|
144
|
+
behavior: BEHAVIOR,
|
|
145
|
+
};
|
|
146
|
+
} finally {
|
|
147
|
+
await life.close();
|
|
148
|
+
}
|
|
149
|
+
}
|
package/scripts/dom.mjs
CHANGED
|
@@ -1,7 +1,55 @@
|
|
|
1
1
|
// Runs inside the source browser. No Node state is captured by this function.
|
|
2
|
+
// Measures whether the selected root renders something of its own or through
|
|
3
|
+
// its children. A root without a box of its own can still be visible:
|
|
4
|
+
// `display: contents`, a zero-sized wrapper around an absolutely positioned
|
|
5
|
+
// child, or a parent whose visibility is overridden by a child.
|
|
6
|
+
export function measureRoot(element) {
|
|
7
|
+
const renders = (node) => {
|
|
8
|
+
const style = getComputedStyle(node);
|
|
9
|
+
if (style.display === "none" || style.visibility === "hidden") return false;
|
|
10
|
+
if (
|
|
11
|
+
node.checkVisibility &&
|
|
12
|
+
!node.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })
|
|
13
|
+
)
|
|
14
|
+
return false;
|
|
15
|
+
const box = node.getBoundingClientRect();
|
|
16
|
+
return box.width > 0 && box.height > 0;
|
|
17
|
+
};
|
|
18
|
+
let width = 0;
|
|
19
|
+
let height = 0;
|
|
20
|
+
for (const child of element.children) {
|
|
21
|
+
if (!renders(child)) continue;
|
|
22
|
+
const box = child.getBoundingClientRect();
|
|
23
|
+
width = Math.max(width, box.width);
|
|
24
|
+
height = Math.max(height, box.height);
|
|
25
|
+
}
|
|
26
|
+
if (renders(element)) {
|
|
27
|
+
const box = element.getBoundingClientRect();
|
|
28
|
+
width = Math.max(width, box.width);
|
|
29
|
+
height = Math.max(height, box.height);
|
|
30
|
+
}
|
|
31
|
+
const style = getComputedStyle(element);
|
|
32
|
+
const displaysNothing = width <= 0 || height <= 0;
|
|
33
|
+
// A root hidden by its own style displays nothing even when a child could
|
|
34
|
+
// override the visibility. A root without a box is empty instead.
|
|
35
|
+
const hidden =
|
|
36
|
+
displaysNothing &&
|
|
37
|
+
(style.display === "none" ||
|
|
38
|
+
style.visibility === "hidden" ||
|
|
39
|
+
(element.checkVisibility &&
|
|
40
|
+
!element.checkVisibility({
|
|
41
|
+
checkOpacity: true,
|
|
42
|
+
checkVisibilityCSS: true,
|
|
43
|
+
})));
|
|
44
|
+
return { hidden, visible: !displaysNothing, width, height };
|
|
45
|
+
}
|
|
46
|
+
|
|
2
47
|
export function extractSection({
|
|
3
48
|
selector: targetSelector,
|
|
4
49
|
omitScripts = false,
|
|
50
|
+
idAttribute = "data-uiport-id",
|
|
51
|
+
rootAttribute = "data-uiport-root",
|
|
52
|
+
rootValue = "true",
|
|
5
53
|
}) {
|
|
6
54
|
const target = document.querySelector(targetSelector);
|
|
7
55
|
if (!target) throw new Error("Target disappeared before capture.");
|
|
@@ -61,13 +109,13 @@ export function extractSection({
|
|
|
61
109
|
};
|
|
62
110
|
visit(target);
|
|
63
111
|
deepElements.forEach((element, index) =>
|
|
64
|
-
element.setAttribute(
|
|
112
|
+
element.setAttribute(idAttribute, `up-${index}`),
|
|
65
113
|
);
|
|
66
|
-
target.setAttribute(
|
|
114
|
+
target.setAttribute(rootAttribute, rootValue);
|
|
67
115
|
let parent = target.parentElement;
|
|
68
116
|
let ancestorId = 0;
|
|
69
117
|
while (parent) {
|
|
70
|
-
parent.setAttribute(
|
|
118
|
+
parent.setAttribute(idAttribute, `up-ancestor-${ancestorId++}`);
|
|
71
119
|
parent = parent.parentElement;
|
|
72
120
|
}
|
|
73
121
|
let preservedScripts = 0;
|
|
@@ -157,7 +205,13 @@ export function extractSection({
|
|
|
157
205
|
}
|
|
158
206
|
}
|
|
159
207
|
if (source.tagName === "STYLE") {
|
|
160
|
-
|
|
208
|
+
// A style element created by a script can hold text that an HTML parser
|
|
209
|
+
// would read as the end of the element. The escape keeps the text in one
|
|
210
|
+
// piece and is equivalent CSS.
|
|
211
|
+
clone.textContent = absolutizeCssUrls(
|
|
212
|
+
source.textContent,
|
|
213
|
+
source.baseURI,
|
|
214
|
+
).replace(/<\/style/gi, "<\\/style");
|
|
161
215
|
return clone;
|
|
162
216
|
}
|
|
163
217
|
if (source.shadowRoot) {
|
|
@@ -204,85 +258,6 @@ export function extractSection({
|
|
|
204
258
|
ancestor = ancestor.parentElement;
|
|
205
259
|
}
|
|
206
260
|
|
|
207
|
-
const references = [];
|
|
208
|
-
const referenceKeys = new Set();
|
|
209
|
-
const addReference = (kind, value, ownerId, base = document.baseURI) => {
|
|
210
|
-
if (!value || /^(data:|#|javascript:|mailto:|tel:)/i.test(value.trim()))
|
|
211
|
-
return;
|
|
212
|
-
const url = absoluteUrl(value, base);
|
|
213
|
-
const key = `${kind}|${url}`;
|
|
214
|
-
if (!referenceKeys.has(key)) {
|
|
215
|
-
referenceKeys.add(key);
|
|
216
|
-
references.push({ kind, url, ownerId });
|
|
217
|
-
}
|
|
218
|
-
};
|
|
219
|
-
const urlsFromCss = (kind, value, ownerId) => {
|
|
220
|
-
for (const match of String(value || "").matchAll(
|
|
221
|
-
/url\(\s*['"]?([^'")]+)['"]?\s*\)/gi,
|
|
222
|
-
))
|
|
223
|
-
addReference(kind, match[1], ownerId);
|
|
224
|
-
};
|
|
225
|
-
|
|
226
|
-
const usedFontFamilies = new Set();
|
|
227
|
-
for (const element of deepElements) {
|
|
228
|
-
const ownerId = element.getAttribute("data-uiport-id");
|
|
229
|
-
if (["SCRIPT", "IFRAME", "OBJECT", "EMBED"].includes(element.tagName))
|
|
230
|
-
continue;
|
|
231
|
-
if (element.hasAttribute("srcset")) {
|
|
232
|
-
const srcset = element.getAttribute("srcset");
|
|
233
|
-
if (!srcset.trim().startsWith("data:"))
|
|
234
|
-
for (const candidate of srcset.split(","))
|
|
235
|
-
addReference(
|
|
236
|
-
"srcset",
|
|
237
|
-
candidate.trim().split(/\s+/)[0],
|
|
238
|
-
ownerId,
|
|
239
|
-
element.baseURI,
|
|
240
|
-
);
|
|
241
|
-
}
|
|
242
|
-
for (const attribute of [
|
|
243
|
-
"src",
|
|
244
|
-
"poster",
|
|
245
|
-
"data-src",
|
|
246
|
-
"data-background-image",
|
|
247
|
-
])
|
|
248
|
-
addReference(
|
|
249
|
-
attribute,
|
|
250
|
-
element.getAttribute(attribute),
|
|
251
|
-
ownerId,
|
|
252
|
-
element.baseURI,
|
|
253
|
-
);
|
|
254
|
-
if (element instanceof HTMLImageElement && element.currentSrc)
|
|
255
|
-
addReference("currentSrc", element.currentSrc, ownerId);
|
|
256
|
-
if (element instanceof SVGUseElement)
|
|
257
|
-
addReference(
|
|
258
|
-
"svg-use",
|
|
259
|
-
element.getAttribute("href") || element.getAttribute("xlink:href"),
|
|
260
|
-
ownerId,
|
|
261
|
-
element.baseURI,
|
|
262
|
-
);
|
|
263
|
-
const style = getComputedStyle(element);
|
|
264
|
-
usedFontFamilies.add(style.fontFamily);
|
|
265
|
-
for (const property of [
|
|
266
|
-
"background-image",
|
|
267
|
-
"mask-image",
|
|
268
|
-
"border-image-source",
|
|
269
|
-
"list-style-image",
|
|
270
|
-
"cursor",
|
|
271
|
-
]) {
|
|
272
|
-
urlsFromCss(property, style.getPropertyValue(property), ownerId);
|
|
273
|
-
}
|
|
274
|
-
for (const pseudoName of ["::before", "::after", "::marker"]) {
|
|
275
|
-
const pseudo = getComputedStyle(element, pseudoName);
|
|
276
|
-
for (const property of ["background-image", "mask-image", "content"]) {
|
|
277
|
-
urlsFromCss(
|
|
278
|
-
`${pseudoName}:${property}`,
|
|
279
|
-
pseudo.getPropertyValue(property),
|
|
280
|
-
ownerId,
|
|
281
|
-
);
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
|
|
286
261
|
const stylesheets = [
|
|
287
262
|
...document.styleSheets,
|
|
288
263
|
...document.adoptedStyleSheets,
|
|
@@ -304,13 +279,6 @@ export function extractSection({
|
|
|
304
279
|
};
|
|
305
280
|
});
|
|
306
281
|
|
|
307
|
-
const customProperties = {};
|
|
308
|
-
const rootStyle = getComputedStyle(target);
|
|
309
|
-
for (const property of rootStyle) {
|
|
310
|
-
if (property.startsWith("--"))
|
|
311
|
-
customProperties[property] = rootStyle.getPropertyValue(property);
|
|
312
|
-
}
|
|
313
|
-
|
|
314
282
|
const animations = [];
|
|
315
283
|
const seen = new Set();
|
|
316
284
|
for (const element of deepElements) {
|
|
@@ -329,7 +297,7 @@ export function extractSection({
|
|
|
329
297
|
} catch {}
|
|
330
298
|
animations.push({
|
|
331
299
|
kind: animation.constructor?.name || "Animation",
|
|
332
|
-
targetId: effect?.target?.getAttribute?.(
|
|
300
|
+
targetId: effect?.target?.getAttribute?.(idAttribute) || null,
|
|
333
301
|
pseudoElement: effect?.pseudoElement || null,
|
|
334
302
|
keyframes,
|
|
335
303
|
timing,
|
|
@@ -395,10 +363,7 @@ export function extractSection({
|
|
|
395
363
|
(attribute) => attribute.name !== "lang",
|
|
396
364
|
),
|
|
397
365
|
bodyAttributes: attributesOf(document.body),
|
|
398
|
-
references,
|
|
399
|
-
usedFontFamilies: [...usedFontFamilies],
|
|
400
366
|
stylesheets,
|
|
401
|
-
customProperties,
|
|
402
367
|
animations,
|
|
403
368
|
featureCounts: {
|
|
404
369
|
elements: deepElements.length,
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// The failures a caller can act on. Every error carries a stable code and a
|
|
2
|
+
// hint, so a script can branch on the code and a person knows what to do.
|
|
3
|
+
export const CODES = {
|
|
4
|
+
USAGE_INVALID: "The arguments of the command are not valid.",
|
|
5
|
+
BROWSER_NOT_FOUND:
|
|
6
|
+
"No supported browser was found. Run `uiport browser install`, or set UIPORT_BROWSER_PATH.",
|
|
7
|
+
OUTPUT_NOT_EMPTY:
|
|
8
|
+
"The output directory already has files. Choose a new directory or empty it.",
|
|
9
|
+
SELECTOR_NOT_FOUND:
|
|
10
|
+
"The selector matched no element. Inspect the page and check the selector.",
|
|
11
|
+
SELECTOR_AMBIGUOUS:
|
|
12
|
+
"The selector matched more than one element. Narrow it, or capture the whole page with `--selector body`.",
|
|
13
|
+
TIMEOUT:
|
|
14
|
+
"The operation exceeded its deadline. Raise `--timeout` or reduce `--viewports`.",
|
|
15
|
+
CANCELLED: "The operation was cancelled.",
|
|
16
|
+
SOURCE_UNREACHABLE:
|
|
17
|
+
"The source page could not be loaded. Check the address and that the page is reachable.",
|
|
18
|
+
ARTIFACT_MISSING:
|
|
19
|
+
"The directory has no exported section. Run `uiport capture` first.",
|
|
20
|
+
INTERNAL: "The operation failed for an unexpected reason.",
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export class UiportError extends Error {
|
|
24
|
+
/**
|
|
25
|
+
* @param {keyof typeof CODES} code
|
|
26
|
+
* @param {string} message
|
|
27
|
+
* @param {{cause?: unknown, hint?: string}} [options]
|
|
28
|
+
*/
|
|
29
|
+
constructor(code, message, options = {}) {
|
|
30
|
+
super(message, options.cause ? { cause: options.cause } : undefined);
|
|
31
|
+
this.name = "UiportError";
|
|
32
|
+
this.code = code;
|
|
33
|
+
this.hint = options.hint || CODES[code];
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @param {unknown} error
|
|
39
|
+
* @returns {{code: string, message: string, hint: string}}
|
|
40
|
+
*/
|
|
41
|
+
export function describeError(error) {
|
|
42
|
+
if (error instanceof UiportError)
|
|
43
|
+
return {
|
|
44
|
+
code: error.code,
|
|
45
|
+
message: error.message,
|
|
46
|
+
hint: error.hint,
|
|
47
|
+
};
|
|
48
|
+
const message = String(error?.message || error || "Operation failed").split(
|
|
49
|
+
/[\r\n]/,
|
|
50
|
+
1,
|
|
51
|
+
)[0];
|
|
52
|
+
return { code: "INTERNAL", message, hint: CODES.INTERNAL };
|
|
53
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { startStaticServer } from "./lib.mjs";
|
|
4
|
+
|
|
5
|
+
// The examples travel with the package, so a person can try the tool without
|
|
6
|
+
// choosing a page of their own first.
|
|
7
|
+
const directory = path.join(
|
|
8
|
+
path.dirname(fileURLToPath(import.meta.url)),
|
|
9
|
+
"..",
|
|
10
|
+
"examples",
|
|
11
|
+
);
|
|
12
|
+
|
|
13
|
+
export async function examples(options) {
|
|
14
|
+
const server = await startStaticServer(directory, options.port);
|
|
15
|
+
const ready = {
|
|
16
|
+
command: "examples",
|
|
17
|
+
status: "ready",
|
|
18
|
+
directory,
|
|
19
|
+
url: server.url,
|
|
20
|
+
};
|
|
21
|
+
console.log(
|
|
22
|
+
options.json
|
|
23
|
+
? JSON.stringify(ready)
|
|
24
|
+
: `UIport serving the original examples at ${server.url}\nTry: uiport capture --url ${server.url}/responsive-hero/ --selector "#hero" --out ./hero\nPress Ctrl+C to stop.`,
|
|
25
|
+
);
|
|
26
|
+
await new Promise((resolve) => {
|
|
27
|
+
const stop = async () => {
|
|
28
|
+
process.removeListener("SIGINT", stop);
|
|
29
|
+
process.removeListener("SIGTERM", stop);
|
|
30
|
+
await server.close();
|
|
31
|
+
resolve();
|
|
32
|
+
};
|
|
33
|
+
process.once("SIGINT", stop);
|
|
34
|
+
process.once("SIGTERM", stop);
|
|
35
|
+
});
|
|
36
|
+
return { command: "examples", status: "stopped" };
|
|
37
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { UiportError } from "./errors.mjs";
|
|
4
|
+
import { BEHAVIOR, METADATA_ID } from "./contract.mjs";
|
|
5
|
+
|
|
6
|
+
/** Reads what an exported section carries, without opening a browser. */
|
|
7
|
+
export async function inspect(options) {
|
|
8
|
+
const file = path.join(options.directory, "index.html");
|
|
9
|
+
let html;
|
|
10
|
+
try {
|
|
11
|
+
html = await fs.readFile(file, "utf8");
|
|
12
|
+
} catch (error) {
|
|
13
|
+
throw new UiportError(
|
|
14
|
+
"ARTIFACT_MISSING",
|
|
15
|
+
`The directory has no exported section: ${file}`,
|
|
16
|
+
{ cause: error },
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
const match = html.match(
|
|
20
|
+
new RegExp(
|
|
21
|
+
`<script type="application/json" id="${METADATA_ID}">([\\s\\S]*?)</script>`,
|
|
22
|
+
),
|
|
23
|
+
);
|
|
24
|
+
let metadata = {};
|
|
25
|
+
if (match)
|
|
26
|
+
try {
|
|
27
|
+
metadata = JSON.parse(match[1]);
|
|
28
|
+
} catch {
|
|
29
|
+
metadata = {};
|
|
30
|
+
}
|
|
31
|
+
let assets;
|
|
32
|
+
try {
|
|
33
|
+
assets = (await fs.readdir(path.join(options.directory, "assets"))).length;
|
|
34
|
+
} catch {
|
|
35
|
+
assets = 0;
|
|
36
|
+
}
|
|
37
|
+
const limitations = Array.isArray(metadata.limitations)
|
|
38
|
+
? metadata.limitations
|
|
39
|
+
: [];
|
|
40
|
+
return {
|
|
41
|
+
command: "inspect",
|
|
42
|
+
status: limitations.length ? "partial" : "complete",
|
|
43
|
+
outputDirectory: options.directory,
|
|
44
|
+
assets,
|
|
45
|
+
elements: metadata.elements ?? null,
|
|
46
|
+
source: metadata.source ?? null,
|
|
47
|
+
behavior: metadata.behavior ?? BEHAVIOR,
|
|
48
|
+
limitations,
|
|
49
|
+
};
|
|
50
|
+
}
|
package/scripts/lib.mjs
CHANGED
|
@@ -5,6 +5,7 @@ import http from "node:http";
|
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { performance } from "node:perf_hooks";
|
|
7
7
|
import { startBrowser } from "./browser-process.mjs";
|
|
8
|
+
import { UiportError } from "./errors.mjs";
|
|
8
9
|
|
|
9
10
|
export const sha256 = (buffer) =>
|
|
10
11
|
crypto.createHash("sha256").update(buffer).digest("hex");
|
|
@@ -94,7 +95,8 @@ export async function inspectOutput(directory) {
|
|
|
94
95
|
stat.isSymbolicLink() ||
|
|
95
96
|
(await fs.readdir(destination)).length
|
|
96
97
|
)
|
|
97
|
-
throw new
|
|
98
|
+
throw new UiportError(
|
|
99
|
+
"OUTPUT_NOT_EMPTY",
|
|
98
100
|
"Output must be a new or empty directory (not a symlink)",
|
|
99
101
|
);
|
|
100
102
|
existing = true;
|
|
@@ -115,27 +117,17 @@ export async function stageOutput(directory) {
|
|
|
115
117
|
return {
|
|
116
118
|
directory: temporary,
|
|
117
119
|
async commit() {
|
|
118
|
-
// Recheck immediately before moving.
|
|
120
|
+
// Recheck immediately before moving. The directory is published with a
|
|
121
|
+
// single rename, so a reader never observes it half written.
|
|
119
122
|
if (existing) await fs.rmdir(destination); // only succeeds when still empty
|
|
120
|
-
await fs.mkdir(destination);
|
|
121
|
-
const moved = [];
|
|
122
123
|
try {
|
|
123
|
-
|
|
124
|
-
await fs.rename(
|
|
125
|
-
path.join(temporary, name),
|
|
126
|
-
path.join(destination, name),
|
|
127
|
-
);
|
|
128
|
-
moved.push(name);
|
|
129
|
-
}
|
|
130
|
-
committed = true;
|
|
124
|
+
await fs.rename(temporary, destination);
|
|
131
125
|
} catch (error) {
|
|
132
|
-
|
|
133
|
-
await fs
|
|
134
|
-
.rename(path.join(destination, name), path.join(temporary, name))
|
|
135
|
-
.catch(() => {});
|
|
136
|
-
await fs.rmdir(destination).catch(() => {});
|
|
126
|
+
if (existing)
|
|
127
|
+
await fs.mkdir(destination, { recursive: true }).catch(() => {});
|
|
137
128
|
throw error;
|
|
138
129
|
}
|
|
130
|
+
committed = true;
|
|
139
131
|
},
|
|
140
132
|
async cleanup() {
|
|
141
133
|
await fs.rm(temporary, { recursive: true, force: true });
|
|
@@ -147,6 +139,10 @@ export async function stageOutput(directory) {
|
|
|
147
139
|
|
|
148
140
|
export async function waitForPageStable(page, settleMs) {
|
|
149
141
|
await page.waitForLoadState("domcontentloaded");
|
|
142
|
+
// The two waits keep their own budget: the network idle window first, then
|
|
143
|
+
// the fonts and decoded images. Sharing one budget would start the capture
|
|
144
|
+
// while a slow image is still loading, which the export — served locally —
|
|
145
|
+
// would not show, producing a false visual difference.
|
|
150
146
|
await page.waitForLoadState("networkidle", { timeout: 2000 }).catch(() => {});
|
|
151
147
|
await page.evaluate(async () => {
|
|
152
148
|
await Promise.race([
|
|
@@ -195,6 +191,7 @@ export function mimeForFile(filePath) {
|
|
|
195
191
|
[".woff2", "font/woff2"],
|
|
196
192
|
[".woff", "font/woff"],
|
|
197
193
|
[".ttf", "font/ttf"],
|
|
194
|
+
[".otf", "font/otf"],
|
|
198
195
|
[".mp4", "video/mp4"],
|
|
199
196
|
[".webm", "video/webm"],
|
|
200
197
|
[".json", "application/json"],
|
|
@@ -312,7 +309,8 @@ export async function launchChromium(chromium, life) {
|
|
|
312
309
|
/* try next installed browser */
|
|
313
310
|
}
|
|
314
311
|
}
|
|
315
|
-
throw new
|
|
312
|
+
throw new UiportError(
|
|
313
|
+
"BROWSER_NOT_FOUND",
|
|
316
314
|
"No supported browser found. Run: uiport browser install (or set UIPORT_BROWSER_PATH).",
|
|
317
315
|
);
|
|
318
316
|
}
|
|
@@ -329,7 +327,10 @@ export function lifecycle(timeoutMs) {
|
|
|
329
327
|
for (const fn of [...cleanups].reverse()) await fn().catch(() => {});
|
|
330
328
|
})());
|
|
331
329
|
const cancel = (message) => {
|
|
332
|
-
reason ||= new
|
|
330
|
+
reason ||= new UiportError(
|
|
331
|
+
message.startsWith("Operation exceeded") ? "TIMEOUT" : "CANCELLED",
|
|
332
|
+
message,
|
|
333
|
+
);
|
|
333
334
|
controller.abort(reason);
|
|
334
335
|
void cleanup();
|
|
335
336
|
};
|