uiport 0.1.3 → 0.1.5

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 CHANGED
@@ -4,6 +4,36 @@ Notable changes are documented here. Versions follow Semantic Versioning.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.1.5] — 2026-11-29
8
+
9
+ ### Added
10
+ - `capture` and `validate` accept `--storage-state FILE`, the session state file the browser itself produces, so a section that sits behind a login can be captured. The file belongs to the user: it is read, used on the source page only, never copied into the output, and its path is not written anywhere. The export opens without it.
11
+ - `docs/analysis.md` records the engineering review: what was examined, what was found, what was measured, what the independent reviews found, and what was deliberately left alone.
12
+
13
+ ### Changed
14
+ - The support matrix states two boundaries the tool always had. The export is the DOM of the first viewport, so a section that changes the class of an element across viewports can bind a contextual property to the rule of another viewport; the validation reports the consequence. The redaction covers credentials, queries and fragments and keeps the path of a URL.
15
+
16
+ ## [0.1.4] — 2026-11-29
17
+
18
+ ### Changed
19
+ - 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.
20
+ - 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.
21
+ - The type check runs on the native TypeScript 7 compiler, and the options of a command now have a declared shape.
22
+
23
+ ### Fixed
24
+ - 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.
25
+ - 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.
26
+ - 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.
27
+ - 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.
28
+ - 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.
29
+ - A page that cannot be reached reports `SOURCE_UNREACHABLE`, with the address it could not reach and without its query or fragment.
30
+ - 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.
31
+ - 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.
32
+ - The inspection refuses a directory that is not an exported section, instead of reading it as one without limitations.
33
+ - 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.
34
+ - 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.
35
+ - 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.
36
+
7
37
  ## [0.1.3] — 2026-11-28
8
38
 
9
39
  ### Added
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  UIport captures a rendered section as editable HTML, original CSS and local assets. Inspect it, compare it with the source, and make it a starting point for your own work. Runs locally, from your terminal or coding agent. No account, API key or hosted service.
6
6
 
7
- [Português brasileiro](README.pt-BR.md) · [Support matrix](docs/support.md) · [Contributing](CONTRIBUTING.md)
7
+ [Português brasileiro](README.pt-BR.md) · [Support matrix](docs/support.md) · [Engineering review](docs/analysis.md) · [Contributing](CONTRIBUTING.md)
8
8
 
9
9
  ![An original responsive section created for UIport](docs/demo.png)
10
10
 
@@ -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.3 browser install
29
- npx uiport@0.1.3 capture --url "https://your-site.example" --selector "#hero" --out ./my-section
30
- npx uiport@0.1.3 serve --dir ./my-section
31
- npx uiport@0.1.3 validate --url "https://your-site.example" --selector "#hero" --dir ./my-section
28
+ npx uiport@0.1.5 browser install
29
+ npx uiport@0.1.5 capture --url "https://your-site.example" --selector "#hero" --out ./my-section
30
+ npx uiport@0.1.5 serve --dir ./my-section
31
+ npx uiport@0.1.5 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.
@@ -68,7 +68,9 @@ Open `http://127.0.0.1:4174`. You can move that output directory and serve it ag
68
68
  | `browser install` | Install Chromium matched to the bundled Playwright version |
69
69
  | `--help` / `--version` | Inspect the CLI without starting a browser |
70
70
 
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.
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.
72
+
73
+ A section that sits behind a login can be captured with `--storage-state FILE`, the session state file the browser itself produces. The file is yours: UIport reads it, uses it on the source page only, and never copies it into the output or writes its path anywhere. The exported section opens without it, exactly as the person who receives it would open it. 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.
72
74
 
73
75
  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.
74
76
 
@@ -81,12 +83,14 @@ Set `UIPORT_BROWSER_PATH` to explicitly choose an executable. Otherwise UIport t
81
83
  - **Exit 1:** command failed, or validation failed its requested checks.
82
84
  - **Validation exit 0:** the observed visual/network checks passed. Behavior remains `not-tested`.
83
85
 
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.
86
+ 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
87
 
86
88
  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
89
 
88
90
  Migration compatibility and intentional command/default changes: [migration notes](docs/migration.md).
89
91
 
92
+ What the engineering review found, what was changed, what was measured and what was deliberately left alone: [engineering review](docs/analysis.md).
93
+
90
94
  ## Use with a coding agent
