uiport 0.1.1 → 0.1.2
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 +20 -0
- package/README.md +5 -5
- package/README.pt-BR.md +5 -5
- package/SECURITY.md +1 -1
- package/bin/cli.mjs +13 -2
- package/docs/architecture.md +1 -1
- package/docs/support.md +9 -3
- package/package.json +1 -1
- package/scripts/capture.mjs +98 -27
- package/scripts/css-context.mjs +12 -6
- package/scripts/dom.mjs +45 -89
- package/scripts/lib.mjs +4 -0
- package/scripts/resources.mjs +130 -70
- package/scripts/srcset.mjs +14 -0
- package/scripts/stdout.mjs +13 -0
- package/scripts/validate.mjs +43 -32
- package/skills/uiport/SKILL.md +2 -2
- package/uiport.md +5 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,26 @@
|
|
|
2
2
|
|
|
3
3
|
Notable changes are documented here. Versions follow Semantic Versioning.
|
|
4
4
|
|
|
5
|
+
## [Unreleased]
|
|
6
|
+
|
|
7
|
+
## [0.1.2] — 2026-11-28
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
- Keep stdout clean: a capture or a validation writes exactly one JSON document, and anything a dependency prints meanwhile goes to the diagnostics channel.
|
|
11
|
+
- Preserve an unparsable `srcset` unchanged and report `SRCSET_INVALID`, instead of dropping the attribute silently and changing which image the browser picks.
|
|
12
|
+
- Report a selected root that renders nothing (`SECTION_NOT_VISIBLE`, `SECTION_EMPTY_AREA`) instead of waiting for a screenshot that cannot succeed, and refuse it during validation with an actionable message. A root that renders through its children — `display: contents`, a zero-sized wrapper, a parent whose visibility is overridden — is no longer reported as empty.
|
|
13
|
+
- Wait for the decoding of fonts and images after the network idle window, with its own budget, so a slow image is decoded before the source is compared with the export.
|
|
14
|
+
- Report the bytes read from the network and the bytes charged against the total budget separately, and enforce the budget across concurrent transfers instead of counting the bytes of a rejected transfer.
|
|
15
|
+
- Order the reported limitations independently of the locale of the machine.
|
|
16
|
+
- Document `INVALID_RESOURCE_URL` in the support matrix.
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
- Accept a manual publication run only from the release tag, and abort when the registry check fails for a reason other than an unknown version.
|
|
20
|
+
- Download the resources referenced by a section concurrently, with a bounded pool of eight transfers. The total budget, the per-resource limit and the exported files stay the same; a capture of forty assets over a 100 ms round trip went from 8.1 s to 4.5 s.
|
|
21
|
+
- Compare the source and the export without copying pixels one by one: when both sides have the same size their decoded pixels are compared directly. Validating a 20-megapixel section went from 7.9 s to 7.0 s and from 618 MB to 529 MB of resident memory.
|
|
22
|
+
- Collect in the browser only what the export uses. The per-element computed styles, the custom property snapshot and the font list were collected for every element and never read.
|
|
23
|
+
- Wait for the network and for the fonts and images at the same time, and localize the assets of the document concurrently.
|
|
24
|
+
|
|
5
25
|
## [0.1.1] — 2026-10-01
|
|
6
26
|
|
|
7
27
|
### Fixed
|
package/README.md
CHANGED
|
@@ -25,13 +25,13 @@ Requires **Node.js 22.14+**; Node 24 LTS recommended. Chromium is installed expl
|
|
|
25
25
|
Run these commands in any directory, including an empty one. `npx` fetches UIport automatically; you do not need a `package.json` or `npm install` in that directory. `browser install` prepares Chromium in Playwright's shared browser cache.
|
|
26
26
|
|
|
27
27
|
```sh
|
|
28
|
-
npx uiport@0.1.
|
|
29
|
-
npx uiport@0.1.
|
|
30
|
-
npx uiport@0.1.
|
|
31
|
-
npx uiport@0.1.
|
|
28
|
+
npx uiport@0.1.2 browser install
|
|
29
|
+
npx uiport@0.1.2 capture --url "https://your-site.example" --selector "#hero" --out ./my-section
|
|
30
|
+
npx uiport@0.1.2 serve --dir ./my-section
|
|
31
|
+
npx uiport@0.1.2 validate --url "https://your-site.example" --selector "#hero" --dir ./my-section
|
|
32
32
|
```
|
|
33
33
|
|
|
34
|
-
Choose the selector using your browser's **Inspect element** tool. It must match exactly one container, such as `main`, `section` or a `div
|
|
34
|
+
Choose the selector using your browser's **Inspect element** tool. It must match exactly one container, such as `main`, `section` or a `div`, and that container must render something at the captured viewport: a root that displays nothing is reported as a partial result. Use `body` to capture the whole visible page, or `html` to include original head scripts as well. This captures one page, not a multi-page crawl.
|
|
35
35
|
|
|
36
36
|
For repeated use: `npm install -g uiport`, then `uiport --help`. Pin a version for repeatable captures; `npx uiport@latest` follows future releases.
|
|
37
37
|
|
package/README.pt-BR.md
CHANGED
|
@@ -25,13 +25,13 @@ Requer **Node.js 22.14+**; recomendamos Node 24 LTS. O Chromium é instalado exp
|
|
|
25
25
|
Execute os comandos em uma pasta de sua escolha, que pode estar vazia. O `npx` obtém o UIport automaticamente; não é necessário criar um `package.json` nem rodar `npm install` nessa pasta. `browser install` prepara o Chromium no cache compartilhado do Playwright.
|
|
26
26
|
|
|
27
27
|
```sh
|
|
28
|
-
npx uiport@0.1.
|
|
29
|
-
npx uiport@0.1.
|
|
30
|
-
npx uiport@0.1.
|
|
31
|
-
npx uiport@0.1.
|
|
28
|
+
npx uiport@0.1.2 browser install
|
|
29
|
+
npx uiport@0.1.2 capture --url "https://seu-site.example" --selector "#hero" --out ./minha-secao
|
|
30
|
+
npx uiport@0.1.2 serve --dir ./minha-secao
|
|
31
|
+
npx uiport@0.1.2 validate --url "https://seu-site.example" --selector "#hero" --dir ./minha-secao
|
|
32
32
|
```
|
|
33
33
|
|
|
34
|
-
Para escolher o seletor, use **Inspecionar elemento** no navegador. Ele precisa encontrar exatamente um container, como `main`, `section` ou `div
|
|
34
|
+
Para escolher o seletor, use **Inspecionar elemento** no navegador. Ele precisa encontrar exatamente um container, como `main`, `section` ou `div`, e esse container precisa renderizar algo no tamanho de tela capturado: uma raiz que não exibe nada é relatada como resultado parcial. Use `body` para capturar a página visível completa ou `html` para incluir também scripts originais do head. Isso captura uma página, sem percorrer automaticamente outras URLs do site.
|
|
35
35
|
|
|
36
36
|
Para uso frequente: `npm install -g uiport`, depois `uiport --help`. Fixe uma versão quando precisar reproduzir uma captura; `npx uiport@latest` acompanha versões futuras.
|
|
37
37
|
|
package/SECURITY.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Security policy
|
|
2
2
|
|
|
3
|
-
The latest 0.1.x release is the supported line
|
|
3
|
+
The latest 0.1.x release is the supported line.
|
|
4
4
|
|
|
5
5
|
Please use GitHub's **Report a vulnerability** feature:
|
|
6
6
|
https://github.com/LorranHippolyte/uiport/security/advisories/new
|
package/bin/cli.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { spawn } from "node:child_process";
|
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { allowed, parseArgs, optionsFor } from "../scripts/options.mjs";
|
|
6
6
|
import { safeErrorMessage } from "../scripts/lib.mjs";
|
|
7
|
+
import { guardStdout } from "../scripts/stdout.mjs";
|
|
7
8
|
const require = createRequire(import.meta.url);
|
|
8
9
|
const { version } = require("../package.json");
|
|
9
10
|
const argv = process.argv.slice(2);
|
|
@@ -102,8 +103,18 @@ try {
|
|
|
102
103
|
process.exitCode = Number(code);
|
|
103
104
|
} else {
|
|
104
105
|
const options = optionsFor(command, args);
|
|
105
|
-
|
|
106
|
-
|
|
106
|
+
// A capture or a validation writes exactly one JSON document to stdout.
|
|
107
|
+
// The guard is installed before the command module is loaded, so that
|
|
108
|
+
// anything printed while loading also goes to the diagnostics channel.
|
|
109
|
+
const guarded = command === "capture" || command === "validate";
|
|
110
|
+
const restore = guarded ? guardStdout() : () => {};
|
|
111
|
+
let result;
|
|
112
|
+
try {
|
|
113
|
+
const { [command]: run } = await import(`../scripts/${command}.mjs`);
|
|
114
|
+
result = await run(options);
|
|
115
|
+
} finally {
|
|
116
|
+
restore();
|
|
117
|
+
}
|
|
107
118
|
if (command !== "serve")
|
|
108
119
|
console.log(JSON.stringify(result, null, args.json ? undefined : 2));
|
|
109
120
|
process.exitCode =
|
package/docs/architecture.md
CHANGED
|
@@ -18,7 +18,7 @@ flowchart LR
|
|
|
18
18
|
- `scripts/options.mjs`: strict arguments, URL/number/viewport validation.
|
|
19
19
|
- `scripts/capture.mjs`: capture orchestration, staged filesystem output, metadata and exact-data WAAPI replay.
|
|
20
20
|
- `scripts/dom.mjs`: browser-side DOM serialization; preserves source scripts/handlers by default (explicit --omit-scripts opt-out), supports section/body/html roots, handles open shadow trees, records styles and animation data.
|
|
21
|
-
- `scripts/resources.mjs`: streamed size/deadline limits, hash-named assets, PostCSS import processing and URL rewriting. Responses from the capture browser are preferred; independent HTTP fetch is a fallback. No personal browser session is imported.
|
|
21
|
+
- `scripts/resources.mjs`: streamed size/deadline limits, hash-named assets, PostCSS import processing and URL rewriting. Responses from the capture browser are preferred; independent HTTP fetch is a fallback. Referenced assets are fetched concurrently through a bounded pool that shares the total budget. No personal browser session is imported.
|
|
22
22
|
- `scripts/browser-resources.mjs`: bounded retention of response bodies and redirect aliases from the fresh source context; Playwright body materialization is not a streaming memory limit.
|
|
23
23
|
- `scripts/css-context.mjs`: restores custom-property declarations whose selectors lost structural context, preserving their specificity, order and enclosing conditions instead of freezing computed viewport values.
|
|
24
24
|
- `scripts/validate.mjs`: isolated source/output contexts, screenshot comparison, resource and execution diagnostics. Does not infer behavioral equivalence.
|
package/docs/support.md
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
# UIport
|
|
1
|
+
# UIport support matrix
|
|
2
|
+
|
|
3
|
+
This matrix describes the 0.1.x CLI line and was last verified against 0.1.2. It applies to every 0.1.x release unless a row says otherwise.
|
|
2
4
|
|
|
3
5
|
UIport exports a rendered section or a selected whole page. It does not reconstruct a complete application backend or crawl a site. A successful capture is not a general proof of fidelity.
|
|
4
6
|
|
|
@@ -11,7 +13,7 @@ UIport exports a rendered section or a selected whole page. It does not reconstr
|
|
|
11
13
|
| SVG fragments | Preserved | Hash stays on local URL, e.g. `assets/…svg#shape` |
|
|
12
14
|
| Hover/focus and CSS animations | Original CSS preserved | Example states and animations exercised by integration tests |
|
|
13
15
|
| Web Animations API | Observed keyframes/timing on DocumentTimeline | Paused/infinite timing tested; does not reconstruct triggering events |
|
|
14
|
-
| Open Shadow DOM | Partial | Declarative shadow tree and inline/adopted styles; simple local fixture covered |
|
|
16
|
+
| Open Shadow DOM | Partial | Declarative shadow tree and inline/adopted styles; simple local fixture covered. The selector must match an element of the light DOM: shadow content is captured when its host is inside the selection, but a root inside a shadow tree is not resolved |
|
|
15
17
|
| Source scripts, handlers and visual libraries | Preserved as in the prototype; capture --omit-scripts opts out | Scripts in the selection and recognized visual libraries are copied; initialization outside the selection, module dependencies and arbitrary listeners still need review. Preserved source code reports SOURCE_RUNTIME_UNVERIFIED |
|
|
16
18
|
| Canvas | Static readable frame only | An unreadable frame is reported; no dynamic WebGL guarantee |
|
|
17
19
|
| Iframes, object/embed | Disabled | Embedded documents are not extracted or allowed to run automatically |
|
|
@@ -36,13 +38,17 @@ Existing prototype exports are accepted by their legacy root marker; validate do
|
|
|
36
38
|
- Viewports: 1–8, dimensions 200–3840 pixels. Screenshot comparisons capped at 20 megapixels.
|
|
37
39
|
- Total operation: default 120 seconds, configurable 1–600 seconds. The deadline also covers browser startup; cancellation closes the owned browser process tree. Process cleanup can add a short shutdown interval. Source navigation is bounded; resource fetches have up to 15 seconds each.
|
|
38
40
|
- Lazy scroll: default 80 steps, configurable 1–1000. `SCROLL_LIMIT` means content may remain unloaded.
|
|
41
|
+
- The selected root must render something at the captured viewport. A root that displays nothing — hidden, without a box of its own, or fully transparent — is reported as a partial result instead of failing the capture, and validation refuses it with an actionable message instead of waiting for a screenshot that can never succeed.
|
|
39
42
|
- Export resource budget: default 20 MiB/file, 100 MiB total; controls downloaded copies, not source browser memory. Successful responses from the fresh capture context are reused, including Referer-dependent resources. Retention has the same per-file/aggregate budgets, but Playwright materializes response bodies before actual-size validation; peak memory is not bounded by these budgets. All referenced CSS resources may be retained, including resources unused by the selected DOM, because CSS is conservative.
|
|
43
|
+
- Resources are downloaded concurrently, with at most eight transfers at a time. The per-file and total budgets are shared by those transfers, so a section that references many assets does not exceed the total budget. The same URL is downloaded once even when several declarations reference it. The result reports `downloadedBytes`, the bytes read from the network, and `budgetBytes`, the bytes charged against the total budget; the charged amount never exceeds the limit, while the read amount can exceed it by the chunk that the limit refused.
|
|
40
44
|
- Public HTTP(S) only; no session/cookie import. Local development URLs are supported. The capture reuses its own navigation responses; fallback fetch does not import browser cookies.
|
|
41
45
|
- Source JavaScript executes in the capture browser. The optional --omit-scripts mode is not a general-purpose sanitizer or sandbox for hostile websites.
|
|
42
46
|
- Source style values and content remain in the HTML. Review artifacts before redistribution. The CLI redacts URL credentials, queries and fragments in resource diagnostics and operational errors and does not print source page content or form values.
|
|
43
47
|
- Network/rendering differences, DOM changed by runtime, special CSS/HTML features and states not observed can still require manual work. No invented replacement effects.
|
|
44
48
|
|
|
45
|
-
Common partial-result codes: `SOURCE_RUNTIME_UNVERIFIED`, `SOURCE_RUNTIME_OMITTED`, `RESOURCE_UNAVAILABLE`, `STYLESHEET_UNAVAILABLE`, `SCROLL_LIMIT`, `RESPONSIVE_DOM_CHANGED`, `CANVAS_STATIC`, `CANVAS_UNREADABLE`, `EMBED_OMITTED`, `ANIMATION_UNSUPPORTED`, `SOURCE_REQUEST_FAILED`, `SOURCE_SCRIPT_ERROR`, `CSS_IMPORT_CYCLE`, `CSS_IMPORT_UNSUPPORTED`.
|
|
49
|
+
Common partial-result codes: `SOURCE_RUNTIME_UNVERIFIED`, `SOURCE_RUNTIME_OMITTED`, `RESOURCE_UNAVAILABLE`, `INVALID_RESOURCE_URL`, `STYLESHEET_UNAVAILABLE`, `SRCSET_INVALID`, `SCROLL_LIMIT`, `RESPONSIVE_DOM_CHANGED`, `SECTION_NOT_VISIBLE`, `SECTION_EMPTY_AREA`, `CANVAS_STATIC`, `CANVAS_UNREADABLE`, `EMBED_OMITTED`, `ANIMATION_UNSUPPORTED`, `SOURCE_REQUEST_FAILED`, `SOURCE_SCRIPT_ERROR`, `CSS_IMPORT_CYCLE`, `CSS_IMPORT_UNSUPPORTED`.
|
|
50
|
+
|
|
51
|
+
`SECTION_NOT_VISIBLE` and `SECTION_EMPTY_AREA` mean the selected root does not render at that viewport: its markup is still exported, but it displays nothing. Choose a selector that matches a visible element, or capture the whole page with `body`. `SRCSET_INVALID` means a `srcset` descriptor list could not be parsed; the original value is preserved unchanged instead of being dropped, so check which image the browser picks. `INVALID_RESOURCE_URL` means a resource URL could not be resolved and was left as it was.
|
|
46
52
|
|
|
47
53
|
## Supported environments
|
|
48
54
|
|
package/package.json
CHANGED
package/scripts/capture.mjs
CHANGED
|
@@ -2,8 +2,8 @@ import fs from "node:fs/promises";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { chromium } from "playwright-core";
|
|
4
4
|
import { parseFragment, serialize } from "parse5";
|
|
5
|
-
import
|
|
6
|
-
import {
|
|
5
|
+
import { extractSection, measureRoot } from "./dom.mjs";
|
|
6
|
+
import { parseSrcsetAttribute } from "./srcset.mjs";
|
|
7
7
|
import { resources } from "./resources.mjs";
|
|
8
8
|
import { browserResources } from "./browser-resources.mjs";
|
|
9
9
|
import { contextualCss } from "./css-context.mjs";
|
|
@@ -91,7 +91,23 @@ export async function capture(options) {
|
|
|
91
91
|
throw new Error(
|
|
92
92
|
`Selector must resolve to exactly one element; found ${count}`,
|
|
93
93
|
);
|
|
94
|
-
|
|
94
|
+
// A root that does not render is reported instead of waiting for a
|
|
95
|
+
// screenshot that can never succeed. The locator is used for the
|
|
96
|
+
// measurement so that a root inside an open shadow tree is found.
|
|
97
|
+
const rendered = await root.evaluate(measureRoot);
|
|
98
|
+
if (rendered.hidden)
|
|
99
|
+
limitation(
|
|
100
|
+
limitations,
|
|
101
|
+
"SECTION_NOT_VISIBLE",
|
|
102
|
+
`The selected root is hidden at ${viewport.name}; its markup is exported but displays nothing`,
|
|
103
|
+
);
|
|
104
|
+
else if (!rendered.visible)
|
|
105
|
+
limitation(
|
|
106
|
+
limitations,
|
|
107
|
+
"SECTION_EMPTY_AREA",
|
|
108
|
+
`The selected root has no rendered size at ${viewport.name}; its markup is exported but displays nothing`,
|
|
109
|
+
);
|
|
110
|
+
else await root.scrollIntoViewIfNeeded();
|
|
95
111
|
const snapshot = await page.evaluate(extractSection, {
|
|
96
112
|
selector,
|
|
97
113
|
omitScripts: options.omitScripts,
|
|
@@ -184,7 +200,30 @@ export async function capture(options) {
|
|
|
184
200
|
})
|
|
185
201
|
.join("\n");
|
|
186
202
|
const head = parseFragment(runtimeHtml + primary.headHtml);
|
|
187
|
-
|
|
203
|
+
// Every referenced resource is localized concurrently and the document is
|
|
204
|
+
// assembled once all of them are known. The download pool inside the
|
|
205
|
+
// resource layer bounds how many transfers run at the same time.
|
|
206
|
+
const pending = [];
|
|
207
|
+
const localizeSrcset = async (value) => {
|
|
208
|
+
const parsed = parseSrcsetAttribute(value);
|
|
209
|
+
if (!parsed.length && value.trim()) {
|
|
210
|
+
// An unparsable descriptor list is preserved unchanged: dropping it
|
|
211
|
+
// would silently change which image the browser picks.
|
|
212
|
+
limitation(
|
|
213
|
+
limitations,
|
|
214
|
+
"SRCSET_INVALID",
|
|
215
|
+
"A srcset attribute could not be parsed and was preserved unchanged",
|
|
216
|
+
);
|
|
217
|
+
return value;
|
|
218
|
+
}
|
|
219
|
+
const candidates = [];
|
|
220
|
+
for (const item of parsed)
|
|
221
|
+
candidates.push(
|
|
222
|
+
`${await assets.localize(item.url, primary.baseUrl)}${item.w ? ` ${item.w}w` : item.d ? ` ${item.d}x` : ""}`,
|
|
223
|
+
);
|
|
224
|
+
return candidates.join(", ");
|
|
225
|
+
};
|
|
226
|
+
function rewrite(node) {
|
|
188
227
|
if (node.attrs) {
|
|
189
228
|
for (const attr of node.attrs) {
|
|
190
229
|
if (
|
|
@@ -193,37 +232,69 @@ export async function capture(options) {
|
|
|
193
232
|
) ||
|
|
194
233
|
(["use", "image"].includes(node.tagName) &&
|
|
195
234
|
["href", "xlink:href"].includes(attr.name))
|
|
196
|
-
)
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
235
|
+
) {
|
|
236
|
+
const original = attr.value;
|
|
237
|
+
pending.push(
|
|
238
|
+
assets
|
|
239
|
+
.localize(
|
|
240
|
+
original,
|
|
241
|
+
primary.baseUrl,
|
|
242
|
+
node.tagName === "script" && attr.name === "src"
|
|
243
|
+
? "script"
|
|
244
|
+
: undefined,
|
|
245
|
+
)
|
|
246
|
+
.then((value) => {
|
|
247
|
+
attr.value = value;
|
|
248
|
+
}),
|
|
203
249
|
);
|
|
250
|
+
}
|
|
204
251
|
if (attr.name === "srcset") {
|
|
205
|
-
const
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
)
|
|
210
|
-
|
|
252
|
+
const original = attr.value;
|
|
253
|
+
pending.push(
|
|
254
|
+
localizeSrcset(original).then((value) => {
|
|
255
|
+
attr.value = value;
|
|
256
|
+
}),
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
if (attr.name === "style") {
|
|
260
|
+
const original = attr.value;
|
|
261
|
+
pending.push(
|
|
262
|
+
assets.cssValue(original, primary.baseUrl).then((value) => {
|
|
263
|
+
attr.value = value;
|
|
264
|
+
}),
|
|
265
|
+
);
|
|
211
266
|
}
|
|
212
|
-
if (attr.name === "style")
|
|
213
|
-
attr.value = await assets.cssValue(attr.value, primary.baseUrl);
|
|
214
267
|
}
|
|
215
268
|
}
|
|
216
269
|
if (node.tagName === "style")
|
|
217
270
|
for (const child of node.childNodes || [])
|
|
218
|
-
if (child.nodeName === "#text")
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
271
|
+
if (child.nodeName === "#text") {
|
|
272
|
+
const original = child.value;
|
|
273
|
+
pending.push(
|
|
274
|
+
assets.css(original, primary.baseUrl).then((value) => {
|
|
275
|
+
child.value = value;
|
|
276
|
+
}),
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
for (const child of node.childNodes || []) rewrite(child);
|
|
280
|
+
if (node.content) rewrite(node.content);
|
|
222
281
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
282
|
+
rewrite(fragment);
|
|
283
|
+
rewrite(head);
|
|
284
|
+
rewrite({ attrs: primary.htmlAttributes });
|
|
285
|
+
rewrite({ attrs: primary.bodyAttributes });
|
|
286
|
+
// Every pending localization settles before the document is assembled. A
|
|
287
|
+
// cancellation must not leave sibling rejections unhandled.
|
|
288
|
+
const settled = await Promise.allSettled(pending);
|
|
289
|
+
const failure = settled.find((entry) => entry.status === "rejected");
|
|
290
|
+
if (failure) throw failure.reason;
|
|
291
|
+
// Resources are localized concurrently, so the order in which problems
|
|
292
|
+
// are observed is not stable. Sorting keeps the reported result
|
|
293
|
+
// reproducible from one run to the next and from one machine to another.
|
|
294
|
+
const compare = (x, y) => (x < y ? -1 : x > y ? 1 : 0);
|
|
295
|
+
limitations.sort(
|
|
296
|
+
(a, b) => compare(a.code, b.code) || compare(a.message, b.message),
|
|
297
|
+
);
|
|
227
298
|
// Context-dependent custom properties retain their original conditions;
|
|
228
299
|
// ordinary inherited/responsive variables are never frozen to one viewport.
|
|
229
300
|
const animations = primary.animations.filter(
|
package/scripts/css-context.mjs
CHANGED
|
@@ -106,15 +106,23 @@ export function contextualCss(stylesheets) {
|
|
|
106
106
|
flush();
|
|
107
107
|
}
|
|
108
108
|
for (const root of roots) visit(root, null);
|
|
109
|
+
// The index is keyed by rule and selector so that rendering does not
|
|
110
|
+
// rescan every observation for each selector.
|
|
109
111
|
const missing = new Map();
|
|
112
|
+
const observations = new Map();
|
|
110
113
|
return {
|
|
111
114
|
async observe(page, snapshot) {
|
|
112
115
|
const result = await page.evaluate(missingSelectors, {
|
|
113
116
|
snapshot,
|
|
114
117
|
rules: descriptors,
|
|
115
118
|
});
|
|
116
|
-
for (const item of result)
|
|
119
|
+
for (const item of result) {
|
|
117
120
|
missing.set(`${item.rule}|${item.selector}|${item.id}`, item);
|
|
121
|
+
const key = `${item.rule}|${item.selector}`;
|
|
122
|
+
const ids = observations.get(key) || new Set();
|
|
123
|
+
ids.add(item.id);
|
|
124
|
+
observations.set(key, ids);
|
|
125
|
+
}
|
|
118
126
|
},
|
|
119
127
|
render() {
|
|
120
128
|
const anchorFor = (container) => {
|
|
@@ -139,11 +147,9 @@ export function contextualCss(stylesheets) {
|
|
|
139
147
|
const anchor = anchorFor(original);
|
|
140
148
|
if (!affected.has(anchor)) continue;
|
|
141
149
|
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(", ")}))`
|
|
150
|
+
const ids = observations.get(`${id}|${selector}`);
|
|
151
|
+
return ids?.size
|
|
152
|
+
? `:is(${selector}, :where(${[...ids].map((elementId) => `[data-uiport-id="${elementId}"]`).join(", ")}))`
|
|
147
153
|
: selector;
|
|
148
154
|
});
|
|
149
155
|
let fallback = postcss.rule({ selector: selectors.join(", ") });
|
package/scripts/dom.mjs
CHANGED
|
@@ -1,4 +1,49 @@
|
|
|
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,
|
|
@@ -204,85 +249,6 @@ export function extractSection({
|
|
|
204
249
|
ancestor = ancestor.parentElement;
|
|
205
250
|
}
|
|
206
251
|
|
|
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
252
|
const stylesheets = [
|
|
287
253
|
...document.styleSheets,
|
|
288
254
|
...document.adoptedStyleSheets,
|
|
@@ -304,13 +270,6 @@ export function extractSection({
|
|
|
304
270
|
};
|
|
305
271
|
});
|
|
306
272
|
|
|
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
273
|
const animations = [];
|
|
315
274
|
const seen = new Set();
|
|
316
275
|
for (const element of deepElements) {
|
|
@@ -395,10 +354,7 @@ export function extractSection({
|
|
|
395
354
|
(attribute) => attribute.name !== "lang",
|
|
396
355
|
),
|
|
397
356
|
bodyAttributes: attributesOf(document.body),
|
|
398
|
-
references,
|
|
399
|
-
usedFontFamilies: [...usedFontFamilies],
|
|
400
357
|
stylesheets,
|
|
401
|
-
customProperties,
|
|
402
358
|
animations,
|
|
403
359
|
featureCounts: {
|
|
404
360
|
elements: deepElements.length,
|
package/scripts/lib.mjs
CHANGED
|
@@ -147,6 +147,10 @@ export async function stageOutput(directory) {
|
|
|
147
147
|
|
|
148
148
|
export async function waitForPageStable(page, settleMs) {
|
|
149
149
|
await page.waitForLoadState("domcontentloaded");
|
|
150
|
+
// The two waits keep their own budget: the network idle window first, then
|
|
151
|
+
// the fonts and decoded images. Sharing one budget would start the capture
|
|
152
|
+
// while a slow image is still loading, which the export — served locally —
|
|
153
|
+
// would not show, producing a false visual difference.
|
|
150
154
|
await page.waitForLoadState("networkidle", { timeout: 2000 }).catch(() => {});
|
|
151
155
|
await page.evaluate(async () => {
|
|
152
156
|
await Promise.race([
|
package/scripts/resources.mjs
CHANGED
|
@@ -20,81 +20,119 @@ export function resources(
|
|
|
20
20
|
limitations,
|
|
21
21
|
browserCache,
|
|
22
22
|
) {
|
|
23
|
+
// A pending download is stored as its promise so that concurrent requests
|
|
24
|
+
// for the same URL share one transfer.
|
|
23
25
|
const downloaded = new Map();
|
|
26
|
+
const localized = new Map();
|
|
27
|
+
const written = new Map();
|
|
24
28
|
let consumed = 0;
|
|
25
29
|
const localPaths = new Set();
|
|
30
|
+
const maxConcurrentDownloads = 8;
|
|
31
|
+
let activeDownloads = 0;
|
|
32
|
+
const waitingDownloads = [];
|
|
33
|
+
// Bytes read from the network, and bytes charged against the total budget.
|
|
34
|
+
// The charge happens before the bytes are retained, so concurrent transfers
|
|
35
|
+
// cannot pass the limit together; the reported download size stays the
|
|
36
|
+
// amount actually received.
|
|
37
|
+
let received = 0;
|
|
38
|
+
function consume(bytes) {
|
|
39
|
+
received += bytes;
|
|
40
|
+
if (consumed + bytes > options.maxTotalBytes)
|
|
41
|
+
throw new Error("Resource size limit exceeded");
|
|
42
|
+
consumed += bytes;
|
|
43
|
+
}
|
|
44
|
+
async function acquireDownloadSlot() {
|
|
45
|
+
if (activeDownloads < maxConcurrentDownloads) {
|
|
46
|
+
activeDownloads++;
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
await new Promise((resolve) => waitingDownloads.push(resolve));
|
|
50
|
+
}
|
|
51
|
+
function releaseDownloadSlot() {
|
|
52
|
+
const next = waitingDownloads.shift();
|
|
53
|
+
if (next) next();
|
|
54
|
+
else activeDownloads--;
|
|
55
|
+
}
|
|
26
56
|
/** @param {string} input */
|
|
27
57
|
async function download(input) {
|
|
28
58
|
const url = normalizeUrl(input);
|
|
29
59
|
if (downloaded.has(url)) return downloaded.get(url);
|
|
30
60
|
if (!/^https?:/i.test(url)) return null;
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
if (
|
|
38
|
-
cached.body.length > options.maxResourceBytes
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
61
|
+
const pending = (async () => {
|
|
62
|
+
let response;
|
|
63
|
+
try {
|
|
64
|
+
if (consumed >= options.maxTotalBytes)
|
|
65
|
+
throw new Error("Total resource budget exceeded");
|
|
66
|
+
const cached = await browserCache?.get(url);
|
|
67
|
+
if (cached) {
|
|
68
|
+
if (cached.body.length > options.maxResourceBytes)
|
|
69
|
+
throw new Error("Resource size limit exceeded");
|
|
70
|
+
consume(cached.body.length);
|
|
71
|
+
return cached;
|
|
72
|
+
}
|
|
73
|
+
await acquireDownloadSlot();
|
|
74
|
+
try {
|
|
75
|
+
response = await fetch(url, {
|
|
76
|
+
signal: AbortSignal.any([
|
|
77
|
+
signal,
|
|
78
|
+
AbortSignal.timeout(Math.min(options.timeoutMs, 15000)),
|
|
79
|
+
]),
|
|
80
|
+
headers: { "user-agent": "UIport/0.1" },
|
|
81
|
+
});
|
|
82
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
83
|
+
const length = Number(response.headers.get("content-length") || 0);
|
|
84
|
+
if (
|
|
85
|
+
length > options.maxResourceBytes ||
|
|
86
|
+
length + consumed > options.maxTotalBytes
|
|
87
|
+
)
|
|
88
|
+
throw new Error("Resource size limit exceeded");
|
|
89
|
+
const chunks = [];
|
|
90
|
+
let size = 0;
|
|
91
|
+
for await (const chunk of /** @type {any} */ (response.body)) {
|
|
92
|
+
size += chunk.length;
|
|
93
|
+
consume(chunk.length);
|
|
94
|
+
if (size > options.maxResourceBytes)
|
|
95
|
+
throw new Error("Resource size limit exceeded");
|
|
96
|
+
chunks.push(chunk);
|
|
97
|
+
}
|
|
98
|
+
const resource = {
|
|
99
|
+
body: Buffer.concat(chunks),
|
|
100
|
+
contentType: response.headers.get("content-type") || "",
|
|
101
|
+
url: response.url || url,
|
|
102
|
+
};
|
|
103
|
+
return resource;
|
|
104
|
+
} finally {
|
|
105
|
+
releaseDownloadSlot();
|
|
106
|
+
}
|
|
107
|
+
} catch (error) {
|
|
108
|
+
signal.throwIfAborted();
|
|
109
|
+
limitation(
|
|
110
|
+
limitations,
|
|
111
|
+
"RESOURCE_UNAVAILABLE",
|
|
112
|
+
`${redactedUrl(url)}: ${safeErrorMessage(error)}`,
|
|
113
|
+
);
|
|
114
|
+
return null;
|
|
115
|
+
} finally {
|
|
116
|
+
if (response?.body && !response.body.locked)
|
|
117
|
+
await response.body.cancel().catch(() => {});
|
|
68
118
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
url: response.url || url,
|
|
73
|
-
};
|
|
74
|
-
downloaded.set(url, resource);
|
|
75
|
-
return resource;
|
|
76
|
-
} catch (error) {
|
|
77
|
-
signal.throwIfAborted();
|
|
78
|
-
limitation(
|
|
79
|
-
limitations,
|
|
80
|
-
"RESOURCE_UNAVAILABLE",
|
|
81
|
-
`${redactedUrl(url)}: ${safeErrorMessage(error)}`,
|
|
82
|
-
);
|
|
83
|
-
downloaded.set(url, null);
|
|
84
|
-
return null;
|
|
85
|
-
} finally {
|
|
86
|
-
if (response?.body && !response.body.locked)
|
|
87
|
-
await response.body.cancel().catch(() => {});
|
|
88
|
-
}
|
|
119
|
+
})();
|
|
120
|
+
downloaded.set(url, pending);
|
|
121
|
+
return pending;
|
|
89
122
|
}
|
|
90
123
|
/** @param {string} raw @param {string} base @param {string} [usage] */
|
|
91
124
|
async function localize(raw, base, usage) {
|
|
92
|
-
if (
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
)
|
|
97
|
-
|
|
125
|
+
if (!raw || /^(data:|#)/i.test(raw)) return raw;
|
|
126
|
+
// The usage decides the file extension, so it belongs to the key.
|
|
127
|
+
const key = `${base}|${raw}|${usage || ""}`;
|
|
128
|
+
if (localized.has(key)) return localized.get(key);
|
|
129
|
+
const pending = localizeResource(raw, base, usage);
|
|
130
|
+
localized.set(key, pending);
|
|
131
|
+
return pending;
|
|
132
|
+
}
|
|
133
|
+
/** @param {string} raw @param {string} base @param {string} [usage] */
|
|
134
|
+
async function localizeResource(raw, base, usage) {
|
|
135
|
+
if (localPaths.has(raw.split("#")[0].replace(/^\.\//, ""))) return raw;
|
|
98
136
|
let url;
|
|
99
137
|
try {
|
|
100
138
|
url = new URL(raw, base);
|
|
@@ -123,14 +161,22 @@ export function resources(
|
|
|
123
161
|
)
|
|
124
162
|
extension = ".js";
|
|
125
163
|
const file = `assets/${sha256(resource.body).slice(0, 24)}${extension}`;
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
164
|
+
// Two different URLs can carry the same bytes and therefore the same file
|
|
165
|
+
// name. One shared write keeps the file intact, and every caller waits
|
|
166
|
+
// for that write before the export is assembled.
|
|
167
|
+
if (!written.has(file))
|
|
168
|
+
written.set(
|
|
169
|
+
file,
|
|
170
|
+
fs.writeFile(path.join(directory, file), resource.body),
|
|
171
|
+
);
|
|
172
|
+
await written.get(file);
|
|
173
|
+
localPaths.add(file);
|
|
130
174
|
return `./${file}${url.hash}`;
|
|
131
175
|
}
|
|
132
176
|
/** @param {string} value @param {string} base */
|
|
133
177
|
async function cssValue(value, base) {
|
|
178
|
+
// Most declarations carry no URL at all: parsing them is wasted work.
|
|
179
|
+
if (!/url\(|image-set\(/i.test(value)) return value;
|
|
134
180
|
const parsed = valueParser(value);
|
|
135
181
|
const nodes = [];
|
|
136
182
|
parsed.walk((node) => {
|
|
@@ -245,8 +291,18 @@ export function resources(
|
|
|
245
291
|
rule.replaceWith(postcss.parse(body).nodes);
|
|
246
292
|
}
|
|
247
293
|
// Imported declarations have already been rewritten against their own base.
|
|
248
|
-
|
|
249
|
-
|
|
294
|
+
// Each declaration is independent, so the resources they reference are
|
|
295
|
+
// localized concurrently. A cancellation must not leave sibling
|
|
296
|
+
// rejections unhandled.
|
|
297
|
+
const rewritten = await Promise.allSettled(
|
|
298
|
+
declarations.map((decl) =>
|
|
299
|
+
cssValue(decl.value, base).then((value) => {
|
|
300
|
+
decl.value = value;
|
|
301
|
+
}),
|
|
302
|
+
),
|
|
303
|
+
);
|
|
304
|
+
const failure = rewritten.find((entry) => entry.status === "rejected");
|
|
305
|
+
if (failure) throw failure.reason;
|
|
250
306
|
root.walkComments((comment) => {
|
|
251
307
|
if (/sourceMappingURL/.test(comment.text)) comment.remove();
|
|
252
308
|
});
|
|
@@ -260,6 +316,10 @@ export function resources(
|
|
|
260
316
|
localize,
|
|
261
317
|
css,
|
|
262
318
|
cssValue,
|
|
263
|
-
stats: () => ({
|
|
319
|
+
stats: () => ({
|
|
320
|
+
assets: localPaths.size,
|
|
321
|
+
downloadedBytes: received,
|
|
322
|
+
budgetBytes: consumed,
|
|
323
|
+
}),
|
|
264
324
|
};
|
|
265
325
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import parseSrcset from "parse-srcset";
|
|
2
|
+
|
|
3
|
+
// parse-srcset reports invalid descriptors through console.log. That would
|
|
4
|
+
// print source page content and break the one-document stdout contract, so
|
|
5
|
+
// the diagnostic is suppressed here and reported by the caller instead.
|
|
6
|
+
export function parseSrcsetAttribute(value) {
|
|
7
|
+
const log = console.log;
|
|
8
|
+
console.log = () => {};
|
|
9
|
+
try {
|
|
10
|
+
return parseSrcset(value);
|
|
11
|
+
} finally {
|
|
12
|
+
console.log = log;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Route whatever is written to stdout to another stream while the returned
|
|
2
|
+
// function has not been called. A capture or a validation writes exactly one
|
|
3
|
+
// JSON document to stdout, and the document itself is written after the
|
|
4
|
+
// restore. This is the safety net for the output contract; the diagnostics of
|
|
5
|
+
// the source are suppressed where they are produced.
|
|
6
|
+
export function guardStdout(target = process.stderr) {
|
|
7
|
+
const original = process.stdout.write;
|
|
8
|
+
process.stdout.write = (chunk, encoding, callback) =>
|
|
9
|
+
target.write(chunk, encoding, callback);
|
|
10
|
+
return () => {
|
|
11
|
+
process.stdout.write = original;
|
|
12
|
+
};
|
|
13
|
+
}
|
package/scripts/validate.mjs
CHANGED
|
@@ -12,25 +12,23 @@ import {
|
|
|
12
12
|
startStaticServer,
|
|
13
13
|
waitForPageStable,
|
|
14
14
|
} from "./lib.mjs";
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
function copy(source, destination) {
|
|
15
|
+
// Copy a decoded PNG into a buffer of the comparison size, padding the rows
|
|
16
|
+
// that the source does not cover with transparent pixels. The copy happens one
|
|
17
|
+
// row at a time: a per-pixel copy costs one Buffer.copy call per pixel.
|
|
18
|
+
function copy(source, destination, width) {
|
|
19
|
+
const bytesPerPixel = 4;
|
|
20
|
+
const rowBytes = source.width * bytesPerPixel;
|
|
22
21
|
for (let y = 0; y < source.height; y += 1) {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
);
|
|
32
|
-
}
|
|
22
|
+
const sourceStart = y * rowBytes;
|
|
23
|
+
const destinationStart = y * width * bytesPerPixel;
|
|
24
|
+
source.data.copy(
|
|
25
|
+
destination,
|
|
26
|
+
destinationStart,
|
|
27
|
+
sourceStart,
|
|
28
|
+
sourceStart + rowBytes,
|
|
29
|
+
);
|
|
33
30
|
}
|
|
31
|
+
return destination;
|
|
34
32
|
}
|
|
35
33
|
|
|
36
34
|
export async function validate(options) {
|
|
@@ -73,9 +71,13 @@ export async function validate(options) {
|
|
|
73
71
|
if ((await root.count()) !== 1)
|
|
74
72
|
throw new Error("Source selector is missing or ambiguous");
|
|
75
73
|
const box = await root.boundingBox();
|
|
76
|
-
if (!box || box.width
|
|
74
|
+
if (!box || box.width <= 0 || box.height <= 0)
|
|
75
|
+
throw new Error(
|
|
76
|
+
"The source selector does not render a visible box; choose a selector that matches a visible element",
|
|
77
|
+
);
|
|
78
|
+
if (box.width * box.height > 20_000_000)
|
|
77
79
|
throw new Error(
|
|
78
|
-
"Source section
|
|
80
|
+
"Source section exceeds the 20 megapixel screenshot limit",
|
|
79
81
|
);
|
|
80
82
|
const sourceBuffer = await root.screenshot({
|
|
81
83
|
animations: "disabled",
|
|
@@ -131,7 +133,11 @@ export async function validate(options) {
|
|
|
131
133
|
if ((await localRoot.count()) !== 1)
|
|
132
134
|
throw new Error("UIport extraction root is missing or ambiguous");
|
|
133
135
|
const localBox = await localRoot.boundingBox();
|
|
134
|
-
if (!localBox || localBox.width
|
|
136
|
+
if (!localBox || localBox.width <= 0 || localBox.height <= 0)
|
|
137
|
+
throw new Error(
|
|
138
|
+
"The exported section does not render a visible box; the capture may have exported a hidden or empty root",
|
|
139
|
+
);
|
|
140
|
+
if (localBox.width * localBox.height > 20_000_000)
|
|
135
141
|
throw new Error("Exported section exceeds screenshot limit");
|
|
136
142
|
const localBuffer = await localRoot.screenshot({
|
|
137
143
|
animations: "disabled",
|
|
@@ -143,18 +149,23 @@ export async function validate(options) {
|
|
|
143
149
|
height = Math.max(sourcePng.height, localPng.height);
|
|
144
150
|
if (width * height > 20_000_000)
|
|
145
151
|
throw new Error("Comparison exceeds screenshot limit");
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
152
|
+
// When both sides have the same size their decoded pixels are already
|
|
153
|
+
// the comparison buffer: no padding copy is needed.
|
|
154
|
+
const sameSize =
|
|
155
|
+
sourcePng.width === localPng.width &&
|
|
156
|
+
sourcePng.height === localPng.height;
|
|
157
|
+
let left, right;
|
|
158
|
+
if (sameSize) {
|
|
159
|
+
left = sourcePng.data;
|
|
160
|
+
right = localPng.data;
|
|
161
|
+
} else {
|
|
162
|
+
left = copy(sourcePng, new Uint8Array(width * height * 4), width);
|
|
163
|
+
right = copy(localPng, new Uint8Array(width * height * 4), width);
|
|
164
|
+
}
|
|
165
|
+
const differentPixels = pixelmatch(left, right, null, width, height, {
|
|
166
|
+
threshold: 0.1,
|
|
167
|
+
includeAA: false,
|
|
168
|
+
});
|
|
158
169
|
const differenceRatio = differentPixels / (width * height);
|
|
159
170
|
const dimensionsMatch =
|
|
160
171
|
sourcePng.width === localPng.width &&
|
package/skills/uiport/SKILL.md
CHANGED
|
@@ -7,8 +7,8 @@ description: Capture a rendered web section as editable HTML, original CSS and l
|
|
|
7
7
|
|
|
8
8
|
Use for a request to extract an existing web section into local files. Use pages the user owns or has permission to reuse. Do not redesign or invent replacement effects.
|
|
9
9
|
|
|
10
|
-
1. Inspect the requested URL and choose one CSS selector matching a section container, or body/html for a full page. Include wrappers/decorations that belong to it; html also includes original head scripts.
|
|
11
|
-
2. Use the installed CLI or source checkout. `npx uiport@0.1.
|
|
10
|
+
1. Inspect the requested URL and choose one CSS selector matching a section container, or body/html for a full page. Include wrappers/decorations that belong to it; html also includes original head scripts. The selected root must render something at the captured viewport: a root that displays nothing is reported as a partial result.
|
|
11
|
+
2. Use the installed CLI or source checkout. `npx uiport@0.1.2` is the pinned form. When testing an unpublished version, use `node bin/cli.mjs` from its checkout.
|
|
12
12
|
3. If needed, install the matching browser with `uiport browser install`. No browser download is hidden inside capture.
|
|
13
13
|
4. Run `uiport capture --url "URL" --selector "SELECTOR" --out "NEW_DIRECTORY" --json`. The default locale is pt-BR. Match locale/color scheme/viewports to the requested source. Never overwrite an existing nonempty directory.
|
|
14
14
|
5. Read the result. Exit 0 means no known reported limitations, not universal fidelity. Exit 2 means a partial artifact exists; inspect every limitation. Exit 1 means failure. Stdout is JSON, progress is stderr.
|
package/uiport.md
CHANGED
|
@@ -37,7 +37,7 @@ O objetivo da revisão manual é manter somente os assets necessários à seçã
|
|
|
37
37
|
- Abra a URL em navegador com JavaScript habilitado.
|
|
38
38
|
- Aguarde DOM, rede, fontes e imagens estabilizarem dentro de um prazo limitado; não espere indefinidamente por páginas com atividade contínua.
|
|
39
39
|
- Role a página para ativar lazy loading e efeitos de entrada. Inspecione o diagnóstico se o limite de rolagem for atingido.
|
|
40
|
-
- Localize uma única raiz que contenha toda a seção, incluindo elementos decorativos, overlays e backgrounds. O seletor deve encontrar uma única raiz. Use um container para uma seção, `body` para a página visível inteira ou `html` para incluir também os scripts do head; não se trata de crawling de múltiplas páginas.
|
|
40
|
+
- Localize uma única raiz que contenha toda a seção, incluindo elementos decorativos, overlays e backgrounds. O seletor deve encontrar uma única raiz, e essa raiz precisa renderizar no viewport capturado. Use um container para uma seção, `body` para a página visível inteira ou `html` para incluir também os scripts do head; não se trata de crawling de múltiplas páginas.
|
|
41
41
|
- Observe o estado inicial e todas as interações relevantes: entrada, scroll, hover, foco, tabs, accordion, carousel e mousemove.
|
|
42
42
|
- Compare os tamanhos de tela necessários e mantenha viewport, idioma e tema consistentes entre captura e validação.
|
|
43
43
|
|
|
@@ -75,7 +75,7 @@ O objetivo da revisão manual é manter somente os assets necessários à seçã
|
|
|
75
75
|
|
|
76
76
|
Use a CLI como ponto de partida, não como autorização para entregar um clone quebrado.
|
|
77
77
|
|
|
78
|
-
|
|
78
|
+
Para usar o código-fonte deste repositório em vez do pacote publicado, execute na raiz do repositório:
|
|
79
79
|
|
|
80
80
|
```sh
|
|
81
81
|
npm ci
|
|
@@ -90,7 +90,7 @@ node bin/cli.mjs capture --url "<URL>" --selector "<SELETOR>" --out "./extractio
|
|
|
90
90
|
|
|
91
91
|
Ajuste `--locale`, `--color-scheme` e `--viewports` conforme a origem e use os mesmos valores na validação. A captura não sobrescreve uma pasta existente com conteúdo. `UIPORT_BROWSER_PATH` permite escolher o executável do navegador; a instalação do Chromium é explícita.
|
|
92
92
|
|
|
93
|
-
Os mesmos subcomandos podem ser executados com `npx uiport@0.1.
|
|
93
|
+
Os mesmos subcomandos podem ser executados com `npx uiport@0.1.2` no lugar de `node bin/cli.mjs`. Ao testar uma versão ainda não publicada, use o checkout local. Consulte os [comandos e opções](README.pt-BR.md) ou execute `node bin/cli.mjs --help`.
|
|
94
94
|
|
|
95
95
|
Leia o diagnóstico antes de entregar:
|
|
96
96
|
|
|
@@ -101,6 +101,8 @@ Leia o diagnóstico antes de entregar:
|
|
|
101
101
|
|
|
102
102
|
O idioma padrão permanece `pt-BR`. `capture --omit-scripts` desativa a cópia de scripts da origem e eventos inline; nesse modo, animações WAAPI observadas continuam podendo ser reproduzidas. Sem essa opção, `SOURCE_RUNTIME_UNVERIFIED` pede inspeção do código preservado.
|
|
103
103
|
|
|
104
|
+
A raiz escolhida precisa renderizar no viewport capturado. `SECTION_NOT_VISIBLE` e `SECTION_EMPTY_AREA` significam que o markup foi exportado, mas não exibe nada: corrija o seletor para um elemento visível ou capture a página inteira com `body`. `SRCSET_INVALID` significa que a lista de descritores do `srcset` não pôde ser interpretada; o valor original foi preservado, então confira qual imagem o navegador escolhe.
|
|
105
|
+
|
|
104
106
|
Se houver runtime omitido ou não verificado, recurso não localizado, mudança estrutural responsiva ou canvas dinâmico, investigue a origem antes de concluir.
|
|
105
107
|
|
|
106
108
|
## Validação obrigatória
|