uiport 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +41 -0
- package/README.md +10 -7
- package/README.pt-BR.md +10 -7
- package/SECURITY.md +1 -1
- package/bin/cli.mjs +34 -8
- package/docs/architecture.md +1 -1
- package/docs/support.md +17 -3
- package/package.json +1 -1
- package/scripts/capture.mjs +171 -36
- package/scripts/contract.mjs +14 -0
- package/scripts/css-context.mjs +18 -10
- package/scripts/diff.mjs +149 -0
- package/scripts/dom.mjs +59 -94
- package/scripts/errors.mjs +53 -0
- package/scripts/examples.mjs +37 -0
- package/scripts/inspect.mjs +50 -0
- package/scripts/lib.mjs +20 -19
- package/scripts/options.mjs +52 -12
- package/scripts/report.mjs +119 -0
- package/scripts/resources.mjs +130 -70
- package/scripts/srcset.mjs +14 -0
- package/scripts/stdout.mjs +13 -0
- package/scripts/validate.mjs +73 -41
- package/skills/uiport/SKILL.md +39 -8
- package/uiport.md +13 -4
package/scripts/options.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// @ts-check
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import { UiportError } from "./errors.mjs";
|
|
3
4
|
|
|
4
5
|
export const common = ["json", "help", "version"];
|
|
5
6
|
export const browserOptions = [
|
|
@@ -20,6 +21,7 @@ export const allowed = {
|
|
|
20
21
|
"max-total-mb",
|
|
21
22
|
"omit-scripts",
|
|
22
23
|
"max-scroll-steps",
|
|
24
|
+
"dry-run",
|
|
23
25
|
],
|
|
24
26
|
validate: [
|
|
25
27
|
...common,
|
|
@@ -30,6 +32,18 @@ export const allowed = {
|
|
|
30
32
|
"max-scroll-steps",
|
|
31
33
|
],
|
|
32
34
|
serve: [...common, "dir", "port"],
|
|
35
|
+
inspect: [...common, "dir"],
|
|
36
|
+
examples: [...common, "port"],
|
|
37
|
+
diff: [
|
|
38
|
+
...common,
|
|
39
|
+
"before",
|
|
40
|
+
"after",
|
|
41
|
+
"viewports",
|
|
42
|
+
"wait",
|
|
43
|
+
"timeout",
|
|
44
|
+
"locale",
|
|
45
|
+
"color-scheme",
|
|
46
|
+
],
|
|
33
47
|
browser: common,
|
|
34
48
|
};
|
|
35
49
|
const booleans = new Set([
|
|
@@ -38,6 +52,7 @@ const booleans = new Set([
|
|
|
38
52
|
"version",
|
|
39
53
|
"allow-external",
|
|
40
54
|
"omit-scripts",
|
|
55
|
+
"dry-run",
|
|
41
56
|
]);
|
|
42
57
|
|
|
43
58
|
/** @param {string[]} argv @param {string[]} keys */
|
|
@@ -47,18 +62,23 @@ export function parseArgs(argv, keys) {
|
|
|
47
62
|
for (let i = 0; i < argv.length; i++) {
|
|
48
63
|
const token = argv[i];
|
|
49
64
|
if (!token.startsWith("--"))
|
|
50
|
-
throw new
|
|
65
|
+
throw new UiportError("USAGE_INVALID", `Unexpected argument: ${token}`);
|
|
51
66
|
const [key, ...parts] = token.slice(2).split("=");
|
|
52
|
-
if (!keys.includes(key))
|
|
67
|
+
if (!keys.includes(key))
|
|
68
|
+
throw new UiportError("USAGE_INVALID", `Unknown option: --${key}`);
|
|
53
69
|
if (Object.hasOwn(result, key))
|
|
54
|
-
throw new
|
|
70
|
+
throw new UiportError("USAGE_INVALID", `Repeated option: --${key}`);
|
|
55
71
|
if (booleans.has(key)) {
|
|
56
|
-
if (parts.length)
|
|
72
|
+
if (parts.length)
|
|
73
|
+
throw new UiportError(
|
|
74
|
+
"USAGE_INVALID",
|
|
75
|
+
`--${key} does not accept a value`,
|
|
76
|
+
);
|
|
57
77
|
result[key] = true;
|
|
58
78
|
} else {
|
|
59
79
|
const value = parts.length ? parts.join("=") : argv[++i];
|
|
60
80
|
if (!value || value.startsWith("--"))
|
|
61
|
-
throw new
|
|
81
|
+
throw new UiportError("USAGE_INVALID", `Missing value for --${key}`);
|
|
62
82
|
result[key] = value;
|
|
63
83
|
}
|
|
64
84
|
}
|
|
@@ -69,7 +89,7 @@ export function parseArgs(argv, keys) {
|
|
|
69
89
|
export function required(args, key) {
|
|
70
90
|
const value = args[key];
|
|
71
91
|
if (typeof value !== "string" || !value.trim())
|
|
72
|
-
throw new
|
|
92
|
+
throw new UiportError("USAGE_INVALID", `Missing required --${key}`);
|
|
73
93
|
return value.trim();
|
|
74
94
|
}
|
|
75
95
|
|
|
@@ -77,7 +97,8 @@ export function required(args, key) {
|
|
|
77
97
|
export function numeric(value, key, fallback, min, max) {
|
|
78
98
|
const n = value === undefined ? fallback : Number(value);
|
|
79
99
|
if (typeof value === "boolean" || !Number.isFinite(n) || n < min || n > max) {
|
|
80
|
-
throw new
|
|
100
|
+
throw new UiportError(
|
|
101
|
+
"USAGE_INVALID",
|
|
81
102
|
`--${key} must be a finite number between ${min} and ${max}`,
|
|
82
103
|
);
|
|
83
104
|
}
|
|
@@ -92,16 +113,22 @@ export function parseViewports(value = "1440x900,1024x768,768x1024,375x812") {
|
|
|
92
113
|
.map((item) => {
|
|
93
114
|
const match = /^(\d{2,4})x(\d{2,4})$/i.exec(item.trim());
|
|
94
115
|
if (!match)
|
|
95
|
-
throw new
|
|
116
|
+
throw new UiportError(
|
|
117
|
+
"USAGE_INVALID",
|
|
118
|
+
`Invalid viewport '${item}'. Use WIDTHxHEIGHT.`,
|
|
119
|
+
);
|
|
96
120
|
const width = Number(match[1]),
|
|
97
121
|
height = Number(match[2]);
|
|
98
122
|
if (width < 200 || height < 200 || width > 3840 || height > 3840)
|
|
99
|
-
throw new
|
|
123
|
+
throw new UiportError(
|
|
124
|
+
"USAGE_INVALID",
|
|
125
|
+
"Viewport dimensions must be between 200 and 3840",
|
|
126
|
+
);
|
|
100
127
|
return { width, height, name: `${width}x${height}` };
|
|
101
128
|
})
|
|
102
129
|
.filter((v) => !seen.has(v.name) && seen.add(v.name));
|
|
103
130
|
if (!items.length || items.length > 8)
|
|
104
|
-
throw new
|
|
131
|
+
throw new UiportError("USAGE_INVALID", "Use between 1 and 8 viewports");
|
|
105
132
|
return items;
|
|
106
133
|
}
|
|
107
134
|
|
|
@@ -113,7 +140,10 @@ export function httpUrl(value) {
|
|
|
113
140
|
url.username ||
|
|
114
141
|
url.password
|
|
115
142
|
)
|
|
116
|
-
throw new
|
|
143
|
+
throw new UiportError(
|
|
144
|
+
"USAGE_INVALID",
|
|
145
|
+
"--url must be HTTP(S) without embedded credentials",
|
|
146
|
+
);
|
|
117
147
|
return url.href;
|
|
118
148
|
}
|
|
119
149
|
|
|
@@ -122,6 +152,7 @@ export function optionsFor(command, args) {
|
|
|
122
152
|
const options = {
|
|
123
153
|
json: args.json === true,
|
|
124
154
|
omitScripts: args["omit-scripts"] === true,
|
|
155
|
+
dryRun: args["dry-run"] === true,
|
|
125
156
|
sourceUrl: "",
|
|
126
157
|
selector: "",
|
|
127
158
|
directory: "",
|
|
@@ -170,7 +201,16 @@ export function optionsFor(command, args) {
|
|
|
170
201
|
options.sourceUrl = httpUrl(required(args, "url"));
|
|
171
202
|
options.selector = required(args, "selector");
|
|
172
203
|
}
|
|
173
|
-
if (
|
|
204
|
+
if (command === "diff") {
|
|
205
|
+
options.before = path.resolve(required(args, "before"));
|
|
206
|
+
options.after = path.resolve(required(args, "after"));
|
|
207
|
+
}
|
|
208
|
+
if (command === "capture" && options.dryRun)
|
|
209
|
+
// A dry run writes nothing, so it needs no destination.
|
|
210
|
+
options.directory = path.resolve(
|
|
211
|
+
typeof args.out === "string" ? args.out : ".uiport-dry-run",
|
|
212
|
+
);
|
|
213
|
+
else if (["capture", "validate", "serve", "inspect"].includes(command))
|
|
174
214
|
options.directory = path.resolve(
|
|
175
215
|
required(args, command === "capture" ? "out" : "dir"),
|
|
176
216
|
);
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// The human reading of a result. The machine reading stays the JSON document;
|
|
2
|
+
// this is what a person sees when they did not ask for JSON.
|
|
3
|
+
const LIMITATION_ACTION = {
|
|
4
|
+
SOURCE_RUNTIME_UNVERIFIED:
|
|
5
|
+
"the source scripts are preserved; test the interactions before delivering",
|
|
6
|
+
SOURCE_RUNTIME_OMITTED:
|
|
7
|
+
"the source scripts were omitted; the behavior of the section is not reproduced",
|
|
8
|
+
RESOURCE_UNAVAILABLE:
|
|
9
|
+
"a resource could not be downloaded; check it in the output",
|
|
10
|
+
INVALID_RESOURCE_URL:
|
|
11
|
+
"a resource address could not be resolved; check it in the output",
|
|
12
|
+
STYLESHEET_UNAVAILABLE:
|
|
13
|
+
"a stylesheet could not be read; the section may be missing styles",
|
|
14
|
+
SRCSET_INVALID:
|
|
15
|
+
"a srcset descriptor list could not be parsed; check which image is used",
|
|
16
|
+
SCROLL_LIMIT: "the lazy loading was cut short; raise --max-scroll-steps",
|
|
17
|
+
RESPONSIVE_DOM_CHANGED:
|
|
18
|
+
"the structure changes across viewports; the first viewport was exported",
|
|
19
|
+
SECTION_NOT_VISIBLE: "the selected root is hidden; choose a visible element",
|
|
20
|
+
SECTION_EMPTY_AREA:
|
|
21
|
+
"the selected root has no size; choose an element that renders",
|
|
22
|
+
CANVAS_STATIC: "a canvas was exported as a still image",
|
|
23
|
+
CANVAS_UNREADABLE: "a canvas could not be read",
|
|
24
|
+
EMBED_OMITTED: "an embedded document was disabled",
|
|
25
|
+
ANIMATION_UNSUPPORTED: "an animation could not be replayed",
|
|
26
|
+
SOURCE_REQUEST_FAILED: "a request of the source failed",
|
|
27
|
+
SOURCE_SCRIPT_ERROR: "the source raised a JavaScript error",
|
|
28
|
+
CSS_IMPORT_CYCLE: "a circular stylesheet import was omitted",
|
|
29
|
+
CSS_IMPORT_UNSUPPORTED: "a stylesheet import could not be read",
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const bytes = (value) => {
|
|
33
|
+
if (!Number.isFinite(value)) return "";
|
|
34
|
+
if (value < 1024) return `${value} B`;
|
|
35
|
+
if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KiB`;
|
|
36
|
+
return `${(value / (1024 * 1024)).toFixed(1)} MiB`;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const limitations = (list = []) =>
|
|
40
|
+
list.map(
|
|
41
|
+
(entry) =>
|
|
42
|
+
` ! ${entry.code} — ${LIMITATION_ACTION[entry.code] || entry.message}`,
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
/** @param {any} result */
|
|
46
|
+
export function report(result) {
|
|
47
|
+
if (!result) return "";
|
|
48
|
+
const lines = [];
|
|
49
|
+
if (result.command === "capture" && result.dryRun) {
|
|
50
|
+
lines.push(`UIport: ${result.selector} matches one element`);
|
|
51
|
+
lines.push(
|
|
52
|
+
result.visible
|
|
53
|
+
? " the element renders; run the capture without --dry-run"
|
|
54
|
+
: " the element does not render; it would be reported as partial",
|
|
55
|
+
);
|
|
56
|
+
} else if (result.command === "capture") {
|
|
57
|
+
const partial = result.status === "partial";
|
|
58
|
+
lines.push(
|
|
59
|
+
`UIport: captured ${result.outputDirectory}${partial ? " (partial)" : ""}`,
|
|
60
|
+
);
|
|
61
|
+
lines.push(
|
|
62
|
+
` ${result.elements} elements · ${result.assets} asset${result.assets === 1 ? "" : "s"}${result.downloadedBytes ? ` (${bytes(result.downloadedBytes)})` : ""}`,
|
|
63
|
+
);
|
|
64
|
+
lines.push(...limitations(result.limitations));
|
|
65
|
+
if (!partial)
|
|
66
|
+
lines.push(" next: uiport serve --dir <directory> to inspect it");
|
|
67
|
+
} else if (result.command === "validate") {
|
|
68
|
+
const failed = result.results.filter((entry) => !entry.pass);
|
|
69
|
+
lines.push(
|
|
70
|
+
failed.length
|
|
71
|
+
? `UIport: validation failed in ${failed.length} of ${result.results.length} viewports`
|
|
72
|
+
: `UIport: validation passed in ${result.results.length} viewports`,
|
|
73
|
+
);
|
|
74
|
+
for (const entry of failed) {
|
|
75
|
+
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
|
+
);
|
|
79
|
+
for (const error of entry.errors || []) lines.push(` ${error}`);
|
|
80
|
+
for (const url of entry.network?.failedRequests || [])
|
|
81
|
+
lines.push(` failed request: ${url}`);
|
|
82
|
+
}
|
|
83
|
+
lines.push(...limitations(result.limitations));
|
|
84
|
+
lines.push(" behavior: not tested; inspect the interactions yourself");
|
|
85
|
+
} else if (result.command === "diff") {
|
|
86
|
+
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)
|
|
93
|
+
lines.push(
|
|
94
|
+
` ! ${entry.viewport} — ${(entry.differenceRatio * 100).toFixed(1)}% of the pixels differ`,
|
|
95
|
+
);
|
|
96
|
+
for (const code of result.limitations.added)
|
|
97
|
+
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`,
|
|
103
|
+
);
|
|
104
|
+
} else if (result.command === "inspect") {
|
|
105
|
+
lines.push(`UIport: ${result.outputDirectory}`);
|
|
106
|
+
lines.push(
|
|
107
|
+
` ${result.elements ?? "?"} elements · ${result.assets ?? 0} asset${result.assets === 1 ? "" : "s"}`,
|
|
108
|
+
);
|
|
109
|
+
lines.push(...limitations(result.limitations));
|
|
110
|
+
} else if (result.command === "browser") {
|
|
111
|
+
lines.push("UIport: Chromium installation complete. Ready to capture.");
|
|
112
|
+
}
|
|
113
|
+
return lines.join("\n");
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** @param {{code:string,message:string,hint:string}} error */
|
|
117
|
+
export function reportError(error) {
|
|
118
|
+
return [`UIport: ${error.message}`, ` ${error.hint}`].join("\n");
|
|
119
|
+
}
|
package/scripts/resources.mjs
CHANGED
|
@@ -20,81 +20,119 @@ export function resources(
|
|
|
20
20
|
limitations,
|
|
21
21
|
browserCache,
|
|
22
22
|
) {
|
|
23
|
+
// A pending download is stored as its promise so that concurrent requests
|
|
24
|
+
// for the same URL share one transfer.
|
|
23
25
|
const downloaded = new Map();
|
|
26
|
+
const localized = new Map();
|
|
27
|
+
const written = new Map();
|
|
24
28
|
let consumed = 0;
|
|
25
29
|
const localPaths = new Set();
|
|
30
|
+
const maxConcurrentDownloads = 8;
|
|
31
|
+
let activeDownloads = 0;
|
|
32
|
+
const waitingDownloads = [];
|
|
33
|
+
// Bytes read from the network, and bytes charged against the total budget.
|
|
34
|
+
// The charge happens before the bytes are retained, so concurrent transfers
|
|
35
|
+
// cannot pass the limit together; the reported download size stays the
|
|
36
|
+
// amount actually received.
|
|
37
|
+
let received = 0;
|
|
38
|
+
function consume(bytes) {
|
|
39
|
+
received += bytes;
|
|
40
|
+
if (consumed + bytes > options.maxTotalBytes)
|
|
41
|
+
throw new Error("Resource size limit exceeded");
|
|
42
|
+
consumed += bytes;
|
|
43
|
+
}
|
|
44
|
+
async function acquireDownloadSlot() {
|
|
45
|
+
if (activeDownloads < maxConcurrentDownloads) {
|
|
46
|
+
activeDownloads++;
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
await new Promise((resolve) => waitingDownloads.push(resolve));
|
|
50
|
+
}
|
|
51
|
+
function releaseDownloadSlot() {
|
|
52
|
+
const next = waitingDownloads.shift();
|
|
53
|
+
if (next) next();
|
|
54
|
+
else activeDownloads--;
|
|
55
|
+
}
|
|
26
56
|
/** @param {string} input */
|
|
27
57
|
async function download(input) {
|
|
28
58
|
const url = normalizeUrl(input);
|
|
29
59
|
if (downloaded.has(url)) return downloaded.get(url);
|
|
30
60
|
if (!/^https?:/i.test(url)) return null;
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
if (
|
|
38
|
-
cached.body.length > options.maxResourceBytes
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
61
|
+
const pending = (async () => {
|
|
62
|
+
let response;
|
|
63
|
+
try {
|
|
64
|
+
if (consumed >= options.maxTotalBytes)
|
|
65
|
+
throw new Error("Total resource budget exceeded");
|
|
66
|
+
const cached = await browserCache?.get(url);
|
|
67
|
+
if (cached) {
|
|
68
|
+
if (cached.body.length > options.maxResourceBytes)
|
|
69
|
+
throw new Error("Resource size limit exceeded");
|
|
70
|
+
consume(cached.body.length);
|
|
71
|
+
return cached;
|
|
72
|
+
}
|
|
73
|
+
await acquireDownloadSlot();
|
|
74
|
+
try {
|
|
75
|
+
response = await fetch(url, {
|
|
76
|
+
signal: AbortSignal.any([
|
|
77
|
+
signal,
|
|
78
|
+
AbortSignal.timeout(Math.min(options.timeoutMs, 15000)),
|
|
79
|
+
]),
|
|
80
|
+
headers: { "user-agent": "UIport/0.1" },
|
|
81
|
+
});
|
|
82
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
83
|
+
const length = Number(response.headers.get("content-length") || 0);
|
|
84
|
+
if (
|
|
85
|
+
length > options.maxResourceBytes ||
|
|
86
|
+
length + consumed > options.maxTotalBytes
|
|
87
|
+
)
|
|
88
|
+
throw new Error("Resource size limit exceeded");
|
|
89
|
+
const chunks = [];
|
|
90
|
+
let size = 0;
|
|
91
|
+
for await (const chunk of /** @type {any} */ (response.body)) {
|
|
92
|
+
size += chunk.length;
|
|
93
|
+
consume(chunk.length);
|
|
94
|
+
if (size > options.maxResourceBytes)
|
|
95
|
+
throw new Error("Resource size limit exceeded");
|
|
96
|
+
chunks.push(chunk);
|
|
97
|
+
}
|
|
98
|
+
const resource = {
|
|
99
|
+
body: Buffer.concat(chunks),
|
|
100
|
+
contentType: response.headers.get("content-type") || "",
|
|
101
|
+
url: response.url || url,
|
|
102
|
+
};
|
|
103
|
+
return resource;
|
|
104
|
+
} finally {
|
|
105
|
+
releaseDownloadSlot();
|
|
106
|
+
}
|
|
107
|
+
} catch (error) {
|
|
108
|
+
signal.throwIfAborted();
|
|
109
|
+
limitation(
|
|
110
|
+
limitations,
|
|
111
|
+
"RESOURCE_UNAVAILABLE",
|
|
112
|
+
`${redactedUrl(url)}: ${safeErrorMessage(error)}`,
|
|
113
|
+
);
|
|
114
|
+
return null;
|
|
115
|
+
} finally {
|
|
116
|
+
if (response?.body && !response.body.locked)
|
|
117
|
+
await response.body.cancel().catch(() => {});
|
|
68
118
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
url: response.url || url,
|
|
73
|
-
};
|
|
74
|
-
downloaded.set(url, resource);
|
|
75
|
-
return resource;
|
|
76
|
-
} catch (error) {
|
|
77
|
-
signal.throwIfAborted();
|
|
78
|
-
limitation(
|
|
79
|
-
limitations,
|
|
80
|
-
"RESOURCE_UNAVAILABLE",
|
|
81
|
-
`${redactedUrl(url)}: ${safeErrorMessage(error)}`,
|
|
82
|
-
);
|
|
83
|
-
downloaded.set(url, null);
|
|
84
|
-
return null;
|
|
85
|
-
} finally {
|
|
86
|
-
if (response?.body && !response.body.locked)
|
|
87
|
-
await response.body.cancel().catch(() => {});
|
|
88
|
-
}
|
|
119
|
+
})();
|
|
120
|
+
downloaded.set(url, pending);
|
|
121
|
+
return pending;
|
|
89
122
|
}
|
|
90
123
|
/** @param {string} raw @param {string} base @param {string} [usage] */
|
|
91
124
|
async function localize(raw, base, usage) {
|
|
92
|
-
if (
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
)
|
|
97
|
-
|
|
125
|
+
if (!raw || /^(data:|#)/i.test(raw)) return raw;
|
|
126
|
+
// The usage decides the file extension, so it belongs to the key.
|
|
127
|
+
const key = `${base}|${raw}|${usage || ""}`;
|
|
128
|
+
if (localized.has(key)) return localized.get(key);
|
|
129
|
+
const pending = localizeResource(raw, base, usage);
|
|
130
|
+
localized.set(key, pending);
|
|
131
|
+
return pending;
|
|
132
|
+
}
|
|
133
|
+
/** @param {string} raw @param {string} base @param {string} [usage] */
|
|
134
|
+
async function localizeResource(raw, base, usage) {
|
|
135
|
+
if (localPaths.has(raw.split("#")[0].replace(/^\.\//, ""))) return raw;
|
|
98
136
|
let url;
|
|
99
137
|
try {
|
|
100
138
|
url = new URL(raw, base);
|
|
@@ -123,14 +161,22 @@ export function resources(
|
|
|
123
161
|
)
|
|
124
162
|
extension = ".js";
|
|
125
163
|
const file = `assets/${sha256(resource.body).slice(0, 24)}${extension}`;
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
164
|
+
// Two different URLs can carry the same bytes and therefore the same file
|
|
165
|
+
// name. One shared write keeps the file intact, and every caller waits
|
|
166
|
+
// for that write before the export is assembled.
|
|
167
|
+
if (!written.has(file))
|
|
168
|
+
written.set(
|
|
169
|
+
file,
|
|
170
|
+
fs.writeFile(path.join(directory, file), resource.body),
|
|
171
|
+
);
|
|
172
|
+
await written.get(file);
|
|
173
|
+
localPaths.add(file);
|
|
130
174
|
return `./${file}${url.hash}`;
|
|
131
175
|
}
|
|
132
176
|
/** @param {string} value @param {string} base */
|
|
133
177
|
async function cssValue(value, base) {
|
|
178
|
+
// Most declarations carry no URL at all: parsing them is wasted work.
|
|
179
|
+
if (!/url\(|image-set\(/i.test(value)) return value;
|
|
134
180
|
const parsed = valueParser(value);
|
|
135
181
|
const nodes = [];
|
|
136
182
|
parsed.walk((node) => {
|
|
@@ -245,8 +291,18 @@ export function resources(
|
|
|
245
291
|
rule.replaceWith(postcss.parse(body).nodes);
|
|
246
292
|
}
|
|
247
293
|
// Imported declarations have already been rewritten against their own base.
|
|
248
|
-
|
|
249
|
-
|
|
294
|
+
// Each declaration is independent, so the resources they reference are
|
|
295
|
+
// localized concurrently. A cancellation must not leave sibling
|
|
296
|
+
// rejections unhandled.
|
|
297
|
+
const rewritten = await Promise.allSettled(
|
|
298
|
+
declarations.map((decl) =>
|
|
299
|
+
cssValue(decl.value, base).then((value) => {
|
|
300
|
+
decl.value = value;
|
|
301
|
+
}),
|
|
302
|
+
),
|
|
303
|
+
);
|
|
304
|
+
const failure = rewritten.find((entry) => entry.status === "rejected");
|
|
305
|
+
if (failure) throw failure.reason;
|
|
250
306
|
root.walkComments((comment) => {
|
|
251
307
|
if (/sourceMappingURL/.test(comment.text)) comment.remove();
|
|
252
308
|
});
|
|
@@ -260,6 +316,10 @@ export function resources(
|
|
|
260
316
|
localize,
|
|
261
317
|
css,
|
|
262
318
|
cssValue,
|
|
263
|
-
stats: () => ({
|
|
319
|
+
stats: () => ({
|
|
320
|
+
assets: localPaths.size,
|
|
321
|
+
downloadedBytes: received,
|
|
322
|
+
budgetBytes: consumed,
|
|
323
|
+
}),
|
|
264
324
|
};
|
|
265
325
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import parseSrcset from "parse-srcset";
|
|
2
|
+
|
|
3
|
+
// parse-srcset reports invalid descriptors through console.log. That would
|
|
4
|
+
// print source page content and break the one-document stdout contract, so
|
|
5
|
+
// the diagnostic is suppressed here and reported by the caller instead.
|
|
6
|
+
export function parseSrcsetAttribute(value) {
|
|
7
|
+
const log = console.log;
|
|
8
|
+
console.log = () => {};
|
|
9
|
+
try {
|
|
10
|
+
return parseSrcset(value);
|
|
11
|
+
} finally {
|
|
12
|
+
console.log = log;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Route whatever is written to stdout to another stream while the returned
|
|
2
|
+
// function has not been called. A capture or a validation writes exactly one
|
|
3
|
+
// JSON document to stdout, and the document itself is written after the
|
|
4
|
+
// restore. This is the safety net for the output contract; the diagnostics of
|
|
5
|
+
// the source are suppressed where they are produced.
|
|
6
|
+
export function guardStdout(target = process.stderr) {
|
|
7
|
+
const original = process.stdout.write;
|
|
8
|
+
process.stdout.write = (chunk, encoding, callback) =>
|
|
9
|
+
target.write(chunk, encoding, callback);
|
|
10
|
+
return () => {
|
|
11
|
+
process.stdout.write = original;
|
|
12
|
+
};
|
|
13
|
+
}
|