@mark1russell7/site-pages 0.4.1 → 0.4.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/README.md +63 -0
- package/build/chunks/freshness.js +1 -1
- package/build/chunks/freshness.js.map +1 -1
- package/build/cli.js +886 -8
- package/build/cli.js.map +1 -1
- package/package.json +1 -1
package/build/cli.js
CHANGED
|
@@ -1,12 +1,373 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { p as runFreshnessCli } from "./chunks/freshness.js";
|
|
2
|
+
import { m as escapeHtml, p as runFreshnessCli, y as safeUrl } from "./chunks/freshness.js";
|
|
3
3
|
import { a as runCli, o as TYPESCRIPT_PROBE, s as probeScript } from "./chunks/build.js";
|
|
4
4
|
import { spawn } from "node:child_process";
|
|
5
5
|
import { appendFileSync, createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
6
|
-
import { delimiter, extname, isAbsolute, join, normalize, resolve, sep } from "node:path";
|
|
6
|
+
import { delimiter, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
|
|
7
7
|
import { parseArgs } from "node:util";
|
|
8
8
|
import { homedir, tmpdir } from "node:os";
|
|
9
9
|
import { createServer } from "node:http";
|
|
10
|
+
// src/bar/bar.ts
|
|
11
|
+
/**
|
|
12
|
+
* The shared site bar (`site-pages bar`). The Pages workflow writes one bar into each built HTML page of a site.
|
|
13
|
+
* Thus each page of each site has the same way to each other page, and no site writes its own bar.
|
|
14
|
+
*
|
|
15
|
+
* The bar has the portfolio of the owner and the name of the site. It also has a link to each page of the site, to
|
|
16
|
+
* GitHub and to npm. The link of the current page has `aria-current="page"`. The bar works at 360 px: its rows wrap.
|
|
17
|
+
* Its CSS has its own class names and variables, so the CSS of a site does not change it.
|
|
18
|
+
*/
|
|
19
|
+
/** The marker attribute of the bar. The navigation crawl looks for it. */
|
|
20
|
+
const BAR_ATTRIBUTE = "data-site-bar";
|
|
21
|
+
/** The CSS of the bar. Each rule starts with `.spb`, so it changes only the bar. */
|
|
22
|
+
const BAR_CSS = `
|
|
23
|
+
.spb{--spb-bg:#ffffff;--spb-fg:#151c2e;--spb-muted:#5f6880;--spb-rule:#d6dbe5;--spb-accent:#2346c4;--spb-wash:#e7ecfd;
|
|
24
|
+
color-scheme:light;position:relative;z-index:2147483000;display:block;margin:0;padding:0;background:var(--spb-bg);color:var(--spb-fg);
|
|
25
|
+
border-bottom:1px solid var(--spb-rule);font:400 14px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
|
|
26
|
+
text-align:left;letter-spacing:normal;text-transform:none}
|
|
27
|
+
@media (prefers-color-scheme:dark){.spb{--spb-bg:#151a2b;--spb-fg:#e6e9f3;--spb-muted:#a3abc2;--spb-rule:#2b3350;--spb-accent:#93abff;--spb-wash:#1f2a4f;color-scheme:dark}}
|
|
28
|
+
:root[data-theme="dark"] .spb,:root.dark .spb{--spb-bg:#151a2b;--spb-fg:#e6e9f3;--spb-muted:#a3abc2;--spb-rule:#2b3350;--spb-accent:#93abff;--spb-wash:#1f2a4f;color-scheme:dark}
|
|
29
|
+
:root[data-theme="light"] .spb,:root.light .spb{--spb-bg:#ffffff;--spb-fg:#151c2e;--spb-muted:#5f6880;--spb-rule:#d6dbe5;--spb-accent:#2346c4;--spb-wash:#e7ecfd;color-scheme:light}
|
|
30
|
+
.spb *{box-sizing:border-box;margin:0;padding:0;font:inherit;letter-spacing:inherit}
|
|
31
|
+
.spb-in{max-width:80rem;margin:0 auto;padding:6px 12px;display:flex;flex-wrap:wrap;align-items:center;gap:4px 16px}
|
|
32
|
+
.spb-id{display:flex;align-items:center;gap:6px;min-width:0;margin-right:auto}
|
|
33
|
+
.spb-id a{color:var(--spb-fg);text-decoration:none;border-radius:4px;overflow-wrap:anywhere}
|
|
34
|
+
.spb-owner{color:var(--spb-muted)!important}
|
|
35
|
+
.spb-site{font-weight:700}
|
|
36
|
+
.spb-id a:hover,.spb-links a:hover{text-decoration:underline;text-underline-offset:3px}
|
|
37
|
+
.spb-sep{color:var(--spb-muted)}
|
|
38
|
+
.spb-links{display:flex;flex-wrap:wrap;align-items:center;gap:2px;list-style:none}
|
|
39
|
+
.spb-links a{display:inline-block;padding:4px 8px;min-height:32px;line-height:24px;border-radius:6px;color:var(--spb-accent);text-decoration:none;white-space:nowrap}
|
|
40
|
+
.spb-links a[aria-current="page"]{background:var(--spb-wash);color:var(--spb-fg);font-weight:600}
|
|
41
|
+
.spb-out{color:var(--spb-muted)!important}
|
|
42
|
+
.spb a:focus-visible{outline:2px solid var(--spb-accent);outline-offset:1px}
|
|
43
|
+
@media print{.spb{display:none}}
|
|
44
|
+
`;
|
|
45
|
+
/** This function gives the path of a page from the site home, with no `index.html`. The home is an empty text. */
|
|
46
|
+
function pagePath(file) {
|
|
47
|
+
return file.split(sep).join("/").replace(/(^|\/)index\.html$/, "$1");
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* This function gives the link of the bar that is the current page: the link with the longest path that starts the
|
|
51
|
+
* page path. The home link is current only on the home page.
|
|
52
|
+
*/
|
|
53
|
+
function currentLink(links, path) {
|
|
54
|
+
let best;
|
|
55
|
+
for (const entry of links) if ((entry.path === "" ? path === "" : path === entry.path || entry.path.endsWith("/") && path.startsWith(entry.path)) && (best === void 0 || entry.path.length > best.path.length)) best = entry;
|
|
56
|
+
return best;
|
|
57
|
+
}
|
|
58
|
+
/** This function gives the links of the bar to the pages of the site, in order: the home, the pages, Releases and Status. */
|
|
59
|
+
function barPages(options) {
|
|
60
|
+
const pages = [{
|
|
61
|
+
label: "Home",
|
|
62
|
+
path: ""
|
|
63
|
+
}, ...options.pages.filter((entry) => entry.path !== "")];
|
|
64
|
+
if (options.sitePages) pages.push({
|
|
65
|
+
label: "Releases",
|
|
66
|
+
path: "releases/"
|
|
67
|
+
}, {
|
|
68
|
+
label: "Status",
|
|
69
|
+
path: "status/"
|
|
70
|
+
});
|
|
71
|
+
const seen = /* @__PURE__ */ new Set();
|
|
72
|
+
return pages.filter((entry) => {
|
|
73
|
+
if (seen.has(entry.path)) return false;
|
|
74
|
+
seen.add(entry.path);
|
|
75
|
+
return true;
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
/** This function gives the HTML of the bar for the page at `path`. */
|
|
79
|
+
function barHtml(options, path) {
|
|
80
|
+
const [owner = "", name = ""] = options.repository.split("/");
|
|
81
|
+
const href = (page) => escapeHtml(`${options.base}${page}`);
|
|
82
|
+
const pages = barPages(options);
|
|
83
|
+
const current = currentLink(pages, path);
|
|
84
|
+
const portfolio = options.portfolio === void 0 ? void 0 : safeUrl(options.portfolio);
|
|
85
|
+
const id = [portfolio ? `<a class="spb-owner" href="${escapeHtml(portfolio)}">${escapeHtml(owner)}</a><span class="spb-sep" aria-hidden="true">/</span>` : "", `<a class="spb-site" href="${href("")}">${escapeHtml(options.siteName ?? name)}</a>`].join("");
|
|
86
|
+
const links = pages.map((entry) => {
|
|
87
|
+
const mark = entry === current ? " aria-current=\"page\"" : "";
|
|
88
|
+
return `<li><a href="${href(entry.path)}" target="_self"${mark}>${escapeHtml(entry.label)}</a></li>`;
|
|
89
|
+
});
|
|
90
|
+
links.push(`<li><a class="spb-out" href="https://github.com/${escapeHtml(options.repository)}">GitHub</a></li>`);
|
|
91
|
+
if (options.npm) links.push(`<li><a class="spb-out" href="https://www.npmjs.com/package/${escapeHtml(options.npm)}">npm</a></li>`);
|
|
92
|
+
return `<nav class="spb" ${BAR_ATTRIBUTE} aria-label="Site"><div class="spb-in"><div class="spb-id">${id}</div><ul class="spb-links">${links.join("")}</ul></div></nav>`;
|
|
93
|
+
}
|
|
94
|
+
const BAR_PATTERN = /\n?<nav class="spb" data-site-bar[\s\S]*?<\/ul><\/div><\/nav>/;
|
|
95
|
+
const STYLE_ID$1 = "site-bar-css";
|
|
96
|
+
const STYLE_PATTERN$1 = /<style id="site-bar-css">[\s\S]*?<\/style>/;
|
|
97
|
+
const SP_HEADER_PATTERN = /<header class="sp-header">[\s\S]*?<\/header>\n?/;
|
|
98
|
+
/**
|
|
99
|
+
* This function writes the bar into the HTML of one page. The bar comes first in `<body>`, and its CSS comes last in
|
|
100
|
+
* `<head>`. A bar from an earlier start goes away, so the function can start two times on one page. The header of a
|
|
101
|
+
* page of site-pages also goes away. The function gives the HTML with no change when the page has no `<body>`.
|
|
102
|
+
*/
|
|
103
|
+
function injectBar(html, bar) {
|
|
104
|
+
if (/<body\b[^>]*>/i.exec(html) === null) return html;
|
|
105
|
+
let out = html.replace(STYLE_PATTERN$1, "").replace(BAR_PATTERN, "").replace(SP_HEADER_PATTERN, "");
|
|
106
|
+
const style = `<style id="${STYLE_ID$1}">${BAR_CSS}</style>`;
|
|
107
|
+
out = /<\/head>/i.test(out) ? out.replace(/<\/head>/i, `${style}</head>`) : out.replace(/<body\b[^>]*>/i, (tag) => `${style}${tag}`);
|
|
108
|
+
return out.replace(/<body\b[^>]*>/i, (tag) => `${tag}\n${bar}`);
|
|
109
|
+
}
|
|
110
|
+
/** This function gives the HTML files of a folder, as paths from the folder, in a stable order. */
|
|
111
|
+
function htmlFiles(root) {
|
|
112
|
+
const files = [];
|
|
113
|
+
const walk = (folder) => {
|
|
114
|
+
for (const entry of readdirSync(folder, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
115
|
+
const full = join(folder, entry.name);
|
|
116
|
+
if (entry.isDirectory()) walk(full);
|
|
117
|
+
else if (entry.isFile() && entry.name.endsWith(".html")) files.push(relative(root, full));
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
walk(root);
|
|
121
|
+
return files;
|
|
122
|
+
}
|
|
123
|
+
/** This function writes the bar into each HTML page of the built site folder, and gives the number of pages. */
|
|
124
|
+
function applyBar(out, options) {
|
|
125
|
+
const files = htmlFiles(out);
|
|
126
|
+
for (const file of files) {
|
|
127
|
+
const full = join(out, file);
|
|
128
|
+
const html = readFileSync(full, "utf8");
|
|
129
|
+
const next = injectBar(html, barHtml(options, pagePath(file)));
|
|
130
|
+
if (next !== html) writeFileSync(full, next);
|
|
131
|
+
}
|
|
132
|
+
return files.length;
|
|
133
|
+
}
|
|
134
|
+
const BAR_HELP = `Usage: site-pages bar --out <dir> [options]
|
|
135
|
+
|
|
136
|
+
Writes the shared site bar into each HTML page of the built site folder. The bar comes first in the
|
|
137
|
+
body of the page. It has the portfolio of the owner, the name of the site, a link to each page of
|
|
138
|
+
the site, GitHub and npm. The bar takes the place of the header of the pages of site-pages.
|
|
139
|
+
|
|
140
|
+
Options:
|
|
141
|
+
--out <dir> The built site folder
|
|
142
|
+
--repo <owner/name> The GitHub repository (default: $GITHUB_REPOSITORY)
|
|
143
|
+
--base </name/> The path of the site home (default: "/<name>/", or "/" for <owner>.github.io)
|
|
144
|
+
--site-name <name> The name of the site in the bar (default: the name of the repository)
|
|
145
|
+
--pages <list> The pages of the site after the home, as label=path pairs separated by
|
|
146
|
+
commas, for example "Demo=demo/,Docs=docs/"
|
|
147
|
+
--site-pages Adds the links to releases/ and status/
|
|
148
|
+
--npm <name> The npm name of the package, for the npm link
|
|
149
|
+
--portfolio <url> The portfolio of the owner (default: https://<owner>.github.io/, and no
|
|
150
|
+
portfolio link on the site <owner>.github.io)
|
|
151
|
+
--help Shows this text
|
|
152
|
+
`;
|
|
153
|
+
/** This function parses the value of `--pages`. It gives an Error for a pair with no label or no path. */
|
|
154
|
+
function parsePages(text) {
|
|
155
|
+
const pages = [];
|
|
156
|
+
for (const pair of text.split(",").map((entry) => entry.trim()).filter(Boolean)) {
|
|
157
|
+
const at = pair.indexOf("=");
|
|
158
|
+
const label = at < 0 ? "" : pair.slice(0, at).trim();
|
|
159
|
+
const path = at < 0 ? "" : pair.slice(at + 1).trim().replace(/^\/+/, "");
|
|
160
|
+
if (label === "" || path === "" || path.includes(":") || path.includes("\\")) return /* @__PURE__ */ new Error(`"${pair}" is not a pair of a label and a path from the site home, for example Docs=docs/`);
|
|
161
|
+
pages.push({
|
|
162
|
+
label,
|
|
163
|
+
path
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
return pages;
|
|
167
|
+
}
|
|
168
|
+
/** This function starts the `bar` command with its arguments, without the word `bar`. */
|
|
169
|
+
function runBarCli(argv, io) {
|
|
170
|
+
let values;
|
|
171
|
+
try {
|
|
172
|
+
({values} = parseArgs({
|
|
173
|
+
args: [...argv],
|
|
174
|
+
allowPositionals: false,
|
|
175
|
+
options: {
|
|
176
|
+
out: { type: "string" },
|
|
177
|
+
repo: { type: "string" },
|
|
178
|
+
base: { type: "string" },
|
|
179
|
+
"site-name": { type: "string" },
|
|
180
|
+
pages: { type: "string" },
|
|
181
|
+
"site-pages": { type: "boolean" },
|
|
182
|
+
npm: { type: "string" },
|
|
183
|
+
portfolio: { type: "string" },
|
|
184
|
+
help: { type: "boolean" }
|
|
185
|
+
}
|
|
186
|
+
}));
|
|
187
|
+
} catch (error) {
|
|
188
|
+
io.stderr(`site-pages bar: ${error instanceof Error ? error.message : String(error)}\n\n${BAR_HELP}`);
|
|
189
|
+
return 2;
|
|
190
|
+
}
|
|
191
|
+
if (values["help"]) {
|
|
192
|
+
io.stdout(BAR_HELP);
|
|
193
|
+
return 0;
|
|
194
|
+
}
|
|
195
|
+
const usage = (message) => {
|
|
196
|
+
io.stderr(`site-pages bar: ${message}\n\n${BAR_HELP}`);
|
|
197
|
+
return 2;
|
|
198
|
+
};
|
|
199
|
+
const text = (key) => typeof values[key] === "string" && values[key] !== "" ? values[key] : void 0;
|
|
200
|
+
const out = text("out");
|
|
201
|
+
if (out === void 0) return usage("give --out");
|
|
202
|
+
const repository = text("repo") ?? io.env["GITHUB_REPOSITORY"] ?? "";
|
|
203
|
+
const [owner = "", name = ""] = repository.split("/");
|
|
204
|
+
if (owner === "" || name === "") return usage("give --repo <owner/name> or set GITHUB_REPOSITORY");
|
|
205
|
+
const ownerSite = name.toLowerCase() === `${owner.toLowerCase()}.github.io`;
|
|
206
|
+
const base = `/${(text("base") ?? (ownerSite ? "/" : `/${name}/`)).replace(/^\/+|\/+$/g, "")}/`.replace(/^\/\/$/, "/");
|
|
207
|
+
const pages = parsePages(text("pages") ?? "");
|
|
208
|
+
if (pages instanceof Error) return usage(pages.message);
|
|
209
|
+
const portfolio = text("portfolio") ?? (ownerSite ? void 0 : `https://${owner.toLowerCase()}.github.io/`);
|
|
210
|
+
const options = {
|
|
211
|
+
repository,
|
|
212
|
+
base,
|
|
213
|
+
siteName: text("site-name"),
|
|
214
|
+
pages,
|
|
215
|
+
sitePages: values["site-pages"] === true,
|
|
216
|
+
npm: text("npm"),
|
|
217
|
+
portfolio
|
|
218
|
+
};
|
|
219
|
+
const count = applyBar(isAbsolute(out) ? out : resolve(io.cwd, out), options);
|
|
220
|
+
if (count === 0) {
|
|
221
|
+
io.stderr(`site-pages bar: ${out} has no HTML page\n`);
|
|
222
|
+
return 1;
|
|
223
|
+
}
|
|
224
|
+
io.stdout(`site-pages bar: the bar is in ${count} pages, with ${barPages(options).map((entry) => entry.label).join(", ")}.\n`);
|
|
225
|
+
return 0;
|
|
226
|
+
}
|
|
227
|
+
// src/bar/cue.ts
|
|
228
|
+
/**
|
|
229
|
+
* The scroll cue of the built pages (`site-pages cue`). The Pages workflow changes each code block (`pre`) of each
|
|
230
|
+
* built HTML page. Each block gets the class `scroll-cue` and a place in the tab order. The page gets the style
|
|
231
|
+
* `scroll-cue.css`. Thus a code block that is wider than its box shows a fade at the edge with more content. This
|
|
232
|
+
* occurs also on a site that does not use the rehype plugin of site-pages. A box with no overflow has no active scroll
|
|
233
|
+
* timeline, so it shows no cue.
|
|
234
|
+
*
|
|
235
|
+
* A block with `data-overflow-ok` or with the class `scroll-cue` stays as it is. The text of `script`, `style` and
|
|
236
|
+
* `textarea` elements does not change.
|
|
237
|
+
*/
|
|
238
|
+
/** The attribute of each code block that the step changed. The script of the fallback finds the blocks with it. */
|
|
239
|
+
const CUE_ATTRIBUTE = "data-scroll-cue";
|
|
240
|
+
const STYLE_ID = "site-cue-css";
|
|
241
|
+
const SCRIPT_ID = "site-cue-js";
|
|
242
|
+
const STYLE_PATTERN = /<style id="site-cue-css">[\s\S]*?<\/style>/;
|
|
243
|
+
const SCRIPT_PATTERN = /<script id="site-cue-js">[\s\S]*?<\/script>/;
|
|
244
|
+
/** This function reads `scroll-cue.css` of the package, the one source of the style of the cue. */
|
|
245
|
+
function cueCss() {
|
|
246
|
+
return readFileSync(new URL("../../styles/scroll-cue.css", import.meta.url), "utf8");
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* The script of a browser with no scroll timelines. In such a browser, the style gives the box the background color
|
|
250
|
+
* `--scroll-cue-bg`. The script sets that variable to the color of the code block. When the block has no color, the
|
|
251
|
+
* script uses the color of its first ancestor with a color. Thus the block keeps the color of its theme. A browser with
|
|
252
|
+
* scroll timelines does not need the script.
|
|
253
|
+
*/
|
|
254
|
+
const CUE_SCRIPT = `(() => { if (!window.CSS || CSS.supports("animation-timeline: scroll()")) return; for (const box of document.querySelectorAll("pre[${CUE_ATTRIBUTE}]")) { box.classList.remove("scroll-cue"); let node = box; let color = ""; while (node) { color = getComputedStyle(node).backgroundColor; if (color !== "transparent" && !/^rgba\\(.*,\\s*0\\)\$/.test(color)) break; node = node.parentElement; } box.classList.add("scroll-cue"); if (node) box.style.setProperty("--scroll-cue-bg", color); } })();`;
|
|
255
|
+
const CLASS_PATTERN = /\sclass\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/i;
|
|
256
|
+
/**
|
|
257
|
+
* This function gives the attributes of one `pre` start tag with the cue. It gives `undefined` when the tag keeps its
|
|
258
|
+
* attributes: the tag has `data-overflow-ok`, or it already has the class `scroll-cue`.
|
|
259
|
+
*/
|
|
260
|
+
function cueAttributes(attributes) {
|
|
261
|
+
if (/\sdata-overflow-ok\b/i.test(attributes)) return void 0;
|
|
262
|
+
const match = CLASS_PATTERN.exec(attributes);
|
|
263
|
+
const classes = match === null ? "" : match[1] ?? match[2] ?? match[3] ?? "";
|
|
264
|
+
if (classes.split(/\s+/).includes("scroll-cue")) return void 0;
|
|
265
|
+
const named = `class="${`${classes.trim()} scroll-cue`.trim()}"`;
|
|
266
|
+
let next = match === null ? `${attributes} ${named}` : attributes.replace(CLASS_PATTERN, ` ${named}`);
|
|
267
|
+
if (!/\stabindex\s*=/i.test(next)) next += " tabindex=\"0\"";
|
|
268
|
+
return `${next} ${CUE_ATTRIBUTE}`;
|
|
269
|
+
}
|
|
270
|
+
/** The text of these elements is not HTML, so the step does not change it. */
|
|
271
|
+
const RAW_TEXT = /<(script|style|textarea)\b[\s\S]*?<\/\1\s*>/gi;
|
|
272
|
+
/**
|
|
273
|
+
* This function writes the cue into the HTML of one page, and gives the HTML and the number of code blocks that it
|
|
274
|
+
* changed. The style comes last in `<head>`, and the script comes last in `<body>`. A style and a script of an earlier
|
|
275
|
+
* start go away, so the function can start two times on one page. A page with no changed block gets no style.
|
|
276
|
+
*/
|
|
277
|
+
function injectCue(html, css) {
|
|
278
|
+
let boxes = 0;
|
|
279
|
+
const source = html.replace(STYLE_PATTERN, "").replace(SCRIPT_PATTERN, "");
|
|
280
|
+
const edit = (part) => part.replace(/<pre\b([^>]*)>/gi, (tag, attributes) => {
|
|
281
|
+
const next = cueAttributes(attributes);
|
|
282
|
+
if (next === void 0) return tag;
|
|
283
|
+
boxes++;
|
|
284
|
+
return `<pre${next}>`;
|
|
285
|
+
});
|
|
286
|
+
let out = "";
|
|
287
|
+
let at = 0;
|
|
288
|
+
for (const raw of source.matchAll(RAW_TEXT)) {
|
|
289
|
+
out += edit(source.slice(at, raw.index)) + raw[0];
|
|
290
|
+
at = raw.index + raw[0].length;
|
|
291
|
+
}
|
|
292
|
+
out += edit(source.slice(at));
|
|
293
|
+
if (!(boxes > 0 || source.includes(` data-scroll-cue`))) return {
|
|
294
|
+
html,
|
|
295
|
+
boxes: 0
|
|
296
|
+
};
|
|
297
|
+
const style = `<style id="${STYLE_ID}">${css}</style>`;
|
|
298
|
+
const script = `<script id="${SCRIPT_ID}">${CUE_SCRIPT}<\/script>`;
|
|
299
|
+
out = /<\/head>/i.test(out) ? out.replace(/<\/head>/i, `${style}</head>`) : `${style}${out}`;
|
|
300
|
+
out = /<\/body>/i.test(out) ? out.replace(/<\/body>(?![\s\S]*<\/body>)/i, `${script}</body>`) : `${out}${script}`;
|
|
301
|
+
return {
|
|
302
|
+
html: out,
|
|
303
|
+
boxes
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
/** This function writes the cue into each HTML page of the built site folder, and gives the number of pages and of code blocks. */
|
|
307
|
+
function applyCue(out, css) {
|
|
308
|
+
const files = htmlFiles(out);
|
|
309
|
+
let changed = 0;
|
|
310
|
+
let boxes = 0;
|
|
311
|
+
for (const file of files) {
|
|
312
|
+
const full = join(out, file);
|
|
313
|
+
const html = readFileSync(full, "utf8");
|
|
314
|
+
const next = injectCue(html, css);
|
|
315
|
+
boxes += next.boxes;
|
|
316
|
+
if (next.html !== html) {
|
|
317
|
+
writeFileSync(full, next.html);
|
|
318
|
+
changed++;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return {
|
|
322
|
+
pages: files.length,
|
|
323
|
+
changed,
|
|
324
|
+
boxes
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
const CUE_HELP = `Usage: site-pages cue --out <dir>
|
|
328
|
+
|
|
329
|
+
Gives each code block (pre) of each HTML page of the built site folder the class scroll-cue and a
|
|
330
|
+
place in the tab order, and writes the style scroll-cue.css into each changed page. A code block that
|
|
331
|
+
is wider than its box then shows a fade at the edge with more content. A block with the attribute
|
|
332
|
+
data-overflow-ok or the class scroll-cue stays as it is.
|
|
333
|
+
|
|
334
|
+
Options:
|
|
335
|
+
--out <dir> The built site folder
|
|
336
|
+
--help Shows this text
|
|
337
|
+
`;
|
|
338
|
+
/** This function starts the `cue` command with its arguments, without the word `cue`. */
|
|
339
|
+
function runCueCli(argv, io, css = cueCss) {
|
|
340
|
+
let values;
|
|
341
|
+
try {
|
|
342
|
+
({values} = parseArgs({
|
|
343
|
+
args: [...argv],
|
|
344
|
+
allowPositionals: false,
|
|
345
|
+
options: {
|
|
346
|
+
out: { type: "string" },
|
|
347
|
+
help: { type: "boolean" }
|
|
348
|
+
}
|
|
349
|
+
}));
|
|
350
|
+
} catch (error) {
|
|
351
|
+
io.stderr(`site-pages cue: ${error instanceof Error ? error.message : String(error)}\n\n${CUE_HELP}`);
|
|
352
|
+
return 2;
|
|
353
|
+
}
|
|
354
|
+
if (values["help"]) {
|
|
355
|
+
io.stdout(CUE_HELP);
|
|
356
|
+
return 0;
|
|
357
|
+
}
|
|
358
|
+
const out = typeof values["out"] === "string" && values["out"] !== "" ? values["out"] : void 0;
|
|
359
|
+
if (out === void 0) {
|
|
360
|
+
io.stderr(`site-pages cue: give --out\n\n${CUE_HELP}`);
|
|
361
|
+
return 2;
|
|
362
|
+
}
|
|
363
|
+
const result = applyCue(isAbsolute(out) ? out : resolve(io.cwd, out), css());
|
|
364
|
+
if (result.pages === 0) {
|
|
365
|
+
io.stderr(`site-pages cue: ${out} has no HTML page\n`);
|
|
366
|
+
return 1;
|
|
367
|
+
}
|
|
368
|
+
io.stdout(`site-pages cue: ${result.boxes} code blocks in ${result.changed} of ${result.pages} pages got the scroll cue.\n`);
|
|
369
|
+
return 0;
|
|
370
|
+
}
|
|
10
371
|
// src/check/browser.ts
|
|
11
372
|
/**
|
|
12
373
|
* A small client of the Chrome DevTools protocol for the `check` command. It starts a Chromium
|
|
@@ -184,6 +545,18 @@ async function connect(url) {
|
|
|
184
545
|
});
|
|
185
546
|
if (reply.exceptionDetails) throw new Error(reply.exceptionDetails.exception?.description ?? reply.exceptionDetails.text ?? "the expression failed");
|
|
186
547
|
return reply.result?.value;
|
|
548
|
+
},
|
|
549
|
+
call: async (source, ...args) => {
|
|
550
|
+
const target = await page.send("Runtime.evaluate", { expression: "globalThis" });
|
|
551
|
+
const reply = await page.send("Runtime.callFunctionOn", {
|
|
552
|
+
functionDeclaration: source,
|
|
553
|
+
objectId: target.result?.objectId,
|
|
554
|
+
arguments: args.map((value) => ({ value })),
|
|
555
|
+
awaitPromise: true,
|
|
556
|
+
returnByValue: true
|
|
557
|
+
});
|
|
558
|
+
if (reply.exceptionDetails) throw new Error(reply.exceptionDetails.exception?.description ?? reply.exceptionDetails.text ?? "the function failed");
|
|
559
|
+
return reply.result?.value;
|
|
187
560
|
}
|
|
188
561
|
};
|
|
189
562
|
return {
|
|
@@ -443,6 +816,44 @@ async function serve(root, base) {
|
|
|
443
816
|
};
|
|
444
817
|
}
|
|
445
818
|
/**
|
|
819
|
+
* This function gives a page expression that scrolls the page to its end, one screen at a time, and then back to the top.
|
|
820
|
+
* Thus each part that starts when it comes into view starts before the measure. Examples are an Astro island with
|
|
821
|
+
* `client:visible` and an image with `loading="lazy"`. Then the expression waits until no Astro island waits to start.
|
|
822
|
+
* An island that the page does not show and an island of a media query that does not match do not count.
|
|
823
|
+
* The expression gives the islands that did not start in `limitMs`.
|
|
824
|
+
*/
|
|
825
|
+
function revealExpression(limitMs) {
|
|
826
|
+
return `(async () => {
|
|
827
|
+
const end = performance.now() + ${String(limitMs)};
|
|
828
|
+
const frame = () => new Promise((done) => requestAnimationFrame(() => setTimeout(done, 0)));
|
|
829
|
+
const root = document.scrollingElement ?? document.documentElement;
|
|
830
|
+
const step = Math.max(Math.round(innerHeight * 0.8), 100);
|
|
831
|
+
for (let top = 0; top < root.scrollHeight && performance.now() < end; top += step) {
|
|
832
|
+
scrollTo({ top, behavior: "instant" });
|
|
833
|
+
await frame();
|
|
834
|
+
await frame();
|
|
835
|
+
}
|
|
836
|
+
scrollTo({ top: root.scrollHeight, behavior: "instant" });
|
|
837
|
+
await frame();
|
|
838
|
+
const waiting = () => [...document.querySelectorAll("astro-island[ssr]")].filter((island) => {
|
|
839
|
+
const client = island.getAttribute("client") ?? "";
|
|
840
|
+
if (client === "media") {
|
|
841
|
+
try {
|
|
842
|
+
const query = JSON.parse(island.getAttribute("opts") ?? "{}").value;
|
|
843
|
+
if (typeof query === "string" && !matchMedia(query).matches) return false;
|
|
844
|
+
} catch {}
|
|
845
|
+
}
|
|
846
|
+
if (client === "visible" && ![...island.children].some((child) => child.getClientRects().length > 0)) return false;
|
|
847
|
+
return true;
|
|
848
|
+
});
|
|
849
|
+
while (waiting().length > 0 && performance.now() < end) await new Promise((done) => setTimeout(done, 50));
|
|
850
|
+
scrollTo({ top: 0, behavior: "instant" });
|
|
851
|
+
await frame();
|
|
852
|
+
await frame();
|
|
853
|
+
return waiting().map((island) => (island.getAttribute("component-url") ?? "").split("/").pop() + " (client:" + (island.getAttribute("client") ?? "") + ")");
|
|
854
|
+
})()`;
|
|
855
|
+
}
|
|
856
|
+
/**
|
|
446
857
|
* This function gives the problems of the cuts of a view with the given width. A box that clips text is a problem at each width.
|
|
447
858
|
* A table or a code block in a box that scrolls is a problem only on a phone. A phone shows no scroll bar, but a desktop shows one.
|
|
448
859
|
* The summary and the log give the page of each problem.
|
|
@@ -488,13 +899,15 @@ async function checkSite(options) {
|
|
|
488
899
|
if (executable === void 0) throw new Error("no Chromium browser was found: give --browser, set SITE_CHECK_BROWSER, or install the Chromium of Playwright");
|
|
489
900
|
if (options.pages.length === 0) throw new Error("no page to check");
|
|
490
901
|
const probes = pageProbes(options);
|
|
902
|
+
if (options.out === void 0 && options.url === void 0) throw new Error("give out or url");
|
|
491
903
|
const server = options.out !== void 0 ? await serve(options.out, options.base ?? "/") : void 0;
|
|
492
|
-
const home = server?.url ?? options.url;
|
|
493
|
-
if (home === void 0) throw new Error("give out or url");
|
|
494
|
-
const homeUrl = new URL(home.endsWith("/") ? home : `${home}/`);
|
|
495
|
-
const browser = await launch(executable, options.timeoutMs);
|
|
496
904
|
const views = [];
|
|
905
|
+
let homeUrl;
|
|
906
|
+
let browser;
|
|
497
907
|
try {
|
|
908
|
+
const home = server?.url ?? options.url ?? "";
|
|
909
|
+
homeUrl = new URL(home.endsWith("/") ? home : `${home}/`);
|
|
910
|
+
browser = await launch(executable, options.timeoutMs);
|
|
498
911
|
const { page } = browser;
|
|
499
912
|
const events = watch(page, homeUrl.origin);
|
|
500
913
|
await Promise.all([
|
|
@@ -520,7 +933,7 @@ async function checkSite(options) {
|
|
|
520
933
|
}
|
|
521
934
|
}
|
|
522
935
|
} finally {
|
|
523
|
-
await browser
|
|
936
|
+
await browser?.close();
|
|
524
937
|
await server?.close();
|
|
525
938
|
}
|
|
526
939
|
const result = {
|
|
@@ -621,6 +1034,9 @@ async function checkView(page, events, input) {
|
|
|
621
1034
|
await loaded;
|
|
622
1035
|
await page.evaluate("document.fonts ? document.fonts.ready.then(() => true) : true");
|
|
623
1036
|
await new Promise((done) => setTimeout(done, options.settleMs));
|
|
1037
|
+
const islandMs = options.islandMs ?? 1e4;
|
|
1038
|
+
const stuck = await page.evaluate(revealExpression(islandMs));
|
|
1039
|
+
for (const island of stuck) view.problems.push(`an island did not start in ${String(islandMs)} ms after a scroll to the end: ${island}`);
|
|
624
1040
|
const pattern = await page.evaluate(OTHER_PATHS);
|
|
625
1041
|
if (pattern !== "") other = new RegExp(pattern);
|
|
626
1042
|
const measure = await page.evaluate(MEASURE);
|
|
@@ -839,6 +1255,468 @@ async function runCheckCli(argv, io) {
|
|
|
839
1255
|
if (step) appendFileSync(step, summary(result));
|
|
840
1256
|
return result.ok ? 0 : 1;
|
|
841
1257
|
}
|
|
1258
|
+
// src/check/nav.ts
|
|
1259
|
+
/**
|
|
1260
|
+
* The navigation check of a site (`site-pages nav`). It opens the home page in a headless Chromium.
|
|
1261
|
+
* It follows the links that the browser shows, and counts the clicks from home to each page.
|
|
1262
|
+
* The check fails when a page of the sitemap is more than `maxClicks` clicks from home.
|
|
1263
|
+
* It also fails when a page has no visible link back to home, or when a link of the site opens a new tab.
|
|
1264
|
+
* A link to a missing page fails too.
|
|
1265
|
+
*
|
|
1266
|
+
* The check clicks each link to the Releases page and the Status page.
|
|
1267
|
+
* A single-page application can catch such a click and show its own page in place of the page of site-pages.
|
|
1268
|
+
* The rules are functions with no I/O, so the tests call them with no browser.
|
|
1269
|
+
*/
|
|
1270
|
+
/**
|
|
1271
|
+
* This function gives the no-reads of a crawl: the paths left in its queue, and each path of the sitemap that it did not
|
|
1272
|
+
* open. A crawl with an empty queue read each page that a link reaches, so it has no no-read.
|
|
1273
|
+
*/
|
|
1274
|
+
function navUnread(queue, pages, sitemap) {
|
|
1275
|
+
if (queue.length === 0) return [];
|
|
1276
|
+
const opened = new Set(pages.map((page) => page.path));
|
|
1277
|
+
return [.../* @__PURE__ */ new Set([...queue, ...sitemap.filter((path) => !opened.has(path))])];
|
|
1278
|
+
}
|
|
1279
|
+
/** The desktop width of the crawl. */
|
|
1280
|
+
const NAV_DESKTOP_WIDTH = 1280;
|
|
1281
|
+
/**
|
|
1282
|
+
* This function gives the path of a URL from the site home, or undefined when the URL is not a page
|
|
1283
|
+
* of the site. A file with an extension other than `.html` is not a page. `index.html` is its folder.
|
|
1284
|
+
*/
|
|
1285
|
+
function sitePath(href, home) {
|
|
1286
|
+
let url;
|
|
1287
|
+
try {
|
|
1288
|
+
url = new URL(href, home);
|
|
1289
|
+
} catch {
|
|
1290
|
+
return;
|
|
1291
|
+
}
|
|
1292
|
+
if (url.origin !== home.origin || !url.pathname.startsWith(home.pathname)) return void 0;
|
|
1293
|
+
const path = url.pathname.slice(home.pathname.length).replace(/(^|\/)index\.html$/, "$1");
|
|
1294
|
+
const last = path.split("/").at(-1) ?? "";
|
|
1295
|
+
if (last.includes(".") && !last.endsWith(".html")) return void 0;
|
|
1296
|
+
return path;
|
|
1297
|
+
}
|
|
1298
|
+
/** This function gives the paths of the `<loc>` entries of a sitemap that are pages of the site. */
|
|
1299
|
+
function sitemapPaths(xml, home) {
|
|
1300
|
+
const paths = [...xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)].map((match) => sitePath(match[1] ?? "", home));
|
|
1301
|
+
return [...new Set(paths.filter((path) => path !== void 0))];
|
|
1302
|
+
}
|
|
1303
|
+
/** The name of a page in a message: its path, or "the home page". */
|
|
1304
|
+
const named = (path) => path === "" ? "the home page" : `/${path}`;
|
|
1305
|
+
/** This function gives the problems of a crawl. It reads no file and opens no page. */
|
|
1306
|
+
function navProblems(result, home, options) {
|
|
1307
|
+
const problems = [];
|
|
1308
|
+
const byPath = new Map(result.pages.map((page) => [page.path, page]));
|
|
1309
|
+
const unread = new Set(result.unread ?? []);
|
|
1310
|
+
for (const path of result.sitemap) {
|
|
1311
|
+
const page = byPath.get(path);
|
|
1312
|
+
if (page === void 0 && unread.has(path)) continue;
|
|
1313
|
+
if (page === void 0) problems.push(`${named(path)} is in the sitemap, and no chain of links from home reaches it`);
|
|
1314
|
+
else if (page.clicks > options.maxClicks) problems.push(`${named(path)} is ${page.clicks} clicks from home, over the limit of ${options.maxClicks}`);
|
|
1315
|
+
}
|
|
1316
|
+
for (const page of result.pages) {
|
|
1317
|
+
if (page.status >= 400) {
|
|
1318
|
+
problems.push(`a link of ${named(page.from ?? "")} goes to ${named(page.path)}, which gives HTTP ${page.status}`);
|
|
1319
|
+
continue;
|
|
1320
|
+
}
|
|
1321
|
+
if (page.path !== "") {
|
|
1322
|
+
if (!page.links.some((link) => link.visible && sitePath(link.href, home) === "")) problems.push(`${named(page.path)} shows no link back to home at ${NAV_DESKTOP_WIDTH} px`);
|
|
1323
|
+
else if (!page.homeAtPhone) problems.push(`${named(page.path)} shows no link back to home at 360 px`);
|
|
1324
|
+
}
|
|
1325
|
+
if (options.requireBar && !page.bar) problems.push(`${named(page.path)} has no site bar`);
|
|
1326
|
+
for (const link of page.links) if (link.target !== "" && link.target !== "_self" && sitePath(link.href, home) !== void 0) problems.push(`the link "${link.text}" of ${named(page.path)} opens ${named(sitePath(link.href, home) ?? "")} in a new tab, so the back button of the browser does not go back`);
|
|
1327
|
+
}
|
|
1328
|
+
for (const click of result.clicks) if (click.landed !== click.to) problems.push(`a click on the link to ${named(click.to)} of ${named(click.from)} shows ${named(click.landed)}`);
|
|
1329
|
+
else if (!click.shown) problems.push(`a click on the link to ${named(click.to)} of ${named(click.from)} does not show that page: the site shows its own page at that path`);
|
|
1330
|
+
return [...new Set(problems)];
|
|
1331
|
+
}
|
|
1332
|
+
/**
|
|
1333
|
+
* The function that clicks the first link of the page to the path in its argument, in the same tab. It gives true when
|
|
1334
|
+
* the page has such a link. The path is an argument of the call, so it is not a part of the code.
|
|
1335
|
+
*/
|
|
1336
|
+
const CLICK_LINK = `function (pathname) {
|
|
1337
|
+
const a = [...document.querySelectorAll("a[href]")].find((el) => new URL(el.getAttribute("href"), location.href).pathname === pathname);
|
|
1338
|
+
if (a) { a.removeAttribute("target"); a.click(); }
|
|
1339
|
+
return Boolean(a);
|
|
1340
|
+
}`;
|
|
1341
|
+
/** The expression that gives the links of the page and the marks of its header. */
|
|
1342
|
+
const NAV_SCAN = `(() => {
|
|
1343
|
+
const shown = (el) => {
|
|
1344
|
+
const box = el.getBoundingClientRect();
|
|
1345
|
+
if (box.width < 1 || box.height < 1) return false;
|
|
1346
|
+
for (let node = el; node; node = node.parentElement) {
|
|
1347
|
+
const style = getComputedStyle(node);
|
|
1348
|
+
if (style.visibility === "hidden" || style.display === "none" || Number(style.opacity) === 0) return false;
|
|
1349
|
+
}
|
|
1350
|
+
return box.right > 0 && box.left < innerWidth;
|
|
1351
|
+
};
|
|
1352
|
+
const links = [...document.querySelectorAll("a[href]")].map((a) => {
|
|
1353
|
+
const url = new URL(a.getAttribute("href"), location.href);
|
|
1354
|
+
url.hash = "";
|
|
1355
|
+
const text = (a.textContent || a.getAttribute("aria-label") || a.getAttribute("title") || "").replace(/\\s+/g, " ").trim().slice(0, 80);
|
|
1356
|
+
return { href: url.href, text, target: a.getAttribute("target") || "", visible: shown(a) };
|
|
1357
|
+
});
|
|
1358
|
+
return { links, bar: document.querySelector("[data-site-bar]") !== null, spHeader: document.querySelector(".sp-header") !== null, path: location.pathname };
|
|
1359
|
+
})()`;
|
|
1360
|
+
async function open(page, target, width, options) {
|
|
1361
|
+
await page.send("Emulation.setDeviceMetricsOverride", {
|
|
1362
|
+
width,
|
|
1363
|
+
height: 900,
|
|
1364
|
+
deviceScaleFactor: 1,
|
|
1365
|
+
mobile: width < 768
|
|
1366
|
+
});
|
|
1367
|
+
const loaded = page.once("Page.loadEventFired", options.timeoutMs);
|
|
1368
|
+
if ((await page.send("Page.navigate", { url: target })).errorText) {
|
|
1369
|
+
loaded.catch(() => {});
|
|
1370
|
+
return {
|
|
1371
|
+
status: 0,
|
|
1372
|
+
scan: {
|
|
1373
|
+
links: [],
|
|
1374
|
+
bar: false,
|
|
1375
|
+
spHeader: false,
|
|
1376
|
+
path: ""
|
|
1377
|
+
}
|
|
1378
|
+
};
|
|
1379
|
+
}
|
|
1380
|
+
await loaded;
|
|
1381
|
+
await new Promise((done) => setTimeout(done, options.settleMs));
|
|
1382
|
+
return {
|
|
1383
|
+
status: await documentStatus(target),
|
|
1384
|
+
scan: await page.evaluate(NAV_SCAN)
|
|
1385
|
+
};
|
|
1386
|
+
}
|
|
1387
|
+
/** This function gives the HTTP status of the document at the URL, or 0 when the request fails. */
|
|
1388
|
+
async function documentStatus(target) {
|
|
1389
|
+
try {
|
|
1390
|
+
const response = await fetch(target, { redirect: "follow" });
|
|
1391
|
+
await response.body?.cancel();
|
|
1392
|
+
return response.status;
|
|
1393
|
+
} catch {
|
|
1394
|
+
return 0;
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
async function shot(page, file, width) {
|
|
1398
|
+
const height = Math.min(Math.max(await page.evaluate("document.documentElement.scrollHeight"), 1), 3e3);
|
|
1399
|
+
const data = await page.send("Page.captureScreenshot", {
|
|
1400
|
+
format: "png",
|
|
1401
|
+
captureBeyondViewport: true,
|
|
1402
|
+
clip: {
|
|
1403
|
+
x: 0,
|
|
1404
|
+
y: 0,
|
|
1405
|
+
width,
|
|
1406
|
+
height,
|
|
1407
|
+
scale: 1
|
|
1408
|
+
}
|
|
1409
|
+
});
|
|
1410
|
+
writeFileSync(file, Buffer.from(data.data, "base64"));
|
|
1411
|
+
}
|
|
1412
|
+
/**
|
|
1413
|
+
* This function makes the browser write the bar into each HTML document of the site, at the response stage of the
|
|
1414
|
+
* request. A response that is not HTML, or a redirect, goes on with no change.
|
|
1415
|
+
*/
|
|
1416
|
+
async function previewBar(page, home, bar) {
|
|
1417
|
+
const fulfill = async (paused) => {
|
|
1418
|
+
const status = paused.responseStatusCode ?? 200;
|
|
1419
|
+
const headers = paused.responseHeaders ?? [];
|
|
1420
|
+
if (!(headers.find((header) => header.name.toLowerCase() === "content-type")?.value ?? "").includes("text/html") || status >= 300 && status < 400) {
|
|
1421
|
+
await page.send("Fetch.continueRequest", { requestId: paused.requestId });
|
|
1422
|
+
return;
|
|
1423
|
+
}
|
|
1424
|
+
const body = await page.send("Fetch.getResponseBody", { requestId: paused.requestId });
|
|
1425
|
+
const next = injectBar(body.base64Encoded ? Buffer.from(body.body, "base64").toString("utf8") : body.body, barHtml(bar, sitePath(paused.request.url, home) ?? ""));
|
|
1426
|
+
await page.send("Fetch.fulfillRequest", {
|
|
1427
|
+
requestId: paused.requestId,
|
|
1428
|
+
responseCode: status,
|
|
1429
|
+
responseHeaders: headers.filter((header) => !/^(content-length|content-encoding)$/i.test(header.name)),
|
|
1430
|
+
body: Buffer.from(next, "utf8").toString("base64")
|
|
1431
|
+
});
|
|
1432
|
+
};
|
|
1433
|
+
page.on("Fetch.requestPaused", (params) => {
|
|
1434
|
+
const paused = params;
|
|
1435
|
+
fulfill(paused).catch(() => page.send("Fetch.continueRequest", { requestId: paused.requestId }).catch(() => {}));
|
|
1436
|
+
});
|
|
1437
|
+
await page.send("Fetch.enable", { patterns: [{
|
|
1438
|
+
urlPattern: `${home.origin}${home.pathname}*`,
|
|
1439
|
+
resourceType: "Document",
|
|
1440
|
+
requestStage: "Response"
|
|
1441
|
+
}] });
|
|
1442
|
+
}
|
|
1443
|
+
/**
|
|
1444
|
+
* This function gives the repository of a site of GitHub Pages from the URL of its home, for example `owner/name`
|
|
1445
|
+
* for `https://owner.github.io/name/`. It gives undefined for a URL of another host.
|
|
1446
|
+
*/
|
|
1447
|
+
function repositoryOfUrl(url) {
|
|
1448
|
+
let parsed;
|
|
1449
|
+
try {
|
|
1450
|
+
parsed = new URL(url);
|
|
1451
|
+
} catch {
|
|
1452
|
+
return;
|
|
1453
|
+
}
|
|
1454
|
+
const owner = /^([a-z0-9-]+)\.github\.io$/i.exec(parsed.hostname)?.[1];
|
|
1455
|
+
if (owner === void 0) return void 0;
|
|
1456
|
+
return `${owner}/${parsed.pathname.split("/").filter(Boolean)[0] ?? `${owner}.github.io`}`;
|
|
1457
|
+
}
|
|
1458
|
+
/** This function crawls the site, clicks the links to the pages of site-pages, and gives the result. */
|
|
1459
|
+
async function crawlSite(options) {
|
|
1460
|
+
const log = options.log ?? (() => {});
|
|
1461
|
+
const executable = findBrowser(options.browser);
|
|
1462
|
+
if (executable === void 0) throw new Error("no Chromium browser was found: give --browser, set SITE_CHECK_BROWSER, or install the Chromium of Playwright");
|
|
1463
|
+
const server = options.out !== void 0 ? await serve(options.out, options.base ?? "/") : void 0;
|
|
1464
|
+
const start = server?.url ?? options.url;
|
|
1465
|
+
if (start === void 0) throw new Error("give out or url");
|
|
1466
|
+
const home = new URL(start.endsWith("/") ? start : `${start}/`);
|
|
1467
|
+
const browser = await launch(executable, options.timeoutMs);
|
|
1468
|
+
const pages = [];
|
|
1469
|
+
const clicks = [];
|
|
1470
|
+
let sitemap = [];
|
|
1471
|
+
let left = [];
|
|
1472
|
+
try {
|
|
1473
|
+
const { page } = browser;
|
|
1474
|
+
await Promise.all([page.send("Page.enable"), page.send("Runtime.enable")]);
|
|
1475
|
+
if (options.previewBar !== void 0) await previewBar(page, home, options.previewBar);
|
|
1476
|
+
try {
|
|
1477
|
+
const response = await fetch(new URL("sitemap.xml", home));
|
|
1478
|
+
if (response.ok) sitemap = sitemapPaths(await response.text(), home);
|
|
1479
|
+
} catch {
|
|
1480
|
+
sitemap = [];
|
|
1481
|
+
}
|
|
1482
|
+
if (options.shots) mkdirSync(options.shots, { recursive: true });
|
|
1483
|
+
const queue = [{
|
|
1484
|
+
path: "",
|
|
1485
|
+
clicks: 0,
|
|
1486
|
+
from: void 0
|
|
1487
|
+
}];
|
|
1488
|
+
const seen = /* @__PURE__ */ new Set([""]);
|
|
1489
|
+
while (queue.length > 0 && pages.length < options.maxPages) {
|
|
1490
|
+
const next = queue.shift();
|
|
1491
|
+
if (next === void 0) break;
|
|
1492
|
+
const target = new URL(next.path, home).href;
|
|
1493
|
+
const desktop = await open(page, target, NAV_DESKTOP_WIDTH, options);
|
|
1494
|
+
const homeAtPhone = (await open(page, target, 360, options)).scan.links.some((link) => link.visible && sitePath(link.href, home) === "");
|
|
1495
|
+
const entry = {
|
|
1496
|
+
path: next.path,
|
|
1497
|
+
clicks: next.clicks,
|
|
1498
|
+
status: desktop.status,
|
|
1499
|
+
from: next.from,
|
|
1500
|
+
links: desktop.scan.links,
|
|
1501
|
+
homeAtPhone,
|
|
1502
|
+
bar: desktop.scan.bar
|
|
1503
|
+
};
|
|
1504
|
+
pages.push(entry);
|
|
1505
|
+
log(`${next.clicks} ${named(next.path)} HTTP ${desktop.status}, ${desktop.scan.links.length} links${homeAtPhone ? "" : ", no home link at 360 px"}`);
|
|
1506
|
+
if (desktop.status >= 400) continue;
|
|
1507
|
+
for (const link of desktop.scan.links) {
|
|
1508
|
+
const path = sitePath(link.href, home);
|
|
1509
|
+
if (path === void 0 || seen.has(path)) continue;
|
|
1510
|
+
seen.add(path);
|
|
1511
|
+
queue.push({
|
|
1512
|
+
path,
|
|
1513
|
+
clicks: next.clicks + 1,
|
|
1514
|
+
from: next.path
|
|
1515
|
+
});
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
left = queue.map((entry) => entry.path);
|
|
1519
|
+
for (const from of pages.filter((entry) => entry.clicks <= 1 && entry.status < 400)) {
|
|
1520
|
+
const targets = [...new Set(from.links.map((link) => sitePath(link.href, home)).filter((path) => path === "releases/" || path === "status/"))];
|
|
1521
|
+
for (const to of targets) {
|
|
1522
|
+
if (to === from.path) continue;
|
|
1523
|
+
await open(page, new URL(from.path, home).href, NAV_DESKTOP_WIDTH, options);
|
|
1524
|
+
const landed = page.once("Page.loadEventFired", options.timeoutMs).catch(() => void 0);
|
|
1525
|
+
await page.call(CLICK_LINK, new URL(to, home).pathname);
|
|
1526
|
+
await Promise.race([landed, new Promise((done) => setTimeout(done, 3e3))]);
|
|
1527
|
+
await new Promise((done) => setTimeout(done, options.settleMs));
|
|
1528
|
+
const scan = await page.evaluate(NAV_SCAN);
|
|
1529
|
+
const click = {
|
|
1530
|
+
from: from.path,
|
|
1531
|
+
to,
|
|
1532
|
+
landed: sitePath(new URL(scan.path, home).href, home) ?? scan.path,
|
|
1533
|
+
shown: scan.spHeader || scan.bar
|
|
1534
|
+
};
|
|
1535
|
+
clicks.push(click);
|
|
1536
|
+
log(`click ${named(from.path)} -> ${named(to)}: ${named(click.landed)}${click.shown ? "" : ", not the page of site-pages"}`);
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
if (options.shots) for (const path of options.shotPages) for (const width of [NAV_DESKTOP_WIDTH, 360]) {
|
|
1540
|
+
const clean = path.replace(/^\/+/, "");
|
|
1541
|
+
await open(page, new URL(clean, home).href, width, options);
|
|
1542
|
+
await shot(page, join(options.shots, `${pageSlug(path)}-${width}.png`), width);
|
|
1543
|
+
}
|
|
1544
|
+
} finally {
|
|
1545
|
+
await browser.close();
|
|
1546
|
+
await server?.close();
|
|
1547
|
+
}
|
|
1548
|
+
const unread = navUnread(left, pages, sitemap);
|
|
1549
|
+
const problems = navProblems({
|
|
1550
|
+
pages,
|
|
1551
|
+
sitemap,
|
|
1552
|
+
clicks,
|
|
1553
|
+
unread
|
|
1554
|
+
}, home, options);
|
|
1555
|
+
const result = {
|
|
1556
|
+
ok: problems.length === 0 && unread.length === 0,
|
|
1557
|
+
home: home.href,
|
|
1558
|
+
pages,
|
|
1559
|
+
sitemap,
|
|
1560
|
+
clicks,
|
|
1561
|
+
problems,
|
|
1562
|
+
unread
|
|
1563
|
+
};
|
|
1564
|
+
if (options.shots) {
|
|
1565
|
+
writeFileSync(join(options.shots, "report.json"), `${JSON.stringify(result, null, 2)}\n`);
|
|
1566
|
+
writeFileSync(join(options.shots, "summary.md"), navSummary(result));
|
|
1567
|
+
}
|
|
1568
|
+
return result;
|
|
1569
|
+
}
|
|
1570
|
+
/** This function gives the text of the no-reads of a crawl, with their count and the first 10 paths. */
|
|
1571
|
+
function navUnreadText(result) {
|
|
1572
|
+
const first = result.unread.slice(0, 10).map(named).join(", ");
|
|
1573
|
+
const more = result.unread.length > 10 ? `, and ${String(result.unread.length - 10)} more` : "";
|
|
1574
|
+
return `the crawl stopped at the limit of ${result.pages.length} ${result.pages.length === 1 ? "page" : "pages"}, so it did not read ${result.unread.length} ${result.unread.length === 1 ? "page" : "pages"}: ${first}${more}.`;
|
|
1575
|
+
}
|
|
1576
|
+
/** This function gives the summary of a crawl as Markdown. */
|
|
1577
|
+
function navSummary(result) {
|
|
1578
|
+
const lines = [
|
|
1579
|
+
`### Navigation of ${result.home}`,
|
|
1580
|
+
"",
|
|
1581
|
+
`${result.pages.length} ${result.pages.length === 1 ? "page" : "pages"} opened, ${result.sitemap.length} in the sitemap, ${result.problems.length} ${result.problems.length === 1 ? "problem" : "problems"}.`,
|
|
1582
|
+
""
|
|
1583
|
+
];
|
|
1584
|
+
if (result.unread.length > 0) lines.push(`**No read:** ${navUnreadText(result)}`, "");
|
|
1585
|
+
for (const problem of result.problems) lines.push(`- ${cell(problem)}`);
|
|
1586
|
+
lines.push("", "| Clicks | Page | HTTP | Home link at 360 px | Site bar |", "|---|---|---|---|---|");
|
|
1587
|
+
for (const page of result.pages) lines.push(`| ${page.clicks} | ${named(page.path)} | ${page.status} | ${page.homeAtPhone ? "yes" : "no"} | ${page.bar ? "yes" : "no"} |`);
|
|
1588
|
+
return `${lines.join("\n")}\n`;
|
|
1589
|
+
}
|
|
1590
|
+
const NAV_HELP = `Usage: site-pages nav (--out <dir> | --url <url>) [options]
|
|
1591
|
+
|
|
1592
|
+
Opens the home page of the site in a headless Chromium and follows the links that the page shows,
|
|
1593
|
+
page by page. It fails when a page of sitemap.xml is more than --max-clicks clicks from home, when
|
|
1594
|
+
a page shows no link back to home at 1280 px or at 360 px, when a link of the site opens a new tab,
|
|
1595
|
+
or when a link goes to a missing page. It clicks each link to releases/ and status/, and fails when
|
|
1596
|
+
the page after the click does not have the header of site-pages.
|
|
1597
|
+
|
|
1598
|
+
Options:
|
|
1599
|
+
--out <dir> The built site folder. The crawl serves it at --base.
|
|
1600
|
+
--url <url> The URL of a live site home, in place of --out
|
|
1601
|
+
--repo <owner/name> The GitHub repository, for the default base (default: $GITHUB_REPOSITORY)
|
|
1602
|
+
--base </name/> The path of the site home (default: "/<name>/", or "/" for <owner>.github.io)
|
|
1603
|
+
--max-clicks <n> The largest number of clicks from home to a page (default: 2)
|
|
1604
|
+
--max-pages <n> The largest number of pages to open (default: 60)
|
|
1605
|
+
--require-bar Each page must have the shared site bar ([data-site-bar])
|
|
1606
|
+
--preview-bar The browser writes the shared site bar into each page of the site as it
|
|
1607
|
+
loads, with Releases and Status. Thus a live site shows the bar before its
|
|
1608
|
+
Pages workflow adds it. The repository comes from a github.io URL, or --repo.
|
|
1609
|
+
--bar-pages <list> The pages of the preview bar, as label=path pairs separated by commas
|
|
1610
|
+
--bar-npm <name> The npm name of the package, for the npm link of the preview bar
|
|
1611
|
+
--shots <dir> The folder for the screenshots, report.json and summary.md
|
|
1612
|
+
--shot-pages <list> The pages to take screenshots of, separated by commas (default: /,releases/,status/)
|
|
1613
|
+
--browser <file> The Chromium executable (default: $SITE_CHECK_BROWSER, the Chromium of
|
|
1614
|
+
Playwright, else Chrome or Edge)
|
|
1615
|
+
--settle <ms> The wait after the load event (default: 800)
|
|
1616
|
+
--timeout <ms> The time limit of a page load (default: 30000)
|
|
1617
|
+
--help Shows this text
|
|
1618
|
+
|
|
1619
|
+
With $GITHUB_STEP_SUMMARY, the crawl adds its table to the job summary.
|
|
1620
|
+
`;
|
|
1621
|
+
/** This function starts the `nav` command with its arguments, without the word `nav`. */
|
|
1622
|
+
async function runNavCli(argv, io) {
|
|
1623
|
+
let values;
|
|
1624
|
+
try {
|
|
1625
|
+
({values} = parseArgs({
|
|
1626
|
+
args: [...argv],
|
|
1627
|
+
allowPositionals: false,
|
|
1628
|
+
options: {
|
|
1629
|
+
out: { type: "string" },
|
|
1630
|
+
url: { type: "string" },
|
|
1631
|
+
repo: { type: "string" },
|
|
1632
|
+
base: { type: "string" },
|
|
1633
|
+
"max-clicks": { type: "string" },
|
|
1634
|
+
"max-pages": { type: "string" },
|
|
1635
|
+
"require-bar": { type: "boolean" },
|
|
1636
|
+
"preview-bar": { type: "boolean" },
|
|
1637
|
+
"bar-pages": { type: "string" },
|
|
1638
|
+
"bar-npm": { type: "string" },
|
|
1639
|
+
shots: { type: "string" },
|
|
1640
|
+
"shot-pages": { type: "string" },
|
|
1641
|
+
browser: { type: "string" },
|
|
1642
|
+
settle: { type: "string" },
|
|
1643
|
+
timeout: { type: "string" },
|
|
1644
|
+
help: { type: "boolean" }
|
|
1645
|
+
}
|
|
1646
|
+
}));
|
|
1647
|
+
} catch (error) {
|
|
1648
|
+
io.stderr(`site-pages nav: ${error instanceof Error ? error.message : String(error)}\n\n${NAV_HELP}`);
|
|
1649
|
+
return 2;
|
|
1650
|
+
}
|
|
1651
|
+
if (values["help"]) {
|
|
1652
|
+
io.stdout(NAV_HELP);
|
|
1653
|
+
return 0;
|
|
1654
|
+
}
|
|
1655
|
+
const usage = (message) => {
|
|
1656
|
+
io.stderr(`site-pages nav: ${message}\n\n${NAV_HELP}`);
|
|
1657
|
+
return 2;
|
|
1658
|
+
};
|
|
1659
|
+
const text = (key) => typeof values[key] === "string" ? values[key] : void 0;
|
|
1660
|
+
const out = text("out");
|
|
1661
|
+
const url = text("url");
|
|
1662
|
+
if (out === void 0 === (url === void 0)) return usage("give --out or --url, not both");
|
|
1663
|
+
const maxClicks = Number(text("max-clicks") ?? 2);
|
|
1664
|
+
const maxPages = Number(text("max-pages") ?? 60);
|
|
1665
|
+
if (!Number.isInteger(maxClicks) || maxClicks < 1 || !Number.isInteger(maxPages) || maxPages < 1) return usage("--max-clicks and --max-pages must be whole numbers of 1 or more");
|
|
1666
|
+
const settleMs = Number(text("settle") ?? 800);
|
|
1667
|
+
const timeoutMs = Number(text("timeout") ?? 3e4);
|
|
1668
|
+
if (!(settleMs >= 0) || !(timeoutMs > 0)) return usage("--settle and --timeout must be numbers of milliseconds");
|
|
1669
|
+
const shotPages = (text("shot-pages") ?? "/,releases/,status/").split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
1670
|
+
const notPath = shotPages.find((entry) => entry.includes(":") || entry.includes("\\"));
|
|
1671
|
+
if (notPath !== void 0) return usage(`a page is a path from the site home, not "${notPath}" (in Git Bash, set MSYS_NO_PATHCONV=1)`);
|
|
1672
|
+
let base = text("base");
|
|
1673
|
+
if (out !== void 0 && base === void 0) {
|
|
1674
|
+
const name = (text("repo") ?? io.env["GITHUB_REPOSITORY"] ?? "").split("/")[1];
|
|
1675
|
+
if (!name) return usage("give --base, --repo or set GITHUB_REPOSITORY");
|
|
1676
|
+
base = /\.github\.io$/i.test(name) ? "/" : `/${name}/`;
|
|
1677
|
+
}
|
|
1678
|
+
if (base !== void 0) base = `/${base.replace(/^\/+|\/+$/g, "")}/`.replace(/^\/\/$/, "/");
|
|
1679
|
+
let preview;
|
|
1680
|
+
if (values["preview-bar"] === true) {
|
|
1681
|
+
const repository = text("repo") ?? (url === void 0 ? io.env["GITHUB_REPOSITORY"] : repositoryOfUrl(url));
|
|
1682
|
+
if (repository === void 0 || !repository.includes("/")) return usage("--preview-bar needs --repo for a site that is not on github.io");
|
|
1683
|
+
const pages = parsePages(text("bar-pages") ?? "");
|
|
1684
|
+
if (pages instanceof Error) return usage(pages.message);
|
|
1685
|
+
const previewBase = base ?? (url === void 0 ? "/" : new URL(url.endsWith("/") ? url : `${url}/`).pathname);
|
|
1686
|
+
const [owner = ""] = repository.split("/");
|
|
1687
|
+
const ownerSite = repository.toLowerCase() === `${owner.toLowerCase()}/${owner.toLowerCase()}.github.io`;
|
|
1688
|
+
preview = {
|
|
1689
|
+
repository,
|
|
1690
|
+
base: previewBase,
|
|
1691
|
+
pages,
|
|
1692
|
+
sitePages: true,
|
|
1693
|
+
npm: text("bar-npm"),
|
|
1694
|
+
portfolio: ownerSite ? void 0 : `https://${owner.toLowerCase()}.github.io/`
|
|
1695
|
+
};
|
|
1696
|
+
}
|
|
1697
|
+
const shots = text("shots");
|
|
1698
|
+
const result = await crawlSite({
|
|
1699
|
+
out: out === void 0 ? void 0 : isAbsolute(out) ? out : resolve(io.cwd, out),
|
|
1700
|
+
url,
|
|
1701
|
+
base,
|
|
1702
|
+
maxClicks,
|
|
1703
|
+
maxPages,
|
|
1704
|
+
requireBar: values["require-bar"] === true,
|
|
1705
|
+
previewBar: preview,
|
|
1706
|
+
shots: shots === void 0 ? void 0 : isAbsolute(shots) ? shots : resolve(io.cwd, shots),
|
|
1707
|
+
shotPages,
|
|
1708
|
+
browser: text("browser"),
|
|
1709
|
+
settleMs,
|
|
1710
|
+
timeoutMs,
|
|
1711
|
+
log: (line) => io.stdout(`${line}\n`)
|
|
1712
|
+
});
|
|
1713
|
+
for (const problem of result.problems) io.stdout(`FAIL ${problem}\n`);
|
|
1714
|
+
if (result.unread.length > 0) io.stdout(`NO READ ${navUnreadText(result)}\n`);
|
|
1715
|
+
io.stdout(`site-pages nav: ${result.pages.length} ${result.pages.length === 1 ? "page" : "pages"}, ${result.problems.length} ${result.problems.length === 1 ? "problem" : "problems"}, ${result.unread.length} ${result.unread.length === 1 ? "page" : "pages"} not read.\n`);
|
|
1716
|
+
const step = io.env["GITHUB_STEP_SUMMARY"];
|
|
1717
|
+
if (step) appendFileSync(step, navSummary(result));
|
|
1718
|
+
return result.ok ? 0 : 1;
|
|
1719
|
+
}
|
|
842
1720
|
// src/cli.ts
|
|
843
1721
|
const argv = process.argv.slice(2);
|
|
844
1722
|
const io = {
|
|
@@ -847,7 +1725,7 @@ const io = {
|
|
|
847
1725
|
stdout: (text) => process.stdout.write(text),
|
|
848
1726
|
stderr: (text) => process.stderr.write(text)
|
|
849
1727
|
};
|
|
850
|
-
(argv[0] === "check" ? runCheckCli(argv.slice(1), io) : argv[0] === "freshness" ? runFreshnessCli(argv.slice(1), io) : runCli(argv, io)).then((code) => {
|
|
1728
|
+
(argv[0] === "check" ? runCheckCli(argv.slice(1), io) : argv[0] === "freshness" ? runFreshnessCli(argv.slice(1), io) : argv[0] === "nav" ? runNavCli(argv.slice(1), io) : argv[0] === "bar" ? Promise.resolve(runBarCli(argv.slice(1), io)) : argv[0] === "cue" ? Promise.resolve(runCueCli(argv.slice(1), io)) : runCli(argv, io)).then((code) => {
|
|
851
1729
|
process.exitCode = code;
|
|
852
1730
|
}, (error) => {
|
|
853
1731
|
process.stderr.write(`site-pages: ${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
|