91
95
 
92
96
  Start with [uiport.md](uiport.md). Read [skills/uiport/SKILL.md](skills/uiport/SKILL.md), or copy it into your agent's skill directory. The same file ships with the npm package. The agent should capture, read limitations, inspect supported interactions and validate, without inventing replacement effects. No LLM API is called by UIport itself.
package/README.pt-BR.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  O UIport captura uma seção renderizada como HTML editável, CSS original e assets locais. Inspecione a implementação, compare com a origem e use como base para continuar seu projeto. Executa localmente, pelo terminal ou pelo seu agente de código, sem conta, chave de IA ou serviço hospedado.
6
6
 
7
- [English](README.md) · [Matriz de suporte](docs/support.md) · [Contribuição](CONTRIBUTING.md)
7
+ [English](README.md) · [Matriz de suporte](docs/support.md) · [Revisão de engenharia](docs/analysis.md) · [Contribuição](CONTRIBUTING.md)
8
8
 
9
9
  ![Seção responsiva autoral criada para o UIport](docs/demo.png)
10
10
 
@@ -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.3 browser install
29
- npx uiport@0.1.3 capture --url "https://seu-site.example" --selector "#hero" --out ./minha-secao
30
- npx uiport@0.1.3 serve --dir ./minha-secao
31
- npx uiport@0.1.3 validate --url "https://seu-site.example" --selector "#hero" --dir ./minha-secao
28
+ npx uiport@0.1.5 browser install
29
+ npx uiport@0.1.5 capture --url "https://seu-site.example" --selector "#hero" --out ./minha-secao
30
+ npx uiport@0.1.5 serve --dir ./minha-secao
31
+ npx uiport@0.1.5 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.
@@ -68,7 +68,9 @@ Abra `http://127.0.0.1:4174`. A pasta de saída pode ser movida e servida novame
68
68
  | `browser install` | Instala Chromium compatível com a versão de Playwright do pacote |
69
69
  | `--help` / `--version` | Mostra ajuda ou versão sem abrir navegador |
70
70
 
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.
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.
72
+
73
+ Uma seção que fica atrás de um login pode ser capturada com `--storage-state FILE`, o arquivo de estado de sessão que o próprio browser produz. O arquivo é seu: o UIport o lê, usa apenas na página de origem e nunca o copia para a saída nem grava o caminho dele em lugar algum. A seção exportada abre sem ele, exatamente como abriria para quem a recebe. 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.
72
74
 
73
75
  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.
74
76
 
@@ -81,12 +83,14 @@ A captura limita recursos copiados a 20 MiB por arquivo e 100 MiB no total, conf
81
83
  - **Retorno 1:** falha operacional ou falha das verificações pedidas no validate.
82
84
  - **Validate retorna 0:** verificações visuais/de rede passaram nos estados observados. Comportamento continua `not-tested`.
83
85
 
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.
86
+ 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
87
 
86
88
  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
89
 
88
90
  Compatibilidade com o protótipo e mudanças intencionais de comandos/limites: [notas de migração](docs/migration.md).
89
91
 
92
+ O que a revisão de engenharia encontrou, o que mudou, o que foi medido e o que foi deixado de fora de propósito: [revisão de engenharia](docs/analysis.md).
93
+
90
94
  ## Usar com agentes e contribuir
91
95
 
92
96
  Comece por [uiport.md](uiport.md). Leia [skills/uiport/SKILL.md](skills/uiport/SKILL.md) ou copie para a pasta de skills do seu agente. A skill também acompanha o pacote npm. O agente deve capturar, ler limitações, inspecionar interações suportadas e validar, sem inventar efeitos substitutos. O UIport não chama uma API de LLM.
package/bin/cli.mjs CHANGED
@@ -27,10 +27,12 @@ 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)
35
+ --storage-state FILE Session state you prepared; used on the source only
34
36
  Capture:
35
37
  --omit-scripts Omit source scripts and inline event handlers
36
38
  --dry-run Check the selector against the page and stop
@@ -42,6 +44,7 @@ Validate:
42
44
 
43
45
  Exit codes: capture 0 = complete, 2 = partial, 1 = error.
44
46
  Validate 0 = requested visual/network checks passed, 1 = failed.
