uiport 0.1.3 → 0.1.4
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 +21 -0
- package/README.md +5 -5
- package/README.pt-BR.md +5 -5
- package/bin/cli.mjs +6 -3
- package/docs/support.md +1 -1
- package/package.json +9 -9
- package/scripts/capture.mjs +33 -8
- package/scripts/css-context.mjs +1 -1
- package/scripts/diff.mjs +81 -27
- package/scripts/dom.mjs +44 -28
- package/scripts/errors.mjs +4 -0
- package/scripts/inspect.mjs +23 -10
- package/scripts/lib.mjs +49 -4
- package/scripts/options.mjs +35 -3
- package/scripts/report.mjs +32 -18
- package/scripts/resources.mjs +21 -7
- package/scripts/validate.mjs +26 -11
- package/skills/uiport/SKILL.md +10 -1
- package/uiport.md +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,27 @@ Notable changes are documented here. Versions follow Semantic Versioning.
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.1.4] — 2026-11-29
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
- The browser moves from Chromium 151 to Chromium 159, through the newer version of Playwright. The exported section is the same; a shorthand property may be written in another order by the browser.
|
|
11
|
+
- The visual comparison uses the OKLab distance of the newer pixelmatch, which replaces the previous YIQ measure. The counted pixels of a real screenshot with text differ by about one percent, and the outcome of a comparison does not change.
|
|
12
|
+
- The type check runs on the native TypeScript 7 compiler, and the options of a command now have a declared shape.
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
- The published directory keeps a readable mode. It inherited the private mode of the staging folder, so a web server or another account could not read the export.
|
|
16
|
+
- The comparison of two exports refuses a damaged artifact instead of reading its missing metadata as an artifact without limitations, compares the limitations by code and message, and reports a difference in either direction.
|
|
17
|
+
- The measurement of the selected root walks the whole subtree and reads the text a root holds, so a root that renders through them is no longer reported as displaying nothing.
|
|
18
|
+
- The failures of the comparison carry their own codes, the section is measured before it is rendered, and the two preview servers are closed as soon as they start.
|
|
19
|
+
- A run that is interrupted or that runs out of time reports `TIMEOUT` or `CANCELLED`, even when the browser rejected the pending operation first. Before, the most common timeout arrived as an internal failure.
|
|
20
|
+
- A page that cannot be reached reports `SOURCE_UNREACHABLE`, with the address it could not reach and without its query or fragment.
|
|
21
|
+
- The check of a selector without a capture scrolls the page like the capture does, measures the visibility the same way, and reports the result the capture would give.
|
|
22
|
+
- The readable result of a validation names the reason of the failure — the pixels, the network or the errors of the page — and lists the limitations of the exported section.
|
|
23
|
+
- The inspection refuses a directory that is not an exported section, instead of reading it as one without limitations.
|
|
24
|
+
- The errors of use carry their own code: an unknown color scheme, a fractional scroll step, a browser command without its argument and a missing browser executable.
|
|
25
|
+
- The publication job reads the section of the changelog that belongs to the tag. The tag carries a leading "v" and the section does not, so the job stopped after the package had been published.
|
|
26
|
+
- The dependencies are pinned to the exact versions again. Two installations had left six of them with a range, which lets an install resolve to a version nobody verified.
|
|
27
|
+
|
|
7
28
|
## [0.1.3] — 2026-11-28
|
|
8
29
|
|
|
9
30
|
### Added
|
package/README.md
CHANGED
|
@@ -25,10 +25,10 @@ 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.4 browser install
|
|
29
|
+
npx uiport@0.1.4 capture --url "https://your-site.example" --selector "#hero" --out ./my-section
|
|
30
|
+
npx uiport@0.1.4 serve --dir ./my-section
|
|
31
|
+
npx uiport@0.1.4 validate --url "https://your-site.example" --selector "#hero" --dir ./my-section
|
|
32
32
|
```
|
|
33
33
|
|
|
34
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.
|
|
@@ -81,7 +81,7 @@ Set `UIPORT_BROWSER_PATH` to explicitly choose an executable. Otherwise UIport t
|
|
|
81
81
|
- **Exit 1:** command failed, or validation failed its requested checks.
|
|
82
82
|
- **Validation exit 0:** the observed visual/network checks passed. Behavior remains `not-tested`.
|
|
83
83
|
|
|
84
|
-
Without `--json` the result is a readable summary on stdout; with `--json` it is one JSON document. Progress always goes to stderr. `serve --json` emits one readiness document and stays running until stopped. A script calling capture must handle exit 2, not treat every nonzero exit as “no files”. An existing nonempty output directory is never overwritten. Retained source code is reported as `SOURCE_RUNTIME_UNVERIFIED`: test its interactions; a screenshot match is not proof that all runtime dependencies survived.
|
|
84
|
+
Without `--json` the result is a readable summary on stdout; with `--json` it is one JSON document. Progress always goes to stderr. `inspect` exits 2 when the exported section reports a limitation and 1 when it is missing or damaged. `serve --json` emits one readiness document and stays running until stopped. A script calling capture must handle exit 2, not treat every nonzero exit as “no files”. An existing nonempty output directory is never overwritten. Retained source code is reported as `SOURCE_RUNTIME_UNVERIFIED`: test its interactions; a screenshot match is not proof that all runtime dependencies survived.
|
|
85
85
|
|
|
86
86
|
Validation disables animations for screenshots. It compares pixels with a default 2% difference allowance and up to 5 px height difference; this does not certify hover, clicks, scroll animation or framework state. External requests are **blocked by default** in the exported page, including another localhost port. `--allow-external` opts out of that offline check. Existing prototype exports remain usable with `validate`; its legacy root marker is recognized without rewriting the folder. New exports use UIport markers. Inspect the [support matrix](docs/support.md) before interpreting a passing result.
|
|
87
87
|
|
package/README.pt-BR.md
CHANGED
|
@@ -25,10 +25,10 @@ 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.4 browser install
|
|
29
|
+
npx uiport@0.1.4 capture --url "https://seu-site.example" --selector "#hero" --out ./minha-secao
|
|
30
|
+
npx uiport@0.1.4 serve --dir ./minha-secao
|
|
31
|
+
npx uiport@0.1.4 validate --url "https://seu-site.example" --selector "#hero" --dir ./minha-secao
|
|
32
32
|
```
|
|
33
33
|
|
|
34
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.
|
|
@@ -81,7 +81,7 @@ A captura limita recursos copiados a 20 MiB por arquivo e 100 MiB no total, conf
|
|
|
81
81
|
- **Retorno 1:** falha operacional ou falha das verificações pedidas no validate.
|
|
82
82
|
- **Validate retorna 0:** verificações visuais/de rede passaram nos estados observados. Comportamento continua `not-tested`.
|
|
83
83
|
|
|
84
|
-
Sem `--json` o resultado é um resumo legível no stdout; com `--json` é um único documento JSON. O progresso sempre vai para stderr. `serve --json` emite um único documento de início e permanece ativo até ser encerrado. Automações precisam tratar retorno 2 separadamente. A captura não sobrescreve uma pasta de saída existente com conteúdo. Código de origem preservado gera `SOURCE_RUNTIME_UNVERIFIED`: teste suas interações; igualdade de screenshots não comprova que todas as dependências foram recuperadas.
|
|
84
|
+
Sem `--json` o resultado é um resumo legível no stdout; com `--json` é um único documento JSON. O progresso sempre vai para stderr. O `inspect` termina com 2 quando a seção exportada relata uma limitação e com 1 quando ela falta ou está danificada. `serve --json` emite um único documento de início e permanece ativo até ser encerrado. Automações precisam tratar retorno 2 separadamente. A captura não sobrescreve uma pasta de saída existente com conteúdo. Código de origem preservado gera `SOURCE_RUNTIME_UNVERIFIED`: teste suas interações; igualdade de screenshots não comprova que todas as dependências foram recuperadas.
|
|
85
85
|
|
|
86
86
|
A comparação visual desativa animações, aceita por padrão 2% de diferença de pixels e até 5 px de diferença de altura. Ela não comprova cliques, hover, efeitos de scroll ou estado de framework. Requisições externas da saída são bloqueadas por padrão, inclusive outra porta de localhost. `--allow-external` permite essas requisições e desativa esse teste de funcionamento sem rede externa. O `validate` também reconhece o marcador de extrações do protótipo sem reescrever a pasta; novas extrações usam os marcadores UIport. Consulte os casos suportados em [docs/support.md](docs/support.md).
|
|
87
87
|
|
package/bin/cli.mjs
CHANGED
|
@@ -27,10 +27,11 @@ Capture / validate / diff:
|
|
|
27
27
|
--viewports 1440x900,1024x768,768x1024,375x812
|
|
28
28
|
--wait 1200 Settle time per navigation (ms, 0–60000)
|
|
29
29
|
--timeout 120000 Whole operation deadline (ms, 1000–600000)
|
|
30
|
-
--max-scroll-steps 80 Bounded lazy-loading scroll (1–1000)
|
|
31
30
|
--locale pt-BR Browser locale
|
|
32
31
|
--color-scheme light light | dark
|
|
33
32
|
--json One JSON result on stdout; progress on stderr
|
|
33
|
+
Capture / validate:
|
|
34
|
+
--max-scroll-steps 80 Bounded lazy-loading scroll (1–1000)
|
|
34
35
|
Capture:
|
|
35
36
|
--omit-scripts Omit source scripts and inline event handlers
|
|
36
37
|
--dry-run Check the selector against the page and stop
|
|
@@ -42,6 +43,7 @@ Validate:
|
|
|
42
43
|
|
|
43
44
|
Exit codes: capture 0 = complete, 2 = partial, 1 = error.
|
|
44
45
|
Validate 0 = requested visual/network checks passed, 1 = failed.
|
|
46
|
+
Diff 0 = the exports are the same, 2 = they differ, 1 = error.
|
|
45
47
|
Visual checks do not certify behavior. Use pages you own or have permission to reuse.
|
|
46
48
|
Browser installation is explicit. Set UIPORT_BROWSER_PATH to choose an executable.
|
|
47
49
|
--help and --version work without a browser. Documentation: https://github.com/LorranHippolyte/uiport
|
|
@@ -66,7 +68,7 @@ try {
|
|
|
66
68
|
console.log(args.json ? JSON.stringify({ version }) : version);
|
|
67
69
|
else if (command === "browser") {
|
|
68
70
|
if (argv[1] !== "install")
|
|
69
|
-
throw new
|
|
71
|
+
throw new UiportError("USAGE_INVALID", "Usage: uiport browser install");
|
|
70
72
|
const child = spawn(
|
|
71
73
|
process.execPath,
|
|
72
74
|
[
|
|
@@ -112,7 +114,8 @@ try {
|
|
|
112
114
|
// A capture or a validation writes exactly one JSON document to stdout.
|
|
113
115
|
// The guard is installed before the command module is loaded, so that
|
|
114
116
|
// anything printed while loading also goes to the diagnostics channel.
|
|
115
|
-
const guarded =
|
|
117
|
+
const guarded =
|
|
118
|
+
command === "capture" || command === "validate" || command === "diff";
|
|
116
119
|
const restore = guarded ? guardStdout() : () => {};
|
|
117
120
|
let result;
|
|
118
121
|
try {
|
package/docs/support.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# UIport support matrix
|
|
2
2
|
|
|
3
|
-
This matrix describes the 0.1.x CLI line and was last verified against 0.1.
|
|
3
|
+
This matrix describes the 0.1.x CLI line and was last verified against 0.1.4. It applies to every 0.1.x release unless a row says otherwise.
|
|
4
4
|
|
|
5
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.
|
|
6
6
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "uiport",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"description": "Bring a rendered web section into your next project as editable HTML, CSS and assets.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -62,18 +62,18 @@
|
|
|
62
62
|
},
|
|
63
63
|
"dependencies": {
|
|
64
64
|
"parse-srcset": "1.0.2",
|
|
65
|
-
"parse5": "
|
|
66
|
-
"pixelmatch": "
|
|
67
|
-
"playwright-core": "1.
|
|
65
|
+
"parse5": "8.1.1",
|
|
66
|
+
"pixelmatch": "8.0.0",
|
|
67
|
+
"playwright-core": "1.65.1",
|
|
68
68
|
"pngjs": "7.0.0",
|
|
69
|
-
"postcss": "8.5.
|
|
69
|
+
"postcss": "8.5.34",
|
|
70
70
|
"postcss-value-parser": "4.2.0"
|
|
71
71
|
},
|
|
72
72
|
"devDependencies": {
|
|
73
73
|
"@eslint/js": "10.0.1",
|
|
74
|
-
"@types/node": "
|
|
75
|
-
"eslint": "10.
|
|
76
|
-
"prettier": "3.
|
|
77
|
-
"typescript": "
|
|
74
|
+
"@types/node": "26.6.11",
|
|
75
|
+
"eslint": "10.16.0",
|
|
76
|
+
"prettier": "3.10.1",
|
|
77
|
+
"typescript": "7.0.2"
|
|
78
78
|
}
|
|
79
79
|
}
|
package/scripts/capture.mjs
CHANGED
|
@@ -28,6 +28,7 @@ import {
|
|
|
28
28
|
redactedUrl,
|
|
29
29
|
scrollForLazyContent,
|
|
30
30
|
serializeAttributes,
|
|
31
|
+
navigationError,
|
|
31
32
|
waitForPageStable,
|
|
32
33
|
} from "./lib.mjs";
|
|
33
34
|
|
|
@@ -49,10 +50,21 @@ async function dryRun(options) {
|
|
|
49
50
|
timeout: Math.min(60000, options.timeoutMs),
|
|
50
51
|
});
|
|
51
52
|
await waitForPageStable(page, options.settleMs);
|
|
53
|
+
// The check scrolls like the capture does, so a section that only appears
|
|
54
|
+
// after the page scrolls is found by both.
|
|
55
|
+
await scrollForLazyContent(page, options.maxScrollSteps);
|
|
56
|
+
await waitForPageStable(page, options.settleMs);
|
|
52
57
|
const root = page.locator(options.selector);
|
|
53
58
|
const matches = await root.count();
|
|
54
|
-
|
|
55
|
-
|
|
59
|
+
// The visibility is measured the same way the capture measures it, so the
|
|
60
|
+
// check does not promise a result the capture would not give.
|
|
61
|
+
const rendered =
|
|
62
|
+
matches === 1
|
|
63
|
+
? await root.evaluate(measureRoot).catch(() => ({
|
|
64
|
+
hidden: true,
|
|
65
|
+
visible: false,
|
|
66
|
+
}))
|
|
67
|
+
: { hidden: false, visible: false };
|
|
56
68
|
const version = browser.version();
|
|
57
69
|
await close();
|
|
58
70
|
if (matches !== 1)
|
|
@@ -62,13 +74,18 @@ async function dryRun(options) {
|
|
|
62
74
|
);
|
|
63
75
|
return {
|
|
64
76
|
command: "capture",
|
|
65
|
-
|
|
77
|
+
// A root that does not render would make the capture partial.
|
|
78
|
+
status: rendered.visible ? "complete" : "partial",
|
|
66
79
|
dryRun: true,
|
|
67
80
|
selector: options.selector,
|
|
68
81
|
matches,
|
|
69
|
-
visible,
|
|
82
|
+
visible: rendered.visible,
|
|
70
83
|
browser: { selected, version },
|
|
71
84
|
};
|
|
85
|
+
} catch (error) {
|
|
86
|
+
// A cancellation is reported with its own code, even when the browser
|
|
87
|
+
// rejected the pending operation first.
|
|
88
|
+
throw life.failure() || error;
|
|
72
89
|
} finally {
|
|
73
90
|
await life.close();
|
|
74
91
|
}
|
|
@@ -126,10 +143,14 @@ export async function capture(options) {
|
|
|
126
143
|
life.check();
|
|
127
144
|
log(`Capturing ${viewport.name}…`);
|
|
128
145
|
await page.setViewportSize(viewport);
|
|
129
|
-
await page
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
146
|
+
await page
|
|
147
|
+
.goto(sourceUrl, {
|
|
148
|
+
waitUntil: "domcontentloaded",
|
|
149
|
+
timeout: Math.min(60000, options.timeoutMs),
|
|
150
|
+
})
|
|
151
|
+
.catch((error) => {
|
|
152
|
+
throw life.failure() || navigationError(error, sourceUrl);
|
|
153
|
+
});
|
|
133
154
|
await waitForPageStable(page, settleMs);
|
|
134
155
|
if (await scrollForLazyContent(page, options.maxScrollSteps))
|
|
135
156
|
limitation(
|
|
@@ -435,6 +456,10 @@ ${serialize(fragment)}
|
|
|
435
456
|
behavior: BEHAVIOR,
|
|
436
457
|
limitations,
|
|
437
458
|
};
|
|
459
|
+
} catch (error) {
|
|
460
|
+
// A cancellation is reported with its own code, even when the browser
|
|
461
|
+
// rejected the pending operation first.
|
|
462
|
+
throw life.failure() || error;
|
|
438
463
|
} finally {
|
|
439
464
|
await life.close();
|
|
440
465
|
await stage?.cleanup();
|
package/scripts/css-context.mjs
CHANGED
|
@@ -151,7 +151,7 @@ export function contextualCss(stylesheets) {
|
|
|
151
151
|
const selectors = descriptors[id].selectors.map((selector) => {
|
|
152
152
|
const ids = observations.get(`${id}|${selector}`);
|
|
153
153
|
return ids?.size
|
|
154
|
-
? `:is(${selector}, :where(${[...ids].map((elementId) => `[
|
|
154
|
+
? `:is(${selector}, :where(${[...ids].map((elementId) => `[${ID_ATTR}="${elementId}"]`).join(", ")}))`
|
|
155
155
|
: selector;
|
|
156
156
|
});
|
|
157
157
|
let fallback = postcss.rule({ selector: selectors.join(", ") });
|
package/scripts/diff.mjs
CHANGED
|
@@ -17,36 +17,75 @@ import {
|
|
|
17
17
|
ROOT_ATTR,
|
|
18
18
|
ROOT_VALUE,
|
|
19
19
|
} from "./contract.mjs";
|
|
20
|
+
import { UiportError } from "./errors.mjs";
|
|
20
21
|
|
|
22
|
+
const rootSelector = `[${ROOT_ATTR}="${ROOT_VALUE}"]`;
|
|
23
|
+
const legacyRootSelector = `[${LEGACY_ROOT_ATTR}="${ROOT_VALUE}"]`;
|
|
24
|
+
const SCREENSHOT_PIXEL_LIMIT = 20_000_000;
|
|
25
|
+
|
|
26
|
+
/** Reads the metadata of an exported section, refusing a damaged artifact. */
|
|
21
27
|
async function readMetadata(directory) {
|
|
28
|
+
const file = path.join(directory, "index.html");
|
|
29
|
+
let html;
|
|
22
30
|
try {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
31
|
+
html = await fs.readFile(file, "utf8");
|
|
32
|
+
} catch (error) {
|
|
33
|
+
throw new UiportError(
|
|
34
|
+
"ARTIFACT_MISSING",
|
|
35
|
+
`The directory has no exported section: ${file}`,
|
|
36
|
+
{ cause: error },
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
const match = html.match(
|
|
40
|
+
new RegExp(
|
|
41
|
+
`<script type="application/json" id="${METADATA_ID}">([\\s\\S]*?)</script>`,
|
|
42
|
+
),
|
|
43
|
+
);
|
|
44
|
+
if (!match)
|
|
45
|
+
throw new UiportError(
|
|
46
|
+
"ARTIFACT_DAMAGED",
|
|
47
|
+
`The exported section has no UIport metadata: ${file}`,
|
|
28
48
|
);
|
|
29
|
-
|
|
49
|
+
try {
|
|
30
50
|
return JSON.parse(match[1]);
|
|
31
51
|
} catch {
|
|
32
|
-
|
|
52
|
+
throw new UiportError(
|
|
53
|
+
"ARTIFACT_DAMAGED",
|
|
54
|
+
`The metadata of the exported section is not valid JSON: ${file}`,
|
|
55
|
+
);
|
|
33
56
|
}
|
|
34
57
|
}
|
|
35
58
|
|
|
36
|
-
|
|
37
|
-
|
|
59
|
+
/** The multiset difference of two limitation lists, by code and message. */
|
|
60
|
+
function difference(left, right) {
|
|
61
|
+
const counts = new Map();
|
|
62
|
+
for (const entry of right) {
|
|
63
|
+
const key = `${entry.code}|${entry.message}`;
|
|
64
|
+
counts.set(key, (counts.get(key) || 0) + 1);
|
|
65
|
+
}
|
|
66
|
+
const missing = [];
|
|
67
|
+
for (const entry of left) {
|
|
68
|
+
const key = `${entry.code}|${entry.message}`;
|
|
69
|
+
const remaining = counts.get(key) || 0;
|
|
70
|
+
if (remaining > 0) counts.set(key, remaining - 1);
|
|
71
|
+
else missing.push(entry);
|
|
72
|
+
}
|
|
73
|
+
return missing;
|
|
74
|
+
}
|
|
38
75
|
|
|
39
76
|
/** Compares two exported sections: the pixels they render and what they report. */
|
|
40
77
|
export async function diff(options) {
|
|
41
78
|
const before = path.resolve(options.before);
|
|
42
79
|
const after = path.resolve(options.after);
|
|
43
|
-
|
|
44
|
-
|
|
80
|
+
// The metadata is read first: a damaged artifact is reported before a browser
|
|
81
|
+
// is started, and it is never read as an artifact without limitations.
|
|
82
|
+
const beforeMetadata = await readMetadata(before);
|
|
83
|
+
const afterMetadata = await readMetadata(after);
|
|
45
84
|
const life = lifecycle(options.timeoutMs);
|
|
46
85
|
try {
|
|
47
86
|
const beforeServer = await startStaticServer(before);
|
|
48
|
-
const afterServer = await startStaticServer(after);
|
|
49
87
|
life.add(beforeServer.close);
|
|
88
|
+
const afterServer = await startStaticServer(after);
|
|
50
89
|
life.add(afterServer.close);
|
|
51
90
|
const { browser, selected } = await launchChromium(chromium, life);
|
|
52
91
|
const results = [];
|
|
@@ -74,17 +113,31 @@ export async function diff(options) {
|
|
|
74
113
|
: legacyRootSelector,
|
|
75
114
|
);
|
|
76
115
|
if ((await root.count()) !== 1)
|
|
77
|
-
throw new
|
|
116
|
+
throw new UiportError(
|
|
117
|
+
"ARTIFACT_DAMAGED",
|
|
78
118
|
"An exported section is missing its extraction root",
|
|
79
119
|
);
|
|
80
|
-
|
|
120
|
+
// The size is checked before the screenshot, so an oversized section
|
|
121
|
+
// is refused instead of being rendered and decoded first.
|
|
122
|
+
const box = await root.boundingBox();
|
|
123
|
+
if (box && box.width * box.height > SCREENSHOT_PIXEL_LIMIT)
|
|
124
|
+
throw new UiportError(
|
|
125
|
+
"COMPARISON_TOO_LARGE",
|
|
126
|
+
"The section exceeds the 20 megapixel comparison limit",
|
|
127
|
+
);
|
|
128
|
+
shots.push(
|
|
129
|
+
await root.screenshot({ animations: "disabled", caret: "hide" }),
|
|
130
|
+
);
|
|
81
131
|
}
|
|
82
132
|
const left = PNG.sync.read(shots[0]);
|
|
83
133
|
const right = PNG.sync.read(shots[1]);
|
|
84
134
|
const width = Math.max(left.width, right.width);
|
|
85
135
|
const height = Math.max(left.height, right.height);
|
|
86
|
-
if (width * height >
|
|
87
|
-
throw new
|
|
136
|
+
if (width * height > SCREENSHOT_PIXEL_LIMIT)
|
|
137
|
+
throw new UiportError(
|
|
138
|
+
"COMPARISON_TOO_LARGE",
|
|
139
|
+
"The comparison exceeds the 20 megapixel limit",
|
|
140
|
+
);
|
|
88
141
|
const sameSize =
|
|
89
142
|
left.width === right.width && left.height === right.height;
|
|
90
143
|
const buffer = (source) => {
|
|
@@ -114,27 +167,28 @@ export async function diff(options) {
|
|
|
114
167
|
identical: ratio === 0,
|
|
115
168
|
differentPixels,
|
|
116
169
|
differenceRatio: ratio,
|
|
117
|
-
dimensionsMatch:
|
|
118
|
-
|
|
170
|
+
dimensionsMatch: sameSize,
|
|
171
|
+
heightDifference: Math.abs(left.height - right.height),
|
|
119
172
|
});
|
|
120
173
|
} finally {
|
|
121
174
|
await context.close();
|
|
122
175
|
}
|
|
123
176
|
}
|
|
124
|
-
const
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
(metadata?.limitations || []).map((entry) => entry.code).sort();
|
|
128
|
-
const added = codes(afterMetadata).filter(
|
|
129
|
-
(code) => !codes(beforeMetadata).includes(code),
|
|
177
|
+
const added = difference(
|
|
178
|
+
afterMetadata.limitations || [],
|
|
179
|
+
beforeMetadata.limitations || [],
|
|
130
180
|
);
|
|
131
|
-
const removed =
|
|
132
|
-
|
|
181
|
+
const removed = difference(
|
|
182
|
+
beforeMetadata.limitations || [],
|
|
183
|
+
afterMetadata.limitations || [],
|
|
133
184
|
);
|
|
134
185
|
const changed = results.some((entry) => !entry.identical);
|
|
186
|
+
const limitationsDiffer = added.length > 0 || removed.length > 0;
|
|
135
187
|
return {
|
|
136
188
|
command: "diff",
|
|
137
|
-
|
|
189
|
+
// Any difference leaves the result partial: a lost limitation is as
|
|
190
|
+
// relevant as a new one.
|
|
191
|
+
status: changed || limitationsDiffer ? "partial" : "complete",
|
|
138
192
|
before,
|
|
139
193
|
after,
|
|
140
194
|
browser: { selected, version: browser.version() },
|
package/scripts/dom.mjs
CHANGED
|
@@ -4,43 +4,59 @@
|
|
|
4
4
|
// `display: contents`, a zero-sized wrapper around an absolutely positioned
|
|
5
5
|
// child, or a parent whose visibility is overridden by a child.
|
|
6
6
|
export function measureRoot(element) {
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
if (
|
|
7
|
+
const styleOf = (node) => getComputedStyle(node);
|
|
8
|
+
const hiddenByStyle = (node) => {
|
|
9
|
+
const style = styleOf(node);
|
|
10
|
+
if (style.display === "none" || style.visibility === "hidden") return true;
|
|
11
|
+
return Boolean(
|
|
11
12
|
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;
|
|
13
|
+
!node.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }),
|
|
14
|
+
);
|
|
17
15
|
};
|
|
16
|
+
// The largest box that renders, considering the element itself, its
|
|
17
|
+
// descendants at any depth and the text it holds. A root without a box of
|
|
18
|
+
// its own is still visible when something inside it renders.
|
|
18
19
|
let width = 0;
|
|
19
20
|
let height = 0;
|
|
20
|
-
|
|
21
|
-
if (
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
21
|
+
const consider = (box) => {
|
|
22
|
+
if (box.width > 0 && box.height > 0) {
|
|
23
|
+
width = Math.max(width, box.width);
|
|
24
|
+
height = Math.max(height, box.height);
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
const walk = (node, depth, inheritedOpacity) => {
|
|
28
|
+
if (depth > 16) return;
|
|
29
|
+
const style = styleOf(node);
|
|
30
|
+
if (style.display === "none" || style.visibility === "hidden") return;
|
|
31
|
+
if (style.contentVisibility === "hidden") return;
|
|
32
|
+
// The opacity of the ancestors multiplies, so a transparent ancestor
|
|
33
|
+
// hides everything below it.
|
|
34
|
+
const opacity = inheritedOpacity * (Number(style.opacity) || 0);
|
|
35
|
+
if (opacity <= 0) return;
|
|
36
|
+
const box = node.getBoundingClientRect();
|
|
37
|
+
consider(box);
|
|
38
|
+
// Text nodes have no box of their own. A range over the content reports
|
|
39
|
+
// theirs, but only when the element does not clip that text away: a
|
|
40
|
+
// zero-sized box with overflow hidden hides it, while `display: contents`
|
|
41
|
+
// lays the text out in the parent.
|
|
42
|
+
const holdsText = style.display === "contents" || box.height > 0;
|
|
43
|
+
if (holdsText && node.textContent && node.textContent.trim()) {
|
|
44
|
+
const range = document.createRange();
|
|
45
|
+
range.selectNodeContents(node);
|
|
46
|
+
for (const rect of range.getClientRects()) consider(rect);
|
|
47
|
+
}
|
|
48
|
+
for (const child of node.children) walk(child, depth + 1, opacity);
|
|
49
|
+
};
|
|
50
|
+
walk(element, 0, 1);
|
|
32
51
|
const displaysNothing = width <= 0 || height <= 0;
|
|
33
52
|
// A root hidden by its own style displays nothing even when a child could
|
|
34
53
|
// override the visibility. A root without a box is empty instead.
|
|
54
|
+
// `display: contents` has no box of its own, and the browser reports it as
|
|
55
|
+
// not visible even when its children render.
|
|
35
56
|
const hidden =
|
|
36
57
|
displaysNothing &&
|
|
37
|
-
(
|
|
38
|
-
|
|
39
|
-
(element.checkVisibility &&
|
|
40
|
-
!element.checkVisibility({
|
|
41
|
-
checkOpacity: true,
|
|
42
|
-
checkVisibilityCSS: true,
|
|
43
|
-
})));
|
|
58
|
+
styleOf(element).display !== "contents" &&
|
|
59
|
+
hiddenByStyle(element);
|
|
44
60
|
return { hidden, visible: !displaysNothing, width, height };
|
|
45
61
|
}
|
|
46
62
|
|
package/scripts/errors.mjs
CHANGED
|
@@ -17,6 +17,10 @@ export const CODES = {
|
|
|
17
17
|
"The source page could not be loaded. Check the address and that the page is reachable.",
|
|
18
18
|
ARTIFACT_MISSING:
|
|
19
19
|
"The directory has no exported section. Run `uiport capture` first.",
|
|
20
|
+
ARTIFACT_DAMAGED:
|
|
21
|
+
"The exported section is incomplete: it has no UIport metadata or no extraction root. Capture it again.",
|
|
22
|
+
COMPARISON_TOO_LARGE:
|
|
23
|
+
"The section exceeds the 20 megapixel comparison limit. Compare a narrower section or a single viewport.",
|
|
20
24
|
INTERNAL: "The operation failed for an unexpected reason.",
|
|
21
25
|
};
|
|
22
26
|
|
package/scripts/inspect.mjs
CHANGED
|
@@ -21,19 +21,32 @@ export async function inspect(options) {
|
|
|
21
21
|
`<script type="application/json" id="${METADATA_ID}">([\\s\\S]*?)</script>`,
|
|
22
22
|
),
|
|
23
23
|
);
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
metadata
|
|
30
|
-
|
|
31
|
-
let
|
|
24
|
+
// An artifact without readable metadata is not read as an artifact without
|
|
25
|
+
// limitations: the validation refuses it, and the inspection refuses it too.
|
|
26
|
+
if (!match)
|
|
27
|
+
throw new UiportError(
|
|
28
|
+
"ARTIFACT_DAMAGED",
|
|
29
|
+
`The exported section has no UIport metadata: ${file}`,
|
|
30
|
+
);
|
|
31
|
+
let metadata;
|
|
32
32
|
try {
|
|
33
|
-
|
|
33
|
+
metadata = JSON.parse(match[1]);
|
|
34
34
|
} catch {
|
|
35
|
-
|
|
35
|
+
throw new UiportError(
|
|
36
|
+
"ARTIFACT_DAMAGED",
|
|
37
|
+
`The metadata of the exported section is not valid JSON: ${file}`,
|
|
38
|
+
);
|
|
36
39
|
}
|
|
40
|
+
// The metadata carries the number of assets the capture recorded; the
|
|
41
|
+
// directory is the fallback for an artifact written before it did.
|
|
42
|
+
let assets = Number.isInteger(metadata.assets) ? metadata.assets : undefined;
|
|
43
|
+
if (assets === undefined)
|
|
44
|
+
try {
|
|
45
|
+
assets = (await fs.readdir(path.join(options.directory, "assets")))
|
|
46
|
+
.length;
|
|
47
|
+
} catch {
|
|
48
|
+
assets = 0;
|
|
49
|
+
}
|
|
37
50
|
const limitations = Array.isArray(metadata.limitations)
|
|
38
51
|
? metadata.limitations
|
|
39
52
|
: [];
|
package/scripts/lib.mjs
CHANGED
|
@@ -86,7 +86,10 @@ export function extensionFor(url, contentType = "") {
|
|
|
86
86
|
export async function inspectOutput(directory) {
|
|
87
87
|
const destination = path.resolve(directory);
|
|
88
88
|
if (destination === path.parse(destination).root)
|
|
89
|
-
throw new
|
|
89
|
+
throw new UiportError(
|
|
90
|
+
"USAGE_INVALID",
|
|
91
|
+
"Refusing a filesystem root as output",
|
|
92
|
+
);
|
|
90
93
|
let existing = false;
|
|
91
94
|
try {
|
|
92
95
|
const stat = await fs.lstat(destination);
|
|
@@ -110,6 +113,12 @@ export async function inspectOutput(directory) {
|
|
|
110
113
|
export async function stageOutput(directory) {
|
|
111
114
|
const { destination, existing } = await inspectOutput(directory);
|
|
112
115
|
await fs.mkdir(path.dirname(destination), { recursive: true });
|
|
116
|
+
// The staging directory is created private by mkdtemp. The published
|
|
117
|
+
// directory keeps the mode a plain mkdir would have given it, so that the
|
|
118
|
+
// export can be read by the user's web server or by another account.
|
|
119
|
+
const permission = existing
|
|
120
|
+
? (await fs.stat(destination)).mode & 0o777
|
|
121
|
+
: 0o777 & ~process.umask();
|
|
113
122
|
const temporary = await fs.mkdtemp(
|
|
114
123
|
path.join(path.dirname(destination), ".uiport-"),
|
|
115
124
|
);
|
|
@@ -119,12 +128,15 @@ export async function stageOutput(directory) {
|
|
|
119
128
|
async commit() {
|
|
120
129
|
// Recheck immediately before moving. The directory is published with a
|
|
121
130
|
// single rename, so a reader never observes it half written.
|
|
131
|
+
await fs.chmod(temporary, permission);
|
|
122
132
|
if (existing) await fs.rmdir(destination); // only succeeds when still empty
|
|
123
133
|
try {
|
|
124
134
|
await fs.rename(temporary, destination);
|
|
125
135
|
} catch (error) {
|
|
126
136
|
if (existing)
|
|
127
|
-
await fs
|
|
137
|
+
await fs
|
|
138
|
+
.mkdir(destination, { recursive: true, mode: permission })
|
|
139
|
+
.catch(() => {});
|
|
128
140
|
throw error;
|
|
129
141
|
}
|
|
130
142
|
committed = true;
|
|
@@ -132,7 +144,7 @@ export async function stageOutput(directory) {
|
|
|
132
144
|
async cleanup() {
|
|
133
145
|
await fs.rm(temporary, { recursive: true, force: true });
|
|
134
146
|
if (existing && !committed)
|
|
135
|
-
await fs.mkdir(destination, { recursive: true });
|
|
147
|
+
await fs.mkdir(destination, { recursive: true }).catch(() => {});
|
|
136
148
|
},
|
|
137
149
|
};
|
|
138
150
|
}
|
|
@@ -285,7 +297,10 @@ export async function launchChromium(chromium, life) {
|
|
|
285
297
|
);
|
|
286
298
|
if (override) {
|
|
287
299
|
if (!fsSync.existsSync(override))
|
|
288
|
-
throw new
|
|
300
|
+
throw new UiportError(
|
|
301
|
+
"BROWSER_NOT_FOUND",
|
|
302
|
+
"UIPORT_BROWSER_PATH does not exist; set it to an executable, or run: uiport browser install",
|
|
303
|
+
);
|
|
289
304
|
return {
|
|
290
305
|
...(await launch({ executablePath: override }).catch((error) => {
|
|
291
306
|
life?.check();
|
|
@@ -315,6 +330,30 @@ export async function launchChromium(chromium, life) {
|
|
|
315
330
|
);
|
|
316
331
|
}
|
|
317
332
|
|
|
333
|
+
const UNREACHABLE = [
|
|
334
|
+
"ERR_CONNECTION_REFUSED",
|
|
335
|
+
"ERR_NAME_NOT_RESOLVED",
|
|
336
|
+
"ERR_INTERNET_DISCONNECTED",
|
|
337
|
+
"ERR_CONNECTION_CLOSED",
|
|
338
|
+
"ERR_CONNECTION_RESET",
|
|
339
|
+
"ERR_ADDRESS_UNREACHABLE",
|
|
340
|
+
"ERR_EMPTY_RESPONSE",
|
|
341
|
+
"ERR_UNSAFE_PORT",
|
|
342
|
+
];
|
|
343
|
+
|
|
344
|
+
/** Turns a navigation failure into the code that says what to do about it. */
|
|
345
|
+
export function navigationError(error, url) {
|
|
346
|
+
if (error instanceof UiportError) return error;
|
|
347
|
+
const message = String(error?.message || "");
|
|
348
|
+
if (UNREACHABLE.some((code) => message.includes(code)))
|
|
349
|
+
return new UiportError(
|
|
350
|
+
"SOURCE_UNREACHABLE",
|
|
351
|
+
`The page could not be reached: ${redactedUrl(url)}`,
|
|
352
|
+
{ cause: error },
|
|
353
|
+
);
|
|
354
|
+
return error;
|
|
355
|
+
}
|
|
356
|
+
|
|
318
357
|
/** Tracks resources so timeouts and SIGINT/SIGTERM also close failed runs. */
|
|
319
358
|
export function lifecycle(timeoutMs) {
|
|
320
359
|
const deadline = performance.now() + timeoutMs;
|
|
@@ -352,6 +391,12 @@ export function lifecycle(timeoutMs) {
|
|
|
352
391
|
cancel(`Operation exceeded ${timeoutMs} ms`);
|
|
353
392
|
if (reason) throw reason;
|
|
354
393
|
},
|
|
394
|
+
// The reason of a cancellation, when there is one. A pending browser
|
|
395
|
+
// operation rejects with the error of the browser before this one is
|
|
396
|
+
// noticed, and the reason is the one the caller should see.
|
|
397
|
+
failure() {
|
|
398
|
+
return reason;
|
|
399
|
+
},
|
|
355
400
|
remaining() {
|
|
356
401
|
this.check();
|
|
357
402
|
return Math.max(1, Math.ceil(deadline - performance.now()));
|
package/scripts/options.mjs
CHANGED
|
@@ -147,14 +147,40 @@ export function httpUrl(value) {
|
|
|
147
147
|
return url.href;
|
|
148
148
|
}
|
|
149
149
|
|
|
150
|
-
/**
|
|
150
|
+
/**
|
|
151
|
+
* @typedef {object} Options
|
|
152
|
+
* @property {boolean} json
|
|
153
|
+
* @property {boolean} omitScripts
|
|
154
|
+
* @property {boolean} dryRun
|
|
155
|
+
* @property {string} sourceUrl
|
|
156
|
+
* @property {string} selector
|
|
157
|
+
* @property {string} before
|
|
158
|
+
* @property {string} after
|
|
159
|
+
* @property {string} directory
|
|
160
|
+
* @property {{width:number,height:number,name:string}[]} viewports
|
|
161
|
+
* @property {number} settleMs
|
|
162
|
+
* @property {number} timeoutMs
|
|
163
|
+
* @property {string} locale
|
|
164
|
+
* @property {'light' | 'dark'} colorScheme
|
|
165
|
+
* @property {number} maxResourceBytes
|
|
166
|
+
* @property {number} maxTotalBytes
|
|
167
|
+
* @property {number} maxScrollSteps
|
|
168
|
+
* @property {number} maximumDifferenceRatio
|
|
169
|
+
* @property {boolean} allowExternal
|
|
170
|
+
* @property {number} port
|
|
171
|
+
*/
|
|
172
|
+
|
|
173
|
+
/** @param {string} command @param {Record<string, string | boolean>} args @returns {Options} */
|
|
151
174
|
export function optionsFor(command, args) {
|
|
175
|
+
/** @type {Options} */
|
|
152
176
|
const options = {
|
|
153
177
|
json: args.json === true,
|
|
154
178
|
omitScripts: args["omit-scripts"] === true,
|
|
155
179
|
dryRun: args["dry-run"] === true,
|
|
156
180
|
sourceUrl: "",
|
|
157
181
|
selector: "",
|
|
182
|
+
before: "",
|
|
183
|
+
after: "",
|
|
158
184
|
directory: "",
|
|
159
185
|
viewports: parseViewports(
|
|
160
186
|
typeof args.viewports === "string" ? args.viewports : undefined,
|
|
@@ -191,12 +217,18 @@ export function optionsFor(command, args) {
|
|
|
191
217
|
port: numeric(args.port, "port", 4173, 0, 65535),
|
|
192
218
|
};
|
|
193
219
|
if (!["light", "dark"].includes(options.colorScheme))
|
|
194
|
-
throw new
|
|
220
|
+
throw new UiportError(
|
|
221
|
+
"USAGE_INVALID",
|
|
222
|
+
"--color-scheme must be light or dark",
|
|
223
|
+
);
|
|
195
224
|
if (
|
|
196
225
|
!Number.isInteger(options.port) ||
|
|
197
226
|
!Number.isInteger(options.maxScrollSteps)
|
|
198
227
|
)
|
|
199
|
-
throw new
|
|
228
|
+
throw new UiportError(
|
|
229
|
+
"USAGE_INVALID",
|
|
230
|
+
"--port and --max-scroll-steps must be integers",
|
|
231
|
+
);
|
|
200
232
|
if (command === "capture" || command === "validate") {
|
|
201
233
|
options.sourceUrl = httpUrl(required(args, "url"));
|
|
202
234
|
options.selector = required(args, "selector");
|
package/scripts/report.mjs
CHANGED
|
@@ -71,44 +71,58 @@ export function report(result) {
|
|
|
71
71
|
? `UIport: validation failed in ${failed.length} of ${result.results.length} viewports`
|
|
72
72
|
: `UIport: validation passed in ${result.results.length} viewports`,
|
|
73
73
|
);
|
|
74
|
+
// The limitations of the exported section are collected from every
|
|
75
|
+
// viewport, because they belong to the artifact and not to one of them.
|
|
76
|
+
const collected = new Map();
|
|
77
|
+
for (const entry of result.results)
|
|
78
|
+
for (const item of entry.captureLimitations || [])
|
|
79
|
+
collected.set(`${item.code}|${item.message}`, item);
|
|
74
80
|
for (const entry of failed) {
|
|
75
81
|
const visual = entry.visual || {};
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
82
|
+
// The pixels are only the reason when the pixels are the reason.
|
|
83
|
+
if (visual.pass === false)
|
|
84
|
+
lines.push(
|
|
85
|
+
` ! ${entry.viewport} — ${(visual.differenceRatio * 100).toFixed(1)}% of the pixels differ (limit ${(visual.maximumDifferenceRatio * 100).toFixed(0)}%)`,
|
|
86
|
+
);
|
|
87
|
+
if (entry.network && entry.network.pass === false)
|
|
88
|
+
lines.push(
|
|
89
|
+
` ! ${entry.viewport} — the exported page made a request it could not satisfy`,
|
|
90
|
+
);
|
|
79
91
|
for (const error of entry.errors || []) lines.push(` ${error}`);
|
|
80
92
|
for (const url of entry.network?.failedRequests || [])
|
|
81
93
|
lines.push(` failed request: ${url}`);
|
|
82
94
|
}
|
|
95
|
+
lines.push(...limitations([...collected.values()]));
|
|
83
96
|
lines.push(...limitations(result.limitations));
|
|
84
97
|
lines.push(" behavior: not tested; inspect the interactions yourself");
|
|
85
98
|
} else if (result.command === "diff") {
|
|
86
99
|
const changed = result.results.filter((entry) => !entry.identical);
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
);
|
|
92
|
-
for (const entry of changed)
|
|
100
|
+
const views = result.results.length === 1 ? "viewport" : "viewports";
|
|
101
|
+
const added = result.limitations.added || [];
|
|
102
|
+
const removed = result.limitations.removed || [];
|
|
103
|
+
if (!changed.length && !added.length && !removed.length)
|
|
93
104
|
lines.push(
|
|
94
|
-
`
|
|
105
|
+
`UIport: the two exports are identical in ${result.results.length} ${views}`,
|
|
95
106
|
);
|
|
96
|
-
|
|
107
|
+
else {
|
|
97
108
|
lines.push(
|
|
98
|
-
`
|
|
99
|
-
);
|
|
100
|
-
for (const code of result.limitations.removed)
|
|
101
|
-
lines.push(
|
|
102
|
-
` - ${code} — a limitation the first export reports and the second does not`,
|
|
109
|
+
`UIport: the two exports differ — ${changed.length} of ${result.results.length} ${views} with different pixels, ${added.length} limitation(s) added and ${removed.length} removed`,
|
|
103
110
|
);
|
|
111
|
+
for (const entry of changed)
|
|
112
|
+
lines.push(
|
|
113
|
+
` ! ${entry.viewport} — ${(entry.differenceRatio * 100).toFixed(1)}% of the pixels differ${entry.dimensionsMatch ? "" : `, and the height differs by ${entry.heightDifference} px`}`,
|
|
114
|
+
);
|
|
115
|
+
for (const entry of added)
|
|
116
|
+
lines.push(` + ${entry.code} — reported only by the second export`);
|
|
117
|
+
for (const entry of removed)
|
|
118
|
+
lines.push(` - ${entry.code} — reported only by the first export`);
|
|
119
|
+
}
|
|
104
120
|
} else if (result.command === "inspect") {
|
|
105
121
|
lines.push(`UIport: ${result.outputDirectory}`);
|
|
106
122
|
lines.push(
|
|
107
123
|
` ${result.elements ?? "?"} elements · ${result.assets ?? 0} asset${result.assets === 1 ? "" : "s"}`,
|
|
108
124
|
);
|
|
109
125
|
lines.push(...limitations(result.limitations));
|
|
110
|
-
} else if (result.command === "browser") {
|
|
111
|
-
lines.push("UIport: Chromium installation complete. Ready to capture.");
|
|
112
126
|
}
|
|
113
127
|
return lines.join("\n");
|
|
114
128
|
}
|
package/scripts/resources.mjs
CHANGED
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
limitation,
|
|
13
13
|
} from "./lib.mjs";
|
|
14
14
|
|
|
15
|
-
/** @param {string} directory @param {import('./options.mjs').
|
|
15
|
+
/** @param {string} directory @param {import('./options.mjs').Options} options @param {AbortSignal} signal @param {{code:string,message:string}[]} limitations @param {{get:(url:string)=>Promise<any>} | undefined} [browserCache] */
|
|
16
16
|
export function resources(
|
|
17
17
|
directory,
|
|
18
18
|
options,
|
|
@@ -29,12 +29,14 @@ export function resources(
|
|
|
29
29
|
const localPaths = new Set();
|
|
30
30
|
const maxConcurrentDownloads = 8;
|
|
31
31
|
let activeDownloads = 0;
|
|
32
|
+
/** @type {((value?: unknown) => void)[]} */
|
|
32
33
|
const waitingDownloads = [];
|
|
33
34
|
// Bytes read from the network, and bytes charged against the total budget.
|
|
34
35
|
// The charge happens before the bytes are retained, so concurrent transfers
|
|
35
36
|
// cannot pass the limit together; the reported download size stays the
|
|
36
37
|
// amount actually received.
|
|
37
38
|
let received = 0;
|
|
39
|
+
/** @param {number} bytes */
|
|
38
40
|
function consume(bytes) {
|
|
39
41
|
received += bytes;
|
|
40
42
|
if (consumed + bytes > options.maxTotalBytes)
|
|
@@ -178,6 +180,7 @@ export function resources(
|
|
|
178
180
|
// Most declarations carry no URL at all: parsing them is wasted work.
|
|
179
181
|
if (!/url\(|image-set\(/i.test(value)) return value;
|
|
180
182
|
const parsed = valueParser(value);
|
|
183
|
+
/** @type {any[]} */
|
|
181
184
|
const nodes = [];
|
|
182
185
|
parsed.walk((node) => {
|
|
183
186
|
if (node.type === "function" && node.value.toLowerCase() === "url") {
|
|
@@ -217,19 +220,22 @@ export function resources(
|
|
|
217
220
|
/** @param {string} text @param {string} base @param {Set<string>} [stack] */
|
|
218
221
|
async function css(text, base, stack = new Set()) {
|
|
219
222
|
const root = postcss.parse(text, { from: undefined });
|
|
223
|
+
/** @type {import('postcss').Declaration[]} */
|
|
220
224
|
const declarations = [];
|
|
221
225
|
root.walkDecls((decl) => {
|
|
222
226
|
declarations.push(decl);
|
|
223
227
|
});
|
|
228
|
+
/** @type {import('postcss').AtRule[]} */
|
|
224
229
|
const imports = [];
|
|
225
230
|
root.walkAtRules(/^import$/i, (rule) => {
|
|
226
231
|
imports.push(rule);
|
|
227
232
|
});
|
|
228
233
|
for (const rule of imports) {
|
|
229
234
|
const parsed = valueParser(rule.params);
|
|
230
|
-
const
|
|
235
|
+
const firstIndex = parsed.nodes.findIndex(
|
|
231
236
|
(n) => n.type !== "space" && n.type !== "comment",
|
|
232
237
|
);
|
|
238
|
+
const first = parsed.nodes[firstIndex];
|
|
233
239
|
const raw =
|
|
234
240
|
first?.type === "string"
|
|
235
241
|
? first.value
|
|
@@ -256,7 +262,7 @@ export function resources(
|
|
|
256
262
|
}
|
|
257
263
|
const imported = await download(url);
|
|
258
264
|
if (!imported) {
|
|
259
|
-
rule.params = `url(${JSON.stringify(url)}) ${valueParser.stringify(parsed.nodes.slice(
|
|
265
|
+
rule.params = `url(${JSON.stringify(url)}) ${valueParser.stringify(parsed.nodes.slice(firstIndex + 1))}`;
|
|
260
266
|
continue;
|
|
261
267
|
}
|
|
262
268
|
let body = await css(
|
|
@@ -265,19 +271,27 @@ export function resources(
|
|
|
265
271
|
new Set([...stack, url]),
|
|
266
272
|
);
|
|
267
273
|
const tail = parsed.nodes
|
|
268
|
-
.slice(
|
|
274
|
+
.slice(firstIndex + 1)
|
|
269
275
|
.filter((n) => n.type !== "space" && n.type !== "comment");
|
|
270
276
|
const wrappers = [];
|
|
271
277
|
if (tail[0]?.value === "layer") {
|
|
272
278
|
const layer = tail.shift();
|
|
273
279
|
wrappers.push([
|
|
274
280
|
"layer",
|
|
275
|
-
layer
|
|
281
|
+
layer?.type === "function"
|
|
282
|
+
? valueParser.stringify(
|
|
283
|
+
/** @type {import('postcss-value-parser').FunctionNode} */ (
|
|
284
|
+
layer
|
|
285
|
+
).nodes,
|
|
286
|
+
)
|
|
287
|
+
: "",
|
|
276
288
|
]);
|
|
277
289
|
}
|
|
278
290
|
if (tail[0]?.type === "function" && tail[0].value === "supports") {
|
|
279
|
-
const supports =
|
|
280
|
-
|
|
291
|
+
const supports =
|
|
292
|
+
/** @type {import('postcss-value-parser').FunctionNode} */ (
|
|
293
|
+
tail.shift()
|
|
294
|
+
);
|
|
281
295
|
const v = valueParser.stringify(supports.nodes);
|
|
282
296
|
wrappers.push([
|
|
283
297
|
"supports",
|
package/scripts/validate.mjs
CHANGED
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
redactedUrl,
|
|
19
19
|
scrollForLazyContent,
|
|
20
20
|
startStaticServer,
|
|
21
|
+
navigationError,
|
|
21
22
|
waitForPageStable,
|
|
22
23
|
} from "./lib.mjs";
|
|
23
24
|
// Copy a decoded PNG into a buffer of the comparison size, padding the rows
|
|
@@ -40,7 +41,16 @@ function copy(source, destination, width) {
|
|
|
40
41
|
}
|
|
41
42
|
|
|
42
43
|
export async function validate(options) {
|
|
43
|
-
|
|
44
|
+
const index = path.join(options.directory, "index.html");
|
|
45
|
+
try {
|
|
46
|
+
await fs.access(index);
|
|
47
|
+
} catch (error) {
|
|
48
|
+
throw new UiportError(
|
|
49
|
+
"ARTIFACT_MISSING",
|
|
50
|
+
`The directory has no exported section: ${index}`,
|
|
51
|
+
{ cause: error },
|
|
52
|
+
);
|
|
53
|
+
}
|
|
44
54
|
const life = lifecycle(options.timeoutMs);
|
|
45
55
|
const results = [];
|
|
46
56
|
try {
|
|
@@ -65,10 +75,14 @@ export async function validate(options) {
|
|
|
65
75
|
try {
|
|
66
76
|
const source = await sourceContext.newPage();
|
|
67
77
|
source.setDefaultTimeout(10000);
|
|
68
|
-
await source
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
78
|
+
await source
|
|
79
|
+
.goto(options.sourceUrl, {
|
|
80
|
+
waitUntil: "domcontentloaded",
|
|
81
|
+
timeout: Math.min(options.timeoutMs, 60000),
|
|
82
|
+
})
|
|
83
|
+
.catch((error) => {
|
|
84
|
+
throw life.failure() || navigationError(error, options.sourceUrl);
|
|
85
|
+
});
|
|
72
86
|
await waitForPageStable(source, options.settleMs);
|
|
73
87
|
const scrollLimited = await scrollForLazyContent(
|
|
74
88
|
source,
|
|
@@ -135,11 +149,8 @@ export async function validate(options) {
|
|
|
135
149
|
});
|
|
136
150
|
await waitForPageStable(local, options.settleMs);
|
|
137
151
|
// Legacy root markers remain supported for existing user exports.
|
|
138
|
-
const isCurrent =
|
|
139
|
-
.locator(`[${ROOT_ATTR}="${ROOT_VALUE}"]`)
|
|
140
|
-
.count())
|
|
141
|
-
? true
|
|
142
|
-
: false;
|
|
152
|
+
const isCurrent =
|
|
153
|
+
(await local.locator(`[${ROOT_ATTR}="${ROOT_VALUE}"]`).count()) > 0;
|
|
143
154
|
const rootSelector = isCurrent
|
|
144
155
|
? `[${ROOT_ATTR}="${ROOT_VALUE}"]`
|
|
145
156
|
: `[${LEGACY_ROOT_ATTR}="${ROOT_VALUE}"]`;
|
|
@@ -151,7 +162,7 @@ export async function validate(options) {
|
|
|
151
162
|
// no limitation at all.
|
|
152
163
|
if (isCurrent && !(await local.locator(`#${METADATA_ID}`).count()))
|
|
153
164
|
throw new Error(
|
|
154
|
-
"The exported section has no UIport metadata; it
|
|
165
|
+
"The exported section has no UIport metadata; capture it again",
|
|
155
166
|
);
|
|
156
167
|
const localBox = await localRoot.boundingBox();
|
|
157
168
|
if (!localBox || localBox.width <= 0 || localBox.height <= 0)
|
|
@@ -238,6 +249,10 @@ export async function validate(options) {
|
|
|
238
249
|
behavior: BEHAVIOR,
|
|
239
250
|
results,
|
|
240
251
|
};
|
|
252
|
+
} catch (error) {
|
|
253
|
+
// A cancellation is reported with its own code, even when the browser
|
|
254
|
+
// rejected the pending operation first.
|
|
255
|
+
throw life.failure() || error;
|
|
241
256
|
} finally {
|
|
242
257
|
await life.close();
|
|
243
258
|
}
|
package/skills/uiport/SKILL.md
CHANGED
|
@@ -8,7 +8,7 @@ description: Capture a rendered web section as editable HTML, original CSS and l
|
|
|
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
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.
|
|
11
|
+
2. Use the installed CLI or source checkout. `npx uiport@0.1.4` 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. Check the selector first with `uiport capture --url "URL" --selector "SELECTOR" --dry-run`. It reports whether the selector resolves to one visible element and writes nothing.
|
|
14
14
|
5. 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.
|
|
@@ -31,6 +31,11 @@ The error document carries a `code` and a `hint`.
|
|
|
31
31
|
| `SELECTOR_AMBIGUOUS` | Narrow the selector, or capture the whole page with `--selector body`. |
|
|
32
32
|
| `TIMEOUT` | Raise `--timeout` or reduce `--viewports`. |
|
|
33
33
|
| `CANCELLED` | The run was interrupted. |
|
|
34
|
+
| `SOURCE_UNREACHABLE` | The page could not be reached: check the address and that the service is up. |
|
|
35
|
+
| `ARTIFACT_MISSING` | The directory has no exported section: capture it first. |
|
|
36
|
+
| `ARTIFACT_DAMAGED` | The export has no metadata or no extraction root: capture it again. |
|
|
37
|
+
| `COMPARISON_TOO_LARGE` | The section is above 20 megapixels: compare a narrower section. |
|
|
38
|
+
| `INTERNAL` | An unexpected failure: read the message, and report it with the version. |
|
|
34
39
|
|
|
35
40
|
## What each limitation asks for
|
|
36
41
|
|
|
@@ -39,6 +44,10 @@ The error document carries a `code` and a `hint`.
|
|
|
39
44
|
| `SOURCE_RUNTIME_UNVERIFIED` | Test the interactions before delivering. |
|
|
40
45
|
| `SOURCE_RUNTIME_OMITTED` | The behavior of the section is not reproduced. |
|
|
41
46
|
| `RESOURCE_UNAVAILABLE` | A resource was not downloaded: check it in the output. |
|
|
47
|
+
| `INVALID_RESOURCE_URL` | A resource address could not be resolved: check it in the output. |
|
|
48
|
+
| `STYLESHEET_UNAVAILABLE` | A stylesheet could not be read: the section may be missing styles. |
|
|
49
|
+
| `SOURCE_REQUEST_FAILED` | A request of the source failed: check whether the section depends on it. |
|
|
50
|
+
| `SOURCE_SCRIPT_ERROR` | The source raised a JavaScript error: the section may be incomplete. |
|
|
42
51
|
| `SRCSET_INVALID` | A descriptor list was not parsed: check which image the browser picks. |
|
|
43
52
|
| `SCROLL_LIMIT` | The lazy loading was cut short: raise `--max-scroll-steps`. |
|
|
44
53
|
| `RESPONSIVE_DOM_CHANGED` | The structure changes across viewports; the first viewport was exported. |
|
package/uiport.md
CHANGED
|
@@ -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.4` 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
|
Confira o seletor antes de capturar, sem escrever nada:
|
|
96
96
|
|