uiport 0.1.2 → 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 +42 -0
- package/README.md +9 -6
- package/README.pt-BR.md +9 -6
- package/bin/cli.mjs +27 -9
- package/docs/support.md +9 -1
- package/package.json +9 -9
- package/scripts/capture.mjs +102 -13
- package/scripts/contract.mjs +14 -0
- package/scripts/css-context.mjs +7 -5
- package/scripts/diff.mjs +203 -0
- package/scripts/dom.mjs +58 -33
- package/scripts/errors.mjs +57 -0
- package/scripts/examples.mjs +37 -0
- package/scripts/inspect.mjs +63 -0
- package/scripts/lib.mjs +62 -20
- package/scripts/options.mjs +87 -15
- package/scripts/report.mjs +133 -0
- package/scripts/resources.mjs +21 -7
- package/scripts/validate.mjs +51 -15
- package/skills/uiport/SKILL.md +47 -7
- package/uiport.md +9 -2
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,48 @@ 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
|
+
|
|
28
|
+
## [0.1.3] — 2026-11-28
|
|
29
|
+
|
|
30
|
+
### Added
|
|
31
|
+
- `uiport diff --before DIRECTORY --after DIRECTORY` compares two exported sections: the pixels they render and the limitations they report.
|
|
32
|
+
- `uiport examples` serves the original examples that ship with the package, so the tool can be tried without choosing a page first.
|
|
33
|
+
- `uiport inspect --dir DIRECTORY` reads the limitations of an exported section without opening a browser.
|
|
34
|
+
- `uiport capture --dry-run` checks the selector against the page and writes nothing.
|
|
35
|
+
- Every failure carries a stable code and a hint, so a script can branch on it and a person knows what to do.
|
|
36
|
+
|
|
37
|
+
### Changed
|
|
38
|
+
- Without `--json` the result is a readable summary on stdout; with `--json` it stays one JSON document. Progress always goes to stderr.
|
|
39
|
+
- The agent skill tells what to do with each failure code and each limitation.
|
|
40
|
+
|
|
41
|
+
### Fixed
|
|
42
|
+
- Bind a contextual custom property to the element of the exported DOM. The identifiers are assigned by position, so an observation from another viewport could point the property at a different element.
|
|
43
|
+
- Keep a style element created by a script in one piece when its text holds a closing tag, and escape that sequence in the exported CSS whatever its case.
|
|
44
|
+
- Serve a font in the OpenType format with the type the browser expects, instead of an opaque type that the browser refuses to load.
|
|
45
|
+
- Publish the captured directory with a single rename, so a reader never observes it half written.
|
|
46
|
+
- The markers that connect a capture to the validation of its result live in one module, and the validation reports an artifact that does not carry them instead of reading it as an empty one.
|
|
47
|
+
- Redact the message of a failure before it reaches any channel, in the readable output as well as in the JSON document.
|
|
48
|
+
|
|
7
49
|
## [0.1.2] — 2026-11-28
|
|
8
50
|
|
|
9
51
|
### Fixed
|
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.
|
|
@@ -62,10 +62,13 @@ Open `http://127.0.0.1:4174`. You can move that output directory and serve it ag
|
|
|
62
62
|
| `capture --url URL --selector CSS --out DIR` | Capture one rendered section |
|
|
63
63
|
| `serve --dir DIR --port 4173` | Preview on loopback; stop with Ctrl+C |
|
|
64
64
|
| `validate --url URL --selector CSS --dir DIR` | Compare screenshots and observe resource errors |
|
|
65
|
+
| `inspect --dir DIR` | Read the limitations of an exported section, without a browser |
|
|
66
|
+
| `diff --before DIR --after DIR` | Compare two exported sections: what they render and what they report |
|
|
67
|
+
| `examples` | Serve the original examples that ship with the package |
|
|
65
68
|
| `browser install` | Install Chromium matched to the bundled Playwright version |
|
|
66
69
|
| `--help` / `--version` | Inspect the CLI without starting a browser |
|
|
67
70
|
|
|
68
|
-
`capture` and `validate` share `--viewports`, `--wait`, `--timeout`, `--max-scroll-steps`, `--locale`, `--color-scheme` and `--json`. Defaults: four viewports (`1440x900,1024x768,768x1024,375x812`), 1200 ms settle time, 120 s whole-operation deadline and 80 scroll steps. The default locale is `pt-BR`; use the same `--locale` and `--color-scheme` in capture and validation.
|
|
71
|
+
`capture` and `validate` share `--viewports`, `--wait`, `--timeout`, `--max-scroll-steps`, `--locale`, `--color-scheme` and `--json`. `capture --dry-run` checks the selector against the page and writes nothing. Defaults: four viewports (`1440x900,1024x768,768x1024,375x812`), 1200 ms settle time, 120 s whole-operation deadline and 80 scroll steps. The default locale is `pt-BR`; use the same `--locale` and `--color-scheme` in capture and validation.
|
|
69
72
|
|
|
70
73
|
Capture limits copied resources to 20 MiB each and 100 MiB in total. Override with `--max-resource-mb` and `--max-total-mb`. The capture reuses responses received by its fresh browser context (including resources requiring Referer), then uses HTTP fetch as fallback. Budgets limit retained response bytes and exported downloads, not the browser's complete memory or the temporary buffer materialized by Playwright. Fallback fetching has a 15 s request deadline.
|
|
71
74
|
|
|
@@ -78,7 +81,7 @@ Set `UIPORT_BROWSER_PATH` to explicitly choose an executable. Otherwise UIport t
|
|
|
78
81
|
- **Exit 1:** command failed, or validation failed its requested checks.
|
|
79
82
|
- **Validation exit 0:** the observed visual/network checks passed. Behavior remains `not-tested`.
|
|
80
83
|
|
|
81
|
-
`--json`
|
|
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.
|
|
82
85
|
|
|
83
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.
|
|
84
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.
|
|
@@ -62,10 +62,13 @@ Abra `http://127.0.0.1:4174`. A pasta de saída pode ser movida e servida novame
|
|
|
62
62
|
| `capture --url URL --selector CSS --out PASTA` | Captura uma seção renderizada |
|
|
63
63
|
| `serve --dir PASTA --port 4173` | Abre servidor local; encerra com Ctrl+C |
|
|
64
64
|
| `validate --url URL --selector CSS --dir PASTA` | Compara imagens e verifica erros de recursos |
|
|
65
|
+
| `inspect --dir PASTA` | Lê as limitações de uma seção exportada, sem abrir navegador |
|
|
66
|
+
| `diff --before PASTA --after PASTA` | Compara duas seções exportadas: o que renderizam e o que relatam |
|
|
67
|
+
| `examples` | Serve os exemplos originais que acompanham o pacote |
|
|
65
68
|
| `browser install` | Instala Chromium compatível com a versão de Playwright do pacote |
|
|
66
69
|
| `--help` / `--version` | Mostra ajuda ou versão sem abrir navegador |
|
|
67
70
|
|
|
68
|
-
Capture e validate aceitam `--viewports`, `--wait`, `--timeout`, `--max-scroll-steps`, `--locale`, `--color-scheme` e `--json`. Padrões: `1440x900,1024x768,768x1024,375x812`, espera de 1200 ms, prazo total de 120 s, 80 passos de rolagem, idioma `pt-BR` e tema `light`. Use o mesmo `--locale` nos dois comandos quando precisar de outro idioma.
|
|
71
|
+
Capture e validate aceitam `--viewports`, `--wait`, `--timeout`, `--max-scroll-steps`, `--locale`, `--color-scheme` e `--json`. `capture --dry-run` confere o seletor na página sem escrever nada. Padrões: `1440x900,1024x768,768x1024,375x812`, espera de 1200 ms, prazo total de 120 s, 80 passos de rolagem, idioma `pt-BR` e tema `light`. Use o mesmo `--locale` nos dois comandos quando precisar de outro idioma.
|
|
69
72
|
|
|
70
73
|
A captura limita recursos copiados a 20 MiB por arquivo e 100 MiB no total, configuráveis por `--max-resource-mb` e `--max-total-mb`. A captura reaproveita respostas recebidas pelo navegador, incluindo recursos que exigem Referer, e usa fetch HTTP como fallback. Os orçamentos limitam bytes retidos e baixados pela exportação, não a memória completa do navegador nem o buffer temporário materializado pelo Playwright. O fetch de fallback tem prazo de até 15 s.
|
|
71
74
|
|
|
@@ -78,7 +81,7 @@ A captura limita recursos copiados a 20 MiB por arquivo e 100 MiB no total, conf
|
|
|
78
81
|
- **Retorno 1:** falha operacional ou falha das verificações pedidas no validate.
|
|
79
82
|
- **Validate retorna 0:** verificações visuais/de rede passaram nos estados observados. Comportamento continua `not-tested`.
|
|
80
83
|
|
|
81
|
-
`--json`
|
|
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.
|
|
82
85
|
|
|
83
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).
|
|
84
87
|
|
package/bin/cli.mjs
CHANGED
|
@@ -5,6 +5,8 @@ import path from "node:path";
|
|
|
5
5
|
import { allowed, parseArgs, optionsFor } from "../scripts/options.mjs";
|
|
6
6
|
import { safeErrorMessage } from "../scripts/lib.mjs";
|
|
7
7
|
import { guardStdout } from "../scripts/stdout.mjs";
|
|
8
|
+
import { describeError, UiportError } from "../scripts/errors.mjs";
|
|
9
|
+
import { report, reportError } from "../scripts/report.mjs";
|
|
8
10
|
const require = createRequire(import.meta.url);
|
|
9
11
|
const { version } = require("../package.json");
|
|
10
12
|
const argv = process.argv.slice(2);
|
|
@@ -16,18 +18,23 @@ Usage:
|
|
|
16
18
|
uiport capture --url URL --selector CSS --out DIRECTORY [options]
|
|
17
19
|
uiport validate --url URL --selector CSS --dir DIRECTORY [options]
|
|
18
20
|
uiport serve --dir DIRECTORY [--port 4173] [--json]
|
|
21
|
+
uiport inspect --dir DIRECTORY [--json]
|
|
22
|
+
uiport diff --before DIRECTORY --after DIRECTORY [--json]
|
|
23
|
+
uiport examples [--port 4173] [--json]
|
|
19
24
|
uiport browser install
|
|
20
25
|
|
|
21
|
-
Capture / validate:
|
|
26
|
+
Capture / validate / diff:
|
|
22
27
|
--viewports 1440x900,1024x768,768x1024,375x812
|
|
23
28
|
--wait 1200 Settle time per navigation (ms, 0–60000)
|
|
24
29
|
--timeout 120000 Whole operation deadline (ms, 1000–600000)
|
|
25
|
-
--max-scroll-steps 80 Bounded lazy-loading scroll (1–1000)
|
|
26
30
|
--locale pt-BR Browser locale
|
|
27
31
|
--color-scheme light light | dark
|
|
28
32
|
--json One JSON result on stdout; progress on stderr
|
|
33
|
+
Capture / validate:
|
|
34
|
+
--max-scroll-steps 80 Bounded lazy-loading scroll (1–1000)
|
|
29
35
|
Capture:
|
|
30
36
|
--omit-scripts Omit source scripts and inline event handlers
|
|
37
|
+
--dry-run Check the selector against the page and stop
|
|
31
38
|
--max-resource-mb 20 Maximum copied resource size (0.001–100 MiB)
|
|
32
39
|
--max-total-mb 100 Total resource download budget (0.001–500 MiB)
|
|
33
40
|
Validate:
|
|
@@ -36,6 +43,7 @@ Validate:
|
|
|
36
43
|
|
|
37
44
|
Exit codes: capture 0 = complete, 2 = partial, 1 = error.
|
|
38
45
|
Validate 0 = requested visual/network checks passed, 1 = failed.
|
|
46
|
+
Diff 0 = the exports are the same, 2 = they differ, 1 = error.
|
|
39
47
|
Visual checks do not certify behavior. Use pages you own or have permission to reuse.
|
|
40
48
|
Browser installation is explicit. Set UIPORT_BROWSER_PATH to choose an executable.
|
|
41
49
|
--help and --version work without a browser. Documentation: https://github.com/LorranHippolyte/uiport
|
|
@@ -49,7 +57,7 @@ try {
|
|
|
49
57
|
console.log(json ? JSON.stringify({ version }) : version);
|
|
50
58
|
else {
|
|
51
59
|
if (!Object.hasOwn(allowed, command))
|
|
52
|
-
throw new
|
|
60
|
+
throw new UiportError("USAGE_INVALID", `Unknown command: ${command}`);
|
|
53
61
|
const args = parseArgs(
|
|
54
62
|
argv.slice(command === "browser" && argv[1] === "install" ? 2 : 1),
|
|
55
63
|
allowed[command],
|
|
@@ -60,7 +68,7 @@ try {
|
|
|
60
68
|
console.log(args.json ? JSON.stringify({ version }) : version);
|
|
61
69
|
else if (command === "browser") {
|
|
62
70
|
if (argv[1] !== "install")
|
|
63
|
-
throw new
|
|
71
|
+
throw new UiportError("USAGE_INVALID", "Usage: uiport browser install");
|
|
64
72
|
const child = spawn(
|
|
65
73
|
process.execPath,
|
|
66
74
|
[
|
|
@@ -106,7 +114,8 @@ try {
|
|
|
106
114
|
// A capture or a validation writes exactly one JSON document to stdout.
|
|
107
115
|
// The guard is installed before the command module is loaded, so that
|
|
108
116
|
// anything printed while loading also goes to the diagnostics channel.
|
|
109
|
-
const guarded =
|
|
117
|
+
const guarded =
|
|
118
|
+
command === "capture" || command === "validate" || command === "diff";
|
|
110
119
|
const restore = guarded ? guardStdout() : () => {};
|
|
111
120
|
let result;
|
|
112
121
|
try {
|
|
@@ -115,21 +124,30 @@ try {
|
|
|
115
124
|
} finally {
|
|
116
125
|
restore();
|
|
117
126
|
}
|
|
118
|
-
if (command !== "serve")
|
|
119
|
-
console.log(
|
|
127
|
+
if (command !== "serve" && command !== "examples")
|
|
128
|
+
console.log(
|
|
129
|
+
args.json ? JSON.stringify(result, null, undefined) : report(result),
|
|
130
|
+
);
|
|
120
131
|
process.exitCode =
|
|
121
132
|
result.status === "partial" ? 2 : result.status === "failed" ? 1 : 0;
|
|
122
133
|
}
|
|
123
134
|
}
|
|
124
135
|
} catch (error) {
|
|
136
|
+
const described = describeError(error);
|
|
137
|
+
// The message of the failure is redacted before it reaches any channel.
|
|
138
|
+
const message = safeErrorMessage(error);
|
|
125
139
|
if (json)
|
|
126
140
|
console.log(
|
|
127
141
|
JSON.stringify({
|
|
128
142
|
command: Object.hasOwn(allowed, command) ? command : "help",
|
|
129
143
|
status: "failed",
|
|
130
|
-
error: {
|
|
144
|
+
error: {
|
|
145
|
+
code: described.code,
|
|
146
|
+
message,
|
|
147
|
+
hint: described.hint,
|
|
148
|
+
},
|
|
131
149
|
}),
|
|
132
150
|
);
|
|
133
|
-
else process.stderr.write(
|
|
151
|
+
else process.stderr.write(`${reportError({ ...described, message })}\n`);
|
|
134
152
|
process.exitCode = 1;
|
|
135
153
|
}
|
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
|
|
|
@@ -32,6 +32,14 @@ Contextual custom-property rules that matched the source but lose structural con
|
|
|
32
32
|
|
|
33
33
|
Existing prototype exports are accepted by their legacy root marker; validate does not rewrite them. The locale default remains pt-BR.
|
|
34
34
|
|
|
35
|
+
## Output contract
|
|
36
|
+
|
|
37
|
+
Without `--json` the result is a readable summary on stdout; with `--json` it is one JSON document. Progress always goes to stderr, and a capture or a validation never writes anything else to stdout.
|
|
38
|
+
|
|
39
|
+
A failure carries a stable code and a hint: `USAGE_INVALID`, `BROWSER_NOT_FOUND`, `OUTPUT_NOT_EMPTY`, `SELECTOR_NOT_FOUND`, `SELECTOR_AMBIGUOUS`, `TIMEOUT`, `CANCELLED`, `SOURCE_UNREACHABLE`, `ARTIFACT_MISSING` and `INTERNAL`.
|
|
40
|
+
|
|
41
|
+
`uiport inspect --dir DIR` reads the limitations of an exported section without opening a browser. `uiport capture --dry-run` checks the selector against the page and writes nothing.
|
|
42
|
+
|
|
35
43
|
## Limits and diagnostics
|
|
36
44
|
|
|
37
45
|
- One CSS selector matching one section container, body or html. Body/html export a single whole page without nesting another html/body; html also includes original head scripts.
|
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
|
@@ -3,6 +3,15 @@ import path from "node:path";
|
|
|
3
3
|
import { chromium } from "playwright-core";
|
|
4
4
|
import { parseFragment, serialize } from "parse5";
|
|
5
5
|
import { extractSection, measureRoot } from "./dom.mjs";
|
|
6
|
+
import { UiportError } from "./errors.mjs";
|
|
7
|
+
import {
|
|
8
|
+
ANIMATIONS_ID,
|
|
9
|
+
BEHAVIOR,
|
|
10
|
+
ID_ATTR,
|
|
11
|
+
METADATA_ID,
|
|
12
|
+
ROOT_ATTR,
|
|
13
|
+
ROOT_VALUE,
|
|
14
|
+
} from "./contract.mjs";
|
|
6
15
|
import { parseSrcsetAttribute } from "./srcset.mjs";
|
|
7
16
|
import { resources } from "./resources.mjs";
|
|
8
17
|
import { browserResources } from "./browser-resources.mjs";
|
|
@@ -19,10 +28,71 @@ import {
|
|
|
19
28
|
redactedUrl,
|
|
20
29
|
scrollForLazyContent,
|
|
21
30
|
serializeAttributes,
|
|
31
|
+
navigationError,
|
|
22
32
|
waitForPageStable,
|
|
23
33
|
} from "./lib.mjs";
|
|
24
34
|
|
|
35
|
+
/** Checks the selector against the page without writing anything. */
|
|
36
|
+
async function dryRun(options) {
|
|
37
|
+
const life = lifecycle(options.timeoutMs);
|
|
38
|
+
try {
|
|
39
|
+
const { browser, selected, close } = await launchChromium(chromium, life);
|
|
40
|
+
const context = await browser.newContext({
|
|
41
|
+
viewport: options.viewports[0],
|
|
42
|
+
deviceScaleFactor: 1,
|
|
43
|
+
locale: options.locale,
|
|
44
|
+
colorScheme: options.colorScheme,
|
|
45
|
+
serviceWorkers: "block",
|
|
46
|
+
});
|
|
47
|
+
const page = await context.newPage();
|
|
48
|
+
await page.goto(options.sourceUrl, {
|
|
49
|
+
waitUntil: "domcontentloaded",
|
|
50
|
+
timeout: Math.min(60000, options.timeoutMs),
|
|
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);
|
|
57
|
+
const root = page.locator(options.selector);
|
|
58
|
+
const matches = await root.count();
|
|
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 };
|
|
68
|
+
const version = browser.version();
|
|
69
|
+
await close();
|
|
70
|
+
if (matches !== 1)
|
|
71
|
+
throw new UiportError(
|
|
72
|
+
matches === 0 ? "SELECTOR_NOT_FOUND" : "SELECTOR_AMBIGUOUS",
|
|
73
|
+
`Selector must resolve to exactly one element; found ${matches}`,
|
|
74
|
+
);
|
|
75
|
+
return {
|
|
76
|
+
command: "capture",
|
|
77
|
+
// A root that does not render would make the capture partial.
|
|
78
|
+
status: rendered.visible ? "complete" : "partial",
|
|
79
|
+
dryRun: true,
|
|
80
|
+
selector: options.selector,
|
|
81
|
+
matches,
|
|
82
|
+
visible: rendered.visible,
|
|
83
|
+
browser: { selected, version },
|
|
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;
|
|
89
|
+
} finally {
|
|
90
|
+
await life.close();
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
25
94
|
export async function capture(options) {
|
|
95
|
+
if (options.dryRun) return dryRun(options);
|
|
26
96
|
const { sourceUrl, selector, viewports, settleMs, locale, colorScheme } =
|
|
27
97
|
options;
|
|
28
98
|
await inspectOutput(options.directory);
|
|
@@ -73,10 +143,14 @@ export async function capture(options) {
|
|
|
73
143
|
life.check();
|
|
74
144
|
log(`Capturing ${viewport.name}…`);
|
|
75
145
|
await page.setViewportSize(viewport);
|
|
76
|
-
await page
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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
|
+
});
|
|
80
154
|
await waitForPageStable(page, settleMs);
|
|
81
155
|
if (await scrollForLazyContent(page, options.maxScrollSteps))
|
|
82
156
|
limitation(
|
|
@@ -88,7 +162,8 @@ export async function capture(options) {
|
|
|
88
162
|
const root = page.locator(selector);
|
|
89
163
|
const count = await root.count();
|
|
90
164
|
if (count !== 1)
|
|
91
|
-
throw new
|
|
165
|
+
throw new UiportError(
|
|
166
|
+
count === 0 ? "SELECTOR_NOT_FOUND" : "SELECTOR_AMBIGUOUS",
|
|
92
167
|
`Selector must resolve to exactly one element; found ${count}`,
|
|
93
168
|
);
|
|
94
169
|
// A root that does not render is reported instead of waiting for a
|
|
@@ -111,6 +186,9 @@ export async function capture(options) {
|
|
|
111
186
|
const snapshot = await page.evaluate(extractSection, {
|
|
112
187
|
selector,
|
|
113
188
|
omitScripts: options.omitScripts,
|
|
189
|
+
idAttribute: ID_ATTR,
|
|
190
|
+
rootAttribute: ROOT_ATTR,
|
|
191
|
+
rootValue: ROOT_VALUE,
|
|
114
192
|
});
|
|
115
193
|
captures.push(snapshot);
|
|
116
194
|
await cache.settle();
|
|
@@ -138,7 +216,12 @@ export async function capture(options) {
|
|
|
138
216
|
}
|
|
139
217
|
cssContext = contextualCss(cssParts);
|
|
140
218
|
}
|
|
141
|
-
|
|
219
|
+
// The contextual custom properties are adapted for the exported DOM,
|
|
220
|
+
// which is the first viewport. The identifiers are assigned by position,
|
|
221
|
+
// so an observation from another viewport only describes the same
|
|
222
|
+
// elements while the structure is unchanged.
|
|
223
|
+
if (snapshot.structure === captures[0].structure)
|
|
224
|
+
await cssContext.observe(page, snapshot);
|
|
142
225
|
}
|
|
143
226
|
await cache.settle();
|
|
144
227
|
await close();
|
|
@@ -315,8 +398,10 @@ export async function capture(options) {
|
|
|
315
398
|
"Some observed animations cannot be replayed on DocumentTimeline",
|
|
316
399
|
);
|
|
317
400
|
const metadata = {
|
|
401
|
+
elements: primary.featureCounts.elements,
|
|
402
|
+
assets: assets.stats().assets,
|
|
318
403
|
limitations,
|
|
319
|
-
behavior:
|
|
404
|
+
behavior: BEHAVIOR,
|
|
320
405
|
source: redactedUrl(sourceUrl),
|
|
321
406
|
};
|
|
322
407
|
const html = `<!doctype html>
|
|
@@ -324,22 +409,22 @@ export async function capture(options) {
|
|
|
324
409
|
<head>
|
|
325
410
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
326
411
|
<title>${escapeHtml(primary.title || "UIport — extracted section")}</title>
|
|
327
|
-
<style>${parts.join("\n").
|
|
412
|
+
<style>${parts.join("\n").replace(/<\/style/gi, "<\\/style")}</style>
|
|
328
413
|
${serialize(head)}
|
|
329
414
|
</head>
|
|
330
415
|
<body${serializeAttributes(primary.bodyAttributes)}>
|
|
331
416
|
${serialize(fragment)}
|
|
332
|
-
<script type="application/json" id="
|
|
333
|
-
<script type="application/json" id="
|
|
417
|
+
<script type="application/json" id="${METADATA_ID}">${jsonForInlineScript(metadata)}</script>
|
|
418
|
+
<script type="application/json" id="${ANIMATIONS_ID}">${jsonForInlineScript(animations)}</script>
|
|
334
419
|
<script>
|
|
335
420
|
(() => {
|
|
336
421
|
const find = (id, root = document) => {
|
|
337
|
-
const direct = root.querySelector('[
|
|
422
|
+
const direct = root.querySelector('[${ID_ATTR}="' + CSS.escape(id) + '"]');
|
|
338
423
|
if (direct) return direct;
|
|
339
424
|
for (const element of root.querySelectorAll('*')) if (element.shadowRoot) { const found = find(id, element.shadowRoot); if (found) return found; }
|
|
340
425
|
return null;
|
|
341
426
|
};
|
|
342
|
-
for (const record of JSON.parse(document.getElementById('
|
|
427
|
+
for (const record of JSON.parse(document.getElementById('${ANIMATIONS_ID}').textContent)) {
|
|
343
428
|
const target = find(record.targetId);
|
|
344
429
|
if (!target) continue;
|
|
345
430
|
try {
|
|
@@ -368,9 +453,13 @@ ${serialize(fragment)}
|
|
|
368
453
|
...assets.stats(),
|
|
369
454
|
elements: primary.featureCounts.elements,
|
|
370
455
|
animationsReplayed: animations.length,
|
|
371
|
-
behavior:
|
|
456
|
+
behavior: BEHAVIOR,
|
|
372
457
|
limitations,
|
|
373
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;
|
|
374
463
|
} finally {
|
|
375
464
|
await life.close();
|
|
376
465
|
await stage?.cleanup();
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// The contract between a capture and the validation of its result. The
|
|
2
|
+
// markers live here so that a rename cannot silently break one side: the
|
|
3
|
+
// validation reads the markers of the exported document, and an artifact that
|
|
4
|
+
// does not carry them is reported instead of being read as an empty one.
|
|
5
|
+
export const ROOT_ATTR = "data-uiport-root";
|
|
6
|
+
export const ROOT_VALUE = "true";
|
|
7
|
+
export const ID_ATTR = "data-uiport-id";
|
|
8
|
+
export const METADATA_ID = "uiport-metadata";
|
|
9
|
+
export const ANIMATIONS_ID = "uiport-animations";
|
|
10
|
+
export const BEHAVIOR = "not-tested";
|
|
11
|
+
|
|
12
|
+
// Artifacts exported before UIport used another marker. They are still
|
|
13
|
+
// accepted for validation, and the folder is never rewritten.
|
|
14
|
+
export const LEGACY_ROOT_ATTR = "data-effect-extractor-root";
|
package/scripts/css-context.mjs
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import postcss from "postcss";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { ID_ATTR } from "./contract.mjs";
|
|
3
4
|
|
|
4
5
|
// Inspect only selector context. No stylesheet or script is executed in this
|
|
5
6
|
// detached document. Keep original declarations, specificity and enclosing
|
|
6
7
|
// media/supports/container/layer rules rather than freezing computed values.
|
|
7
|
-
function missingSelectors({ snapshot, rules }) {
|
|
8
|
+
function missingSelectors({ snapshot, rules, idAttribute }) {
|
|
8
9
|
const copy = document.implementation.createHTMLDocument("");
|
|
9
10
|
for (const { name, value } of snapshot.htmlAttributes)
|
|
10
11
|
copy.documentElement.setAttribute(name, value);
|
|
@@ -20,8 +21,8 @@ function missingSelectors({ snapshot, rules }) {
|
|
|
20
21
|
}
|
|
21
22
|
container.innerHTML = snapshot.html;
|
|
22
23
|
const clones = new Map(
|
|
23
|
-
[...copy.querySelectorAll(
|
|
24
|
-
element.getAttribute(
|
|
24
|
+
[...copy.querySelectorAll(`[${idAttribute}]`)].map((element) => [
|
|
25
|
+
element.getAttribute(idAttribute),
|
|
25
26
|
element,
|
|
26
27
|
]),
|
|
27
28
|
);
|
|
@@ -30,7 +31,7 @@ function missingSelectors({ snapshot, rules }) {
|
|
|
30
31
|
for (const selector of rule.selectors) {
|
|
31
32
|
try {
|
|
32
33
|
for (const element of document.querySelectorAll(selector)) {
|
|
33
|
-
const id = element.getAttribute(
|
|
34
|
+
const id = element.getAttribute(idAttribute);
|
|
34
35
|
const cloned = clones.get(id);
|
|
35
36
|
if (cloned && !cloned.matches(selector))
|
|
36
37
|
result.push({ rule: rule.id, selector, id });
|
|
@@ -115,6 +116,7 @@ export function contextualCss(stylesheets) {
|
|
|
115
116
|
const result = await page.evaluate(missingSelectors, {
|
|
116
117
|
snapshot,
|
|
117
118
|
rules: descriptors,
|
|
119
|
+
idAttribute: ID_ATTR,
|
|
118
120
|
});
|
|
119
121
|
for (const item of result) {
|
|
120
122
|
missing.set(`${item.rule}|${item.selector}|${item.id}`, item);
|
|
@@ -149,7 +151,7 @@ export function contextualCss(stylesheets) {
|
|
|
149
151
|
const selectors = descriptors[id].selectors.map((selector) => {
|
|
150
152
|
const ids = observations.get(`${id}|${selector}`);
|
|
151
153
|
return ids?.size
|
|
152
|
-
? `:is(${selector}, :where(${[...ids].map((elementId) => `[
|
|
154
|
+
? `:is(${selector}, :where(${[...ids].map((elementId) => `[${ID_ATTR}="${elementId}"]`).join(", ")}))`
|
|
153
155
|
: selector;
|
|
154
156
|
});
|
|
155
157
|
let fallback = postcss.rule({ selector: selectors.join(", ") });
|