47
+ Diff 0 = the exports are the same, 2 = they differ, 1 = error.
45
48
  Visual checks do not certify behavior. Use pages you own or have permission to reuse.
46
49
  Browser installation is explicit. Set UIPORT_BROWSER_PATH to choose an executable.
47
50
  --help and --version work without a browser. Documentation: https://github.com/LorranHippolyte/uiport
@@ -66,7 +69,7 @@ try {
66
69
  console.log(args.json ? JSON.stringify({ version }) : version);
67
70
  else if (command === "browser") {
68
71
  if (argv[1] !== "install")
69
- throw new Error("Usage: uiport browser install");
72
+ throw new UiportError("USAGE_INVALID", "Usage: uiport browser install");
70
73
  const child = spawn(
71
74
  process.execPath,
72
75
  [
@@ -108,11 +111,12 @@ try {
108
111
  );
109
112
  process.exitCode = Number(code);
110
113
  } else {
111
- const options = optionsFor(command, args);
114
+ const options = await optionsFor(command, args);
112
115
  // A capture or a validation writes exactly one JSON document to stdout.
113
116
  // The guard is installed before the command module is loaded, so that
114
117
  // anything printed while loading also goes to the diagnostics channel.
115
- const guarded = command === "capture" || command === "validate";
118
+ const guarded =
119
+ command === "capture" || command === "validate" || command === "diff";
116
120
  const restore = guarded ? guardStdout() : () => {};
117
121
  let result;
118
122
  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. It applies to every 0.1.x release unless a row says otherwise.
3
+ This matrix describes the 0.1.x CLI line and was last verified against 0.1.5. 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
 
@@ -49,9 +49,11 @@ A failure carries a stable code and a hint: `USAGE_INVALID`, `BROWSER_NOT_FOUND`
49
49
  - 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.
50
50
  - 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.
51
51
  - 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.
52
- - 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.
52
+ - Public HTTP(S) only; the tool imports no session of its own. A section that sits behind a login can be captured with `--storage-state FILE`, the session state file the browser itself produces. The file is read, used on the source page only, and never copied into the output; the export opens without it. The path of the file is not written to the artifact either.
53
+ - Local development URLs are supported. The capture reuses its own navigation responses; fallback fetch does not import browser cookies.
53
54
  - Source JavaScript executes in the capture browser. The optional --omit-scripts mode is not a general-purpose sanitizer or sandbox for hostile websites.
54
- - 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.
55
+ - 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. The path of a URL is kept, because it identifies the resource; a secret carried in a path segment is not masked, so avoid capturing an address that carries one.
56
+ - The exported DOM is the one captured at the first viewport. When the source changes the class or another attribute of an element across viewports without changing the element structure, the contextual custom property is expected to follow the export, but an observation that lands between the extraction and the measurement can bind it to the rule of another viewport. `validate` reports the consequence as a visual difference; when a section behaves this way, capture it at the viewport you intend to deliver.
55
57
  - Network/rendering differences, DOM changed by runtime, special CSS/HTML features and states not observed can still require manual work. No invented replacement effects.
56
58
 
57
59
  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`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "uiport",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
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": "7.3.0",
66
- "pixelmatch": "7.1.0",
67
- "playwright-core": "1.62.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.28",
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": "22.19.0",
75
- "eslint": "10.11.0",
76
- "prettier": "3.6.2",
77
- "typescript": "5.9.3"
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
  }
@@ -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
 
@@ -42,6 +43,8 @@ async function dryRun(options) {
42
43
  locale: options.locale,
43
44
  colorScheme: options.colorScheme,
44
45
  serviceWorkers: "block",
46
+ // The session the user prepared, and only on the page of the source.
47
+ ...(options.storageState ? { storageState: options.storageState } : {}),
45
48
  });
46
49
  const page = await context.newPage();
47
50
  await page.goto(options.sourceUrl, {
@@ -49,10 +52,21 @@ async function dryRun(options) {
49
52
  timeout: Math.min(60000, options.timeoutMs),
50
53
  });
51
54
  await waitForPageStable(page, options.settleMs);
55
+ // The check scrolls like the capture does, so a section that only appears
56
+ // after the page scrolls is found by both.
57
+ await scrollForLazyContent(page, options.maxScrollSteps);
58
+ await waitForPageStable(page, options.settleMs);
52
59
  const root = page.locator(options.selector);
53
60
  const matches = await root.count();
54
- const visible =
55
- matches === 1 ? await root.isVisible().catch(() => false) : false;
61
+ // The visibility is measured the same way the capture measures it, so the
62
+ // check does not promise a result the capture would not give.
63
+ const rendered =
64
+ matches === 1
65
+ ? await root.evaluate(measureRoot).catch(() => ({
66
+ hidden: true,
67
+ visible: false,
68
+ }))
69
+ : { hidden: false, visible: false };
56
70
  const version = browser.version();
57
71
  await close();
58
72
  if (matches !== 1)
@@ -62,13 +76,18 @@ async function dryRun(options) {
62
76
  );
63
77
  return {
64
78
  command: "capture",
65
- status: "complete",
79
+ // A root that does not render would make the capture partial.
80
+ status: rendered.visible ? "complete" : "partial",
66
81
  dryRun: true,
67
82
  selector: options.selector,
68
83
  matches,
69
- visible,
84
+ visible: rendered.visible,
70
85
  browser: { selected, version },
71
86
  };
87
+ } catch (error) {
88
+ // A cancellation is reported with its own code, even when the browser
89
+ // rejected the pending operation first.
90
+ throw life.failure() || error;
72
91
  } finally {
73
92
  await life.close();
74
93
  }
@@ -92,6 +111,8 @@ export async function capture(options) {
92
111
  locale,
93
112
  colorScheme,
94
113
  serviceWorkers: "block",
114
+ // The session the user prepared, and only on the page of the source.
115
+ ...(options.storageState ? { storageState: options.storageState } : {}),
95
116
  });
96
117
  const page = await context.newPage();
97
118
  const cache = browserResources(page, options, life.signal);
@@ -126,10 +147,14 @@ export async function capture(options) {
126
147
  life.check();
127
148
  log(`Capturing ${viewport.name}…`);
128
149
  await page.setViewportSize(viewport);
129
- await page.goto(sourceUrl, {
130
- waitUntil: "domcontentloaded",
131
- timeout: Math.min(60000, options.timeoutMs),
132
- });
150
+ await page
151
+ .goto(sourceUrl, {
152
+ waitUntil: "domcontentloaded",
153
+ timeout: Math.min(60000, options.timeoutMs),
154
+ })
155
+ .catch((error) => {
156
+ throw life.failure() || navigationError(error, sourceUrl);
157
+ });
133
158
  await waitForPageStable(page, settleMs);
134
159
  if (await scrollForLazyContent(page, options.maxScrollSteps))
135
160
  limitation(
@@ -382,6 +407,9 @@ export async function capture(options) {
382
407
  limitations,
383
408
  behavior: BEHAVIOR,
384
409
  source: redactedUrl(sourceUrl),
410
+ // The fact that a session was used is worth recording; the file that
411
+ // carries it is not, and it never leaves the machine of the user.
412
+ ...(options.storageState ? { authenticated: true } : {}),
385
413
  };
386
414
  const html = `<!doctype html>
387
415
  <html lang="${escapeHtml(locale)}"${serializeAttributes(primary.htmlAttributes)}>
@@ -435,6 +463,10 @@ ${serialize(fragment)}
435
463
  behavior: BEHAVIOR,
436
464
  limitations,
437
465
  };
466
+ } catch (error) {
467
+ // A cancellation is reported with its own code, even when the browser
468
+ // rejected the pending operation first.
469
+ throw life.failure() || error;
438
470
  } finally {
439
471
  await life.close();
440
472
  await stage?.cleanup();
@@ -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) => `[data-uiport-id="${elementId}"]`).join(", ")}))`
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
- const html = await fs.readFile(path.join(directory, "index.html"), "utf8");
24
- const match = html.match(
25
- new RegExp(
26
- `<script type="application/json" id="${METADATA_ID}">([\\s\\S]*?)</script>`,
27
- ),
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
- if (!match) return null;
49
+ try {
30
50
  return JSON.parse(match[1]);
31
51
  } catch {
32
- return null;
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
- const rootSelector = `[${ROOT_ATTR}="${ROOT_VALUE}"]`;
37
- const legacyRootSelector = `[${LEGACY_ROOT_ATTR}="${ROOT_VALUE}"]`;
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
- for (const directory of [before, after])
44
- await fs.access(path.join(directory, "index.html"));
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 Error(
116
+ throw new UiportError(
117
+ "ARTIFACT_DAMAGED",
78
118
  "An exported section is missing its extraction root",
79
119
  );
80
- shots.push(await root.screenshot({ animations: "disabled" }));
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 > 20_000_000)
87
- throw new Error("Comparison exceeds screenshot limit");
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
- left.width === right.width && left.height === right.height,
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 beforeMetadata = await readMetadata(before);
125
- const afterMetadata = await readMetadata(after);
126
- const codes = (metadata) =>
127
- (metadata?.limitations || []).map((entry) => entry.code).sort();
128
- const added = codes(afterMetadata).filter(
129
- (code) => !codes(beforeMetadata).includes(code),
177
+ const added = difference(
178
+ afterMetadata.limitations || [],
179
+ beforeMetadata.limitations || [],
130
180
  );
131
- const removed = codes(beforeMetadata).filter(
132
- (code) => !codes(afterMetadata).includes(code),
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
- status: changed || added.length ? "partial" : "complete",
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 renders = (node) => {
8
- const style = getComputedStyle(node);
9
- if (style.display === "none" || style.visibility === "hidden") return false;
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
- 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);
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
- (style.display === "none" ||
38
- style.visibility === "hidden" ||
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
 
@@ -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
 
@@ -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
- let metadata = {};
25
- if (match)
26
- try {
27
- metadata = JSON.parse(match[1]);
28
- } catch {
29
- metadata = {};
30
- }
31
- let assets;
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
- assets = (await fs.readdir(path.join(options.directory, "assets"))).length;
33
+ metadata = JSON.parse(match[1]);
34
34
  } catch {
35
- assets = 0;
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 Error("Refusing a filesystem root as output");
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.mkdir(destination, { recursive: true }).catch(() => {});
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 Error("UIPORT_BROWSER_PATH does not exist");
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()));
@@ -1,4 +1,5 @@
1
1
  // @ts-check
2
+ import fs from "node:fs/promises";
2
3
  import path from "node:path";
3
4
  import { UiportError } from "./errors.mjs";
4
5
 
@@ -22,6 +23,7 @@ export const allowed = {
22
23
  "omit-scripts",
23
24
  "max-scroll-steps",
24
25
  "dry-run",
26
+ "storage-state",
25
27
  ],
26
28
  validate: [
27
29
  ...common,
@@ -30,6 +32,7 @@ export const allowed = {
30
32
  "max-diff-ratio",
31
33
  "allow-external",
32
34
  "max-scroll-steps",
35
+ "storage-state",
33
36
  ],
34
37
  serve: [...common, "dir", "port"],
35
38
  inspect: [...common, "dir"],
@@ -93,6 +96,46 @@ export function required(args, key) {
93
96
  return value.trim();
94
97
  }
95
98
 
99
+ /**
100
+ * Reads the session state the user prepared, when one is given. The file
101
+ * belongs to the user and stays on their machine: it is read by the browser
102
+ * and never copied into the output.
103
+ * @param {string | boolean | undefined} value
104
+ */
105
+ export async function storageState(value) {
106
+ if (typeof value !== "string" || !value) return undefined;
107
+ const file = path.resolve(value);
108
+ let content;
109
+ try {
110
+ content = await fs.readFile(file, "utf8");
111
+ } catch (error) {
112
+ throw new UiportError(
113
+ "USAGE_INVALID",
114
+ `The session state file could not be read: ${file}`,
115
+ );
116
+ }
117
+ let parsed;
118
+ try {
119
+ parsed = JSON.parse(content);
120
+ } catch {
121
+ throw new UiportError(
122
+ "USAGE_INVALID",
123
+ `The session state file is not valid JSON: ${file}`,
124
+ );
125
+ }
126
+ if (typeof parsed !== "object" || parsed === null)
127
+ throw new UiportError(
128
+ "USAGE_INVALID",
129
+ `The session state file is not a session state: ${file}`,
130
+ );
131
+ if (!Array.isArray(parsed.cookies) && !parsed.origins)
132
+ throw new UiportError(
133
+ "USAGE_INVALID",
134
+ `The session state file has neither cookies nor origins: ${file}`,
135
+ );
136
+ return file;
137
+ }
138
+
96
139
  /** @param {unknown} value @param {string} key @param {number} fallback @param {number} min @param {number} max */
97
140
  export function numeric(value, key, fallback, min, max) {
98
141
  const n = value === undefined ? fallback : Number(value);
@@ -147,15 +190,43 @@ export function httpUrl(value) {
147
190
  return url.href;
148
191
  }
149
192
 
150
- /** @param {string} command @param {Record<string, string | boolean>} args */
151
- export function optionsFor(command, args) {
193
+ /**
194
+ * @typedef {object} Options
195
+ * @property {boolean} json
196
+ * @property {boolean} omitScripts
197
+ * @property {boolean} dryRun
198
+ * @property {string} sourceUrl
199
+ * @property {string} selector
200
+ * @property {string} before
201
+ * @property {string} after
202
+ * @property {string} directory
203
+ * @property {string | undefined} storageState
204
+ * @property {{width:number,height:number,name:string}[]} viewports
205
+ * @property {number} settleMs
206
+ * @property {number} timeoutMs
207
+ * @property {string} locale
208
+ * @property {'light' | 'dark'} colorScheme
209
+ * @property {number} maxResourceBytes
210
+ * @property {number} maxTotalBytes
211
+ * @property {number} maxScrollSteps
212
+ * @property {number} maximumDifferenceRatio
213
+ * @property {boolean} allowExternal
214
+ * @property {number} port
215
+ */
216
+
217
+ /** @param {string} command @param {Record<string, string | boolean>} args @returns {Promise<Options>} */
218
+ export async function optionsFor(command, args) {
219
+ /** @type {Options} */
152
220
  const options = {
153
221
  json: args.json === true,
154
222
  omitScripts: args["omit-scripts"] === true,
155
223
  dryRun: args["dry-run"] === true,
156
224
  sourceUrl: "",
157
225
  selector: "",
226
+ before: "",
227
+ after: "",
158
228
  directory: "",
229
+ storageState: undefined,
159
230
  viewports: parseViewports(
160
231
  typeof args.viewports === "string" ? args.viewports : undefined,
161
232
  ),
@@ -191,15 +262,22 @@ export function optionsFor(command, args) {
191
262
  port: numeric(args.port, "port", 4173, 0, 65535),
192
263
  };
193
264
  if (!["light", "dark"].includes(options.colorScheme))
194
- throw new Error("--color-scheme must be light or dark");
265
+ throw new UiportError(
266
+ "USAGE_INVALID",
267
+ "--color-scheme must be light or dark",
268
+ );
195
269
  if (
196
270
  !Number.isInteger(options.port) ||
197
271
  !Number.isInteger(options.maxScrollSteps)
198
272
  )
199
- throw new Error("--port and --max-scroll-steps must be integers");
273
+ throw new UiportError(
274
+ "USAGE_INVALID",
275
+ "--port and --max-scroll-steps must be integers",
276
+ );
200
277
  if (command === "capture" || command === "validate") {
201
278
  options.sourceUrl = httpUrl(required(args, "url"));
202
279
  options.selector = required(args, "selector");
280
+ options.storageState = await storageState(args["storage-state"]);
203
281
  }
204
282
  if (command === "diff") {
205
283
  options.before = path.resolve(required(args, "before"));
@@ -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
- lines.push(
77
- ` ! ${entry.viewport} — ${(visual.differenceRatio * 100).toFixed(1)}% of the pixels differ (limit ${(visual.maximumDifferenceRatio * 100).toFixed(0)}%)`,
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
- lines.push(
88
- changed.length
89
- ? `UIport: the two exports differ in ${changed.length} of ${result.results.length} viewports`
90
- : `UIport: the two exports are identical in ${result.results.length} viewports`,
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
- ` ! ${entry.viewport} — ${(entry.differenceRatio * 100).toFixed(1)}% of the pixels differ`,
105
+ `UIport: the two exports are identical in ${result.results.length} ${views}`,
95
106
  );
96
- for (const code of result.limitations.added)
107
+ else {
97
108
  lines.push(
98
- ` + ${code} — a limitation the second export reports and the first does not`,
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
  }
@@ -12,7 +12,7 @@ import {
12
12
  limitation,
13
13
  } from "./lib.mjs";
14
14
 
15
- /** @param {string} directory @param {import('./options.mjs').optionsFor extends (...args: any[]) => infer T ? T : never} options @param {AbortSignal} signal @param {{code:string,message:string}[]} limitations @param {{get:(url:string)=>Promise<any>} | undefined} [browserCache] */
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 first = parsed.nodes.find(
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(parsed.nodes.indexOf(first) + 1))}`;
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(parsed.nodes.indexOf(first) + 1)
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.type === "function" ? valueParser.stringify(layer.nodes) : "",
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 = tail[0];
280
- tail.shift();
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",
@@ -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
- await fs.access(path.join(options.directory, "index.html"));
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 {
@@ -60,15 +70,24 @@ export async function validate(options) {
60
70
  serviceWorkers: "block",
61
71
  };
62
72
  // Separate contexts ensure the exported page cannot inherit source cookies/storage.
63
- const sourceContext = await browser.newContext(settings);
73
+ // The session is used on the source only: the exported page must open
74
+ // without it, exactly as a reader would receive it.
75
+ const sourceContext = await browser.newContext({
76
+ ...settings,
77
+ ...(options.storageState ? { storageState: options.storageState } : {}),
78
+ });
64
79
  const localContext = await browser.newContext(settings);
65
80
  try {
66
81
  const source = await sourceContext.newPage();
67
82
  source.setDefaultTimeout(10000);
68
- await source.goto(options.sourceUrl, {
69
- waitUntil: "domcontentloaded",
70
- timeout: Math.min(options.timeoutMs, 60000),
71
- });
83
+ await source
84
+ .goto(options.sourceUrl, {
85
+ waitUntil: "domcontentloaded",
86
+ timeout: Math.min(options.timeoutMs, 60000),
87
+ })
88
+ .catch((error) => {
89
+ throw life.failure() || navigationError(error, options.sourceUrl);
90
+ });
72
91
  await waitForPageStable(source, options.settleMs);
73
92
  const scrollLimited = await scrollForLazyContent(
74
93
  source,
@@ -135,11 +154,8 @@ export async function validate(options) {
135
154
  });
136
155
  await waitForPageStable(local, options.settleMs);
137
156
  // Legacy root markers remain supported for existing user exports.
138
- const isCurrent = (await local
139
- .locator(`[${ROOT_ATTR}="${ROOT_VALUE}"]`)
140
- .count())
141
- ? true
142
- : false;
157
+ const isCurrent =
158
+ (await local.locator(`[${ROOT_ATTR}="${ROOT_VALUE}"]`).count()) > 0;
143
159
  const rootSelector = isCurrent
144
160
  ? `[${ROOT_ATTR}="${ROOT_VALUE}"]`
145
161
  : `[${LEGACY_ROOT_ATTR}="${ROOT_VALUE}"]`;
@@ -151,7 +167,7 @@ export async function validate(options) {
151
167
  // no limitation at all.
152
168
  if (isCurrent && !(await local.locator(`#${METADATA_ID}`).count()))
153
169
  throw new Error(
154
- "The exported section has no UIport metadata; it was modified after the capture",
170
+ "The exported section has no UIport metadata; capture it again",
155
171
  );
156
172
  const localBox = await localRoot.boundingBox();
157
173
  if (!localBox || localBox.width <= 0 || localBox.height <= 0)
@@ -238,6 +254,10 @@ export async function validate(options) {
238
254
  behavior: BEHAVIOR,
239
255
  results,
240
256
  };
257
+ } catch (error) {
258
+ // A cancellation is reported with its own code, even when the browser
259
+ // rejected the pending operation first.
260
+ throw life.failure() || error;
241
261
  } finally {
242
262
  await life.close();
243
263
  }
@@ -8,15 +8,16 @@ 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.3` is the pinned form. When testing an unpublished version, use `node bin/cli.mjs` from its checkout.
11
+ 2. Use the installed CLI or source checkout. `npx uiport@0.1.5` 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.
15
- 6. 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. With `--json` stdout carries one JSON document; without it, stdout carries a readable summary and progress goes to stderr.
16
- 7. Preview with `uiport serve --dir "DIRECTORY"` and compare with `uiport validate --url "URL" --selector "SELECTOR" --dir "DIRECTORY" --json`, using the same viewport/locale/color-scheme options. `uiport inspect --dir "DIRECTORY" --json` reads the limitations of an artifact without opening a browser.
17
- 8. Inspect hover/focus, animation and relevant interactions separately. Validation disables animation for screenshots and reports behavior as not tested. Source scripts inside the selection, inline handlers and recognized visual library scripts are retained by default. Use capture --omit-scripts to omit them explicitly. Outside initialization, listeners and framework dependencies are not generically recovered; inspect SOURCE_RUNTIME_UNVERIFIED.
18
- 9. If an effect cannot be isolated from original source, explain the limitation. Do not create a visually similar substitute and call it an extraction. Manual integration of necessary original runtime code is separate work requiring inspection and validation.
19
- 10. Deliver `index.html` and `assets/` only in the extraction folder. Put reports/screenshots outside it. State the path, verified behavior and remaining limitations.
15
+ 6. When the section sits behind a login, add `--storage-state "FILE"`, the session state file the browser itself produces. Use it only when the user owns the session and asked for it: the file is read, used on the source page only, never copied into the output, and its path is not written anywhere. The export opens without it.
16
+ 7. 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. With `--json` stdout carries one JSON document; without it, stdout carries a readable summary and progress goes to stderr.
17
+ 8. Preview with `uiport serve --dir "DIRECTORY"` and compare with `uiport validate --url "URL" --selector "SELECTOR" --dir "DIRECTORY" --json`, using the same viewport/locale/color-scheme options. `uiport inspect --dir "DIRECTORY" --json` reads the limitations of an artifact without opening a browser.
18
+ 9. Inspect hover/focus, animation and relevant interactions separately. Validation disables animation for screenshots and reports behavior as not tested. Source scripts inside the selection, inline handlers and recognized visual library scripts are retained by default. Use capture --omit-scripts to omit them explicitly. Outside initialization, listeners and framework dependencies are not generically recovered; inspect SOURCE_RUNTIME_UNVERIFIED.
19
+ 10. If an effect cannot be isolated from original source, explain the limitation. Do not create a visually similar substitute and call it an extraction. Manual integration of necessary original runtime code is separate work requiring inspection and validation.
20
+ 11. Deliver `index.html` and `assets/` only in the extraction folder. Put reports/screenshots outside it. State the path, verified behavior and remaining limitations.
20
21
 
21
22
  ## When the command fails
22
23
 
@@ -31,6 +32,11 @@ The error document carries a `code` and a `hint`.
31
32
  | `SELECTOR_AMBIGUOUS` | Narrow the selector, or capture the whole page with `--selector body`. |
32
33
  | `TIMEOUT` | Raise `--timeout` or reduce `--viewports`. |
33
34
  | `CANCELLED` | The run was interrupted. |
35
+ | `SOURCE_UNREACHABLE` | The page could not be reached: check the address and that the service is up. |
36
+ | `ARTIFACT_MISSING` | The directory has no exported section: capture it first. |
37
+ | `ARTIFACT_DAMAGED` | The export has no metadata or no extraction root: capture it again. |
38
+ | `COMPARISON_TOO_LARGE` | The section is above 20 megapixels: compare a narrower section. |
39
+ | `INTERNAL` | An unexpected failure: read the message, and report it with the version. |
34
40
 
35
41
  ## What each limitation asks for
36
42
 
@@ -39,6 +45,10 @@ The error document carries a `code` and a `hint`.
39
45
  | `SOURCE_RUNTIME_UNVERIFIED` | Test the interactions before delivering. |
40
46
  | `SOURCE_RUNTIME_OMITTED` | The behavior of the section is not reproduced. |
41
47
  | `RESOURCE_UNAVAILABLE` | A resource was not downloaded: check it in the output. |
48
+ | `INVALID_RESOURCE_URL` | A resource address could not be resolved: check it in the output. |
49
+ | `STYLESHEET_UNAVAILABLE` | A stylesheet could not be read: the section may be missing styles. |
50
+ | `SOURCE_REQUEST_FAILED` | A request of the source failed: check whether the section depends on it. |
51
+ | `SOURCE_SCRIPT_ERROR` | The source raised a JavaScript error: the section may be incomplete. |
42
52
  | `SRCSET_INVALID` | A descriptor list was not parsed: check which image the browser picks. |
43
53
  | `SCROLL_LIMIT` | The lazy loading was cut short: raise `--max-scroll-steps`. |
44
54
  | `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.3` 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`.
93
+ Os mesmos subcomandos podem ser executados com `npx uiport@0.1.5` 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