@mark1russell7/site-pages 0.8.1 → 0.8.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 CHANGED
@@ -688,6 +688,79 @@ The file sets no look for the content. Buttons, cards, code and tables stay in t
688
688
 
689
689
  A site with its own look does not import `shell.css`. It uses only the plugin and `showBuild`, or nothing from this section.
690
690
 
691
+ ## The offline shell of a site
692
+
693
+ The entry `@mark1russell7/site-pages/offline` is for `vite.config.ts`. Its plugin `siteOffline` lets a built site open with no network. A phone can also install the site as an app.
694
+
695
+ ```ts
696
+ import { defineConfig } from "vite";
697
+ import { siteOffline } from "@mark1russell7/site-pages/offline";
698
+
699
+ export default defineConfig({
700
+ root: "site",
701
+ plugins: [siteOffline({ manifest: { name: "Field notes", icons: [{ src: "icon.svg", sizes: "any", type: "image/svg+xml" }] } })],
702
+ });
703
+ ```
704
+
705
+ The plugin operates only in a build. It does these three operations:
706
+
707
+ - It adds a manifest link and a small script to each HTML page. The script registers the service worker. A failure goes to `console.warn`, so a browser with no service worker shows the page as usual.
708
+ - It writes `manifest.webmanifest`. The app starts at the site home, and its scope is the site home.
709
+ - It writes `service-worker.js`. The worker keeps each file of the built folder. These files include the files of the public folder and of other plugins.
710
+
711
+ Put `siteOffline` last in the list of plugins. A file that a step after the Vite build adds is not in the list of the worker.
712
+
713
+ These files stay out of the cache:
714
+
715
+ - source maps,
716
+ - the files and folders with a name that starts with a dot,
717
+ - each file larger than `maxFileBytes` (the default is 10 MiB),
718
+ - each file that a pattern of `exclude` matches. A pattern examines the path from the root of the folder.
719
+
720
+ The worker answers a request of a kept file from its cache. The path of a folder gives its `index.html`. A navigation to a page that the worker does not keep goes to the network. With no network, it gets the home page from the cache, with the header `x-site-offline: fallback`. The worker does not answer other requests.
721
+
722
+ The name of the cache has the base of the site and a SHA-256 hash of the kept files. A new build with a changed file gives a new name. The new worker then removes the old cache of the same base, and only that cache.
723
+
724
+ The register script also tells the state of the offline copy to the page. It sets the attribute `data-offline` of the root element, and it sends the event `site-offline` on `window` at each change. Show the state to the visitor. A phone that closes the page before the end of the copy keeps no copy.
725
+
726
+ | State | Meaning |
727
+ | --- | --- |
728
+ | `none` | The browser has no service worker. The site has no offline copy. |
729
+ | `outside` | The page is outside the scope of the worker, for example the home address with no slash at its end. |
730
+ | `saving` | The worker keeps the files. The copy is not complete. |
731
+ | `ready` | An active worker kept each file. The site opens with no network. |
732
+ | `failed` | The browser refused the worker, or the worker did not keep each file. |
733
+
734
+ `watchOffline(listener)` of `@mark1russell7/site-pages/chrome` calls the listener with the current state and with each change. It gives the function that stops the calls.
735
+
736
+ ```ts
737
+ import { watchOffline } from "@mark1russell7/site-pages/chrome";
738
+
739
+ watchOffline((state) => (byId("offline").textContent = state === "ready" ? "This page opens with no network." : ""));
740
+ ```
741
+
742
+ The worker keeps only the built files. It keeps no data of the site. Data that the site reads or writes goes offline through its own store.
743
+
744
+ The base of the site must be a path from the root of the origin, for example `/` or `/name/`. A relative base, for example `./`, stops the build.
745
+
746
+ | Export of `./offline` | Operation |
747
+ | --- | --- |
748
+ | `siteOffline({ manifest, maxFileBytes, exclude, onList })` | Makes the plugin. The value `false` for `manifest` writes no manifest. `onList` gets the kept files and the files that stay out. |
749
+ | `precacheList(files, { base, maxFileBytes, exclude })` | Gives the URLs that the worker keeps, in order, and the reason of each file that stays out. It has no I/O. |
750
+ | `offlineCacheName(base, files)` | Gives the name of the cache from the URLs and the contents of the kept files. |
751
+ | `serviceWorkerSource({ base, cache, urls })` | Gives the source of the service worker. |
752
+ | `webManifest(options, base)` | Gives the web manifest. |
753
+ | `registerScript(base)` | Gives the script that registers the worker and tells the state of the copy, for a page without the plugin. |
754
+ | `OFFLINE_STATES`, `OFFLINE_EVENT`, `OFFLINE_ATTRIBUTE` | Give the states of the copy, the name of the event and the name of the attribute. |
755
+
756
+ The command `site-pages check --out <dir> --offline` is the gate of the offline shell. After the usual views, it opens the home page in a new browser and waits until a service worker controls the page. Then it stops its server, cuts the network of the page, and opens each page again, at the first width and in the first scheme. An offline view fails for each of these problems:
757
+
758
+ - No service worker of the site becomes active in the time limit of a page load.
759
+ - The worker does not answer the page, or gives the home page in its place.
760
+ - Each problem of a usual view, for example a request that fails.
761
+
762
+ The option `--offline` needs `--out`, because the check stops the server of the folder to cut the network.
763
+
691
764
  ## The response explorer
692
765
 
693
766
  The entry `@mark1russell7/site-pages/explorer` shows a measured response in the browser. A visitor chooses a measure, varies one or two dimensions, and holds or facets the others. The view shows the measured points, the fitted curve or surface, and its held-out error in plain words. The record has the format `response-records/1` of `@mark1russell7/rigor-statistics`.
package/build/chrome.d.ts CHANGED
@@ -1,9 +1,25 @@
1
1
  /**
2
2
  * The small helpers of a page in the browser: the element helpers, the element lookup, the theme
3
- * button, the copy button and the build stamp. It also has a radio group with one focus stop.
3
+ * button, the copy button and the build stamp. It also has a radio group with one focus stop,
4
+ * and the state of the offline copy of the site.
4
5
  * This module imports no Node.js module, so a site can bundle it. Import it from
5
6
  * `@mark1russell7/site-pages/chrome`, because the package root also has Node.js code.
6
7
  */
8
+ /**
9
+ * The states of the offline copy:
10
+ * - `none`: the browser has no service worker, so the site has no offline copy.
11
+ * - `outside`: the page is outside the scope of the worker, for example the address of the home with no slash at its end.
12
+ * - `saving`: the worker keeps the files. The copy is not complete.
13
+ * - `ready`: an active worker kept each file. The site opens with no network.
14
+ * - `failed`: the browser refused the worker, or the worker did not keep each file.
15
+ */
16
+ export declare const OFFLINE_STATES: readonly ["none", "outside", "saving", "ready", "failed"];
17
+ /** A state of the offline copy. */
18
+ export type OfflineState = (typeof OFFLINE_STATES)[number];
19
+ /** The event on `window` at each change of the state. Its `detail` is the state. */
20
+ export declare const OFFLINE_EVENT = "site-offline";
21
+ /** The attribute of the root element with the current state, so a style can show it. */
22
+ export declare const OFFLINE_ATTRIBUTE = "data-offline";
7
23
  /** A child of `h`: a node or a text. The values `null`, `undefined` and `false` give no child. */
8
24
  export type Child = Node | string | null | undefined | false;
9
25
  /** The value of an attribute of `h`. The value `true` gives an empty attribute. */
@@ -125,4 +141,10 @@ export declare class Segmented<T extends string> {
125
141
  private choose;
126
142
  private show;
127
143
  }
144
+ /**
145
+ * This function calls `listener` with the state of the offline copy of the site, and again at each change.
146
+ * The register script of `siteOffline` tells the state. A page with no register script gets no call.
147
+ * It gives the function that stops the calls.
148
+ */
149
+ export declare function watchOffline(listener: (state: OfflineState) => void): () => void;
128
150
  //# sourceMappingURL=chrome.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"chrome.d.ts","names":[],"sources":["../src/chrome.ts"],"mappings":";;;;;;;YASY,QAAQ;;YAGR;;;;;wBAMI,EAAE,gBAAgB,uBAChC,KAAK,GACL,QAAO,SAAS,eAAe,qBAC5B,oBAAoB,iBAAiB,aACvC,sBAAsB;;;;;;wBAeT,IAAI,gBAAgB,sBAClC,KAAK,GACL,QAAO,SAAS,eAAe,qBAC5B,oBAAoB,iBAAiB,aACvC,qBAAqB;;;;;wBA8BR,KAAK,UAAU,cAAc,aAAa,aAAa;;qBAO1D;;YAGD,gBAAgB;;;;;wBAMZ,gBAAgB;;;;;wBAShB,WAAW,OAAO,OAAO;;wBAazB,UAAU,qBAAqB;;;;;;;;;wBAc/B,WAAW,QAAQ,mBAAmB;;iBAUrC;;WAEN;;WAEA;;WAEA;;;;;;;;;wBAUK,UAAU,SAAS,aAAa,OAAO,WAAW;;;;;wBAS5C,gBAAgB,eAAe;;iBA0BpC;;WAEN;;WAEA;;WAEA;;;;;;wBAOW,SAAS,QAAQ,mBAAmB,cAAc,UAAS,kBAAuB;;;YAY5F;;;;;;wBAaI,YAAY,aAAa,eAAe,eAAe,OAAM;;iBAQ5D,OAAO;;WAEb,OAAO;;WAEP;;WAEA;;;;;;;qBAQE,UAAU;mBACJ;mBACA;mBACA;UACT;;;;;EAMR,YAAY,WAAW,aAAa,kBAAkB,OAAO,MAAM,SAAS,GAAG,WAAW,OAAO,YAAY,OAAM;;MAyB/G,SAAS;;EAKb,IAAI,OAAO;UAKH;UAOA"}
1
+ {"version":3,"file":"chrome.d.ts","names":[],"sources":["../src/chrome.ts"],"mappings":";;;;;;;;;;;;;;;qBAiBa;;YAGD,uBAAuB;;qBAGtB;;qBAGA;;YAGD,QAAQ;;YAGR;;;;;wBAMI,EAAE,gBAAgB,uBAChC,KAAK,GACL,QAAO,SAAS,eAAe,qBAC5B,oBAAoB,iBAAiB,aACvC,sBAAsB;;;;;;wBAeT,IAAI,gBAAgB,sBAClC,KAAK,GACL,QAAO,SAAS,eAAe,qBAC5B,oBAAoB,iBAAiB,aACvC,qBAAqB;;;;;wBA8BR,KAAK,UAAU,cAAc,aAAa,aAAa;;qBAO1D;;YAGD,gBAAgB;;;;;wBAMZ,gBAAgB;;;;;wBAShB,WAAW,OAAO,OAAO;;wBAazB,UAAU,qBAAqB;;;;;;;;;wBAc/B,WAAW,QAAQ,mBAAmB;;iBAUrC;;WAEN;;WAEA;;WAEA;;;;;;;;;wBAUK,UAAU,SAAS,aAAa,OAAO,WAAW;;;;;wBAS5C,gBAAgB,eAAe;;iBA0BpC;;WAEN;;WAEA;;WAEA;;;;;;wBAOW,SAAS,QAAQ,mBAAmB,cAAc,UAAS,kBAAuB;;;YAY5F;;;;;;wBAaI,YAAY,aAAa,eAAe,eAAe,OAAM;;iBAQ5D,OAAO;;WAEb,OAAO;;WAEP;;WAEA;;;;;;;qBAQE,UAAU;mBACJ;mBACA;mBACA;UACT;;;;;EAMR,YAAY,WAAW,aAAa,kBAAkB,OAAO,MAAM,SAAS,GAAG,WAAW,OAAO,YAAY,OAAM;;MAyB/G,SAAS;;EAKb,IAAI,OAAO;UAKH;UAOA;;;;;;;wBAoBM,aAAa,WAAW,OAAO"}
package/build/chrome.js CHANGED
@@ -1,5 +1,31 @@
1
1
  // src/chrome.ts
2
2
  /**
3
+ * The small helpers of a page in the browser: the element helpers, the element lookup, the theme
4
+ * button, the copy button and the build stamp. It also has a radio group with one focus stop,
5
+ * and the state of the offline copy of the site.
6
+ * This module imports no Node.js module, so a site can bundle it. Import it from
7
+ * `@mark1russell7/site-pages/chrome`, because the package root also has Node.js code.
8
+ */
9
+ /**
10
+ * The states of the offline copy:
11
+ * - `none`: the browser has no service worker, so the site has no offline copy.
12
+ * - `outside`: the page is outside the scope of the worker, for example the address of the home with no slash at its end.
13
+ * - `saving`: the worker keeps the files. The copy is not complete.
14
+ * - `ready`: an active worker kept each file. The site opens with no network.
15
+ * - `failed`: the browser refused the worker, or the worker did not keep each file.
16
+ */
17
+ const OFFLINE_STATES = [
18
+ "none",
19
+ "outside",
20
+ "saving",
21
+ "ready",
22
+ "failed"
23
+ ];
24
+ /** The event on `window` at each change of the state. Its `detail` is the state. */
25
+ const OFFLINE_EVENT = "site-offline";
26
+ /** The attribute of the root element with the current state, so a style can show it. */
27
+ const OFFLINE_ATTRIBUTE = "data-offline";
28
+ /**
3
29
  * This function makes an element with attributes and children. An attribute with the value
4
30
  * `false`, `null` or `undefined` is not set. The attribute `class` sets the class name.
5
31
  */
@@ -233,6 +259,25 @@ var Segmented = class {
233
259
  });
234
260
  }
235
261
  };
236
- export { Segmented, THEMES, applyTheme, byId, copyText, copyToClipboard, currentTheme, h, nextTheme, rovingIndex, setupTheme, showBuild, svg };
262
+ /** This function gives a value as a state of the offline copy, or `undefined` when it is not a state. */
263
+ function offlineStateOf(value) {
264
+ return OFFLINE_STATES.find((state) => state === value);
265
+ }
266
+ /**
267
+ * This function calls `listener` with the state of the offline copy of the site, and again at each change.
268
+ * The register script of `siteOffline` tells the state. A page with no register script gets no call.
269
+ * It gives the function that stops the calls.
270
+ */
271
+ function watchOffline(listener) {
272
+ const now = offlineStateOf(document.documentElement.getAttribute(OFFLINE_ATTRIBUTE));
273
+ if (now !== void 0) listener(now);
274
+ const changed = (event) => {
275
+ const state = offlineStateOf(event.detail);
276
+ if (state !== void 0) listener(state);
277
+ };
278
+ addEventListener(OFFLINE_EVENT, changed);
279
+ return () => removeEventListener(OFFLINE_EVENT, changed);
280
+ }
281
+ export { OFFLINE_ATTRIBUTE, OFFLINE_EVENT, OFFLINE_STATES, Segmented, THEMES, applyTheme, byId, copyText, copyToClipboard, currentTheme, h, nextTheme, rovingIndex, setupTheme, showBuild, svg, watchOffline };
237
282
 
238
283
  //# sourceMappingURL=chrome.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"chrome.js","names":[],"sources":["../src/chrome.ts"],"sourcesContent":["/// <reference lib=\"dom\" />\n/**\n * The small helpers of a page in the browser: the element helpers, the element lookup, the theme\n * button, the copy button and the build stamp. It also has a radio group with one focus stop.\n * This module imports no Node.js module, so a site can bundle it. Import it from\n * `@mark1russell7/site-pages/chrome`, because the package root also has Node.js code.\n */\n\n/** A child of `h`: a node or a text. The values `null`, `undefined` and `false` give no child. */\nexport type Child = Node | string | null | undefined | false;\n\n/** The value of an attribute of `h`. The value `true` gives an empty attribute. */\nexport type AttributeValue = string | number | boolean | null | undefined;\n\n/**\n * This function makes an element with attributes and children. An attribute with the value\n * `false`, `null` or `undefined` is not set. The attribute `class` sets the class name.\n */\nexport function h<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n attrs: Readonly<Record<string, AttributeValue>> = {},\n ...children: readonly (Child | readonly Child[])[]\n): HTMLElementTagNameMap[K] {\n const el = document.createElement(tag);\n return fill(el, attrs, children, (value) => {\n el.className = value;\n });\n}\n\n/** The namespace of the SVG elements. */\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\n/**\n * This function makes an SVG element with attributes and children, with the rules of `h`. The\n * attribute `class` sets the attribute `class`, because the class name of an SVG element is\n * read-only.\n */\nexport function svg<K extends keyof SVGElementTagNameMap>(\n tag: K,\n attrs: Readonly<Record<string, AttributeValue>> = {},\n ...children: readonly (Child | readonly Child[])[]\n): SVGElementTagNameMap[K] {\n const el = document.createElementNS(SVG_NS, tag);\n return fill(el, attrs, children, (value) => {\n el.setAttribute(\"class\", value);\n });\n}\n\n/** This function sets the attributes and adds the children of an element of `h` or `svg`. */\nfunction fill<E extends Element>(\n el: E,\n attrs: Readonly<Record<string, AttributeValue>>,\n children: readonly (Child | readonly Child[])[],\n setClass: (value: string) => void,\n): E {\n for (const [name, value] of Object.entries(attrs)) {\n if (value === false || value === null || value === undefined) continue;\n if (name === \"class\") setClass(String(value));\n else el.setAttribute(name, value === true ? \"\" : String(value));\n }\n for (const child of children.flat()) {\n if (child === null || child === undefined || child === false) continue;\n el.append(child);\n }\n return el;\n}\n\n/**\n * This function gives the element with the ID. The page has each ID that the code asks for. Thus\n * a missing ID is an error of the page, and the function throws an `Error`.\n */\nexport function byId<T extends HTMLElement = HTMLElement>(id: string): T {\n const el = document.getElementById(id);\n if (el === null) throw new Error(`The page has no element \"${id}\".`);\n return el as T;\n}\n\n/** The themes of the theme button, in the sequence of the clicks. `auto` follows the setting of the system. */\nexport const THEMES: readonly [\"auto\", \"light\", \"dark\"] = [\"auto\", \"light\", \"dark\"];\n\n/** A theme of the page. */\nexport type Theme = (typeof THEMES)[number];\n\n/**\n * This function gives the theme of the page from the attribute `data-theme` of the `html` element.\n * Without the attribute, or with another value, the theme is `auto`.\n */\nexport function currentTheme(): Theme {\n const theme = document.documentElement.dataset[\"theme\"];\n return theme === \"light\" || theme === \"dark\" ? theme : \"auto\";\n}\n\n/**\n * This function sets the theme of the page, and keeps it in `localStorage` under `storageKey`.\n * The theme `auto` removes the attribute `data-theme` and the stored value.\n */\nexport function applyTheme(theme: Theme, storageKey: string): void {\n const root = document.documentElement;\n if (theme === \"auto\") delete root.dataset[\"theme\"];\n else root.dataset[\"theme\"] = theme;\n try {\n if (theme === \"auto\") localStorage.removeItem(storageKey);\n else localStorage.setItem(storageKey, theme);\n } catch {\n // A browser with no storage keeps the theme until the page closes.\n }\n}\n\n/** This function sets the next theme after the current theme (auto, light, dark, auto), and gives it. */\nexport function nextTheme(storageKey: string): Theme {\n const next = THEMES[(THEMES.indexOf(currentTheme()) + 1) % THEMES.length] ?? \"auto\";\n applyTheme(next, storageKey);\n return next;\n}\n\n/**\n * This function makes a theme button. Each click sets the next theme. The text of the button is\n * \"Theme: auto\", \"Theme: light\" or \"Theme: dark\", and its `aria-label` tells the same theme.\n *\n * @remarks Before the first paint, a script in the `head` of the page reads `storageKey` from\n * `localStorage` and sets `data-theme`. Thus a dark page does not show white for a moment. The\n * plugin `siteShell` of the entry `./vite` adds that script.\n */\nexport function setupTheme(button: HTMLButtonElement, storageKey: string): void {\n const show = (theme: Theme): void => {\n button.textContent = `Theme: ${theme}`;\n button.setAttribute(\"aria-label\", `Color theme: ${theme}. Select to change.`);\n };\n show(currentTheme());\n button.addEventListener(\"click\", () => show(nextTheme(storageKey)));\n}\n\n/** The data of a build: `siteShell` writes it, and `showBuild` shows it. */\nexport interface BuildInfo {\n /** The first 7 characters of the commit, or `local` for a build outside CI. */\n readonly sha: string;\n /** The date of the build, as `YYYY-MM-DD`. */\n readonly date: string;\n /** The version of the package. A site without a version does not set it. */\n readonly version?: string | undefined;\n}\n\n/**\n * This function shows the version and the build of the site in an element. The text is \"Version\n * 1.2.3, build abc1234 of 2026-11-03\", and the commit is a link to GitHub. A build with no version\n * starts with \"Build\", and a local build has no link.\n *\n * @param repository - The repository as \"owner/name\".\n */\nexport function showBuild(element: HTMLElement, build: BuildInfo, repository: string): void {\n const commit = build.sha === \"local\" ? \"local\" : h(\"a\", { href: `https://github.com/${repository}/commit/${build.sha}` }, build.sha);\n element.append(build.version === undefined ? \"Build \" : `Version ${build.version}, build `, commit, ` of ${build.date}`);\n}\n\n/**\n * This function copies a text to the clipboard, and gives `true` when the copy is done. It uses\n * the Clipboard API. When that API is not available or refuses, it uses `document.execCommand`.\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n // An insecure page has no Clipboard API, and a browser can refuse the copy. The old command is the fallback.\n }\n try {\n const area = document.createElement(\"textarea\");\n area.value = text;\n area.setAttribute(\"readonly\", \"\");\n area.style.position = \"fixed\";\n area.style.opacity = \"0\";\n document.body.append(area);\n area.select();\n try {\n return document.execCommand(\"copy\");\n } finally {\n area.remove();\n }\n } catch {\n return false;\n }\n}\n\n/** The options of `copyText`. */\nexport interface CopyTextOptions {\n /** The text of the button after a copy. The default is \"Copied\". */\n readonly copied?: string;\n /** The text of the button after a failure. The default is \"Copy failed\". */\n readonly failed?: string;\n /** The time in milliseconds until the button shows its label again. The default is 1600. */\n readonly ms?: number;\n}\n\n/**\n * This function copies a text to the clipboard with `copyToClipboard`. The button tells the result\n * for a short time, then it shows its label again. The function gives the result of the copy.\n */\nexport async function copyText(button: HTMLButtonElement, text: string, options: CopyTextOptions = {}): Promise<boolean> {\n const label = button.textContent;\n const ok = await copyToClipboard(text);\n button.textContent = ok ? (options.copied ?? \"Copied\") : (options.failed ?? \"Copy failed\");\n window.setTimeout(() => {\n button.textContent = label;\n }, options.ms ?? 1600);\n return ok;\n}\n\n/** The arrow keys of a group: `horizontal` (Left and Right), `vertical` (Up and Down) or `both`. */\n/** The arrow keys of a group: left and right, up and down, or the four arrows. */\nexport type RovingAxis = \"horizontal\" | \"vertical\" | \"both\";\n\nconst ROVING_STEPS: Readonly<Record<RovingAxis, Readonly<Record<string, number>>>> = {\n horizontal: { ArrowRight: 1, ArrowLeft: -1 },\n vertical: { ArrowDown: 1, ArrowUp: -1 },\n both: { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 },\n};\n\n/**\n * This function gives the index of the next item after an arrow key, in a group of `count` items. The index\n * wraps at each end. A key that is not an arrow of the axis gives `undefined`, and so does an empty group. An\n * index outside the group goes to the first item on a step forward, and to the last item on a step back.\n */\nexport function rovingIndex(key: string, index: number, count: number, axis: RovingAxis = \"both\"): number | undefined {\n const step = ROVING_STEPS[axis][key];\n if (step === undefined || count <= 0) return undefined;\n if (!Number.isInteger(index) || index < 0 || index >= count) return step > 0 ? 0 : count - 1;\n return (index + step + count) % count;\n}\n\n/** A choice of a `Segmented` control. */\nexport interface Choice<T extends string> {\n /** The value of the choice. */\n readonly value: T;\n /** The text of the button. */\n readonly label: string;\n /** The tooltip and the accessible name of the button. Without it, the button has neither. */\n readonly title?: string;\n}\n\n/**\n * A group of radio buttons with one focus stop. The selected button has `tabIndex` 0, and the others have -1.\n * The arrow keys select the next button, with a wrap at each end, and move the focus to it. The container keeps\n * its own role and label, for example `role=\"radiogroup\"` in the HTML.\n */\nexport class Segmented<T extends string> {\n private readonly buttons: readonly HTMLButtonElement[];\n private readonly choices: readonly Choice<T>[];\n private readonly onChange: (value: T) => void;\n private current: T;\n\n /**\n * This constructor puts one button for each choice into the container, in place of its children. The listener\n * gets each change by a click or a key, and no event for the choice that is already selected.\n */\n constructor(container: HTMLElement, choices: readonly Choice<T>[], current: T, onChange: (value: T) => void, axis: RovingAxis = \"both\") {\n this.choices = choices;\n this.current = current;\n this.onChange = onChange;\n this.buttons = choices.map((choice) => {\n const button = h(\n \"button\",\n { type: \"button\", role: \"radio\", \"data-value\": choice.value, title: choice.title, \"aria-label\": choice.title },\n choice.label,\n );\n button.addEventListener(\"click\", () => this.choose(choice.value, false));\n return button;\n });\n container.replaceChildren(...this.buttons);\n container.addEventListener(\"keydown\", (event) => {\n const index = this.choices.findIndex((c) => c.value === this.current);\n const next = rovingIndex(event.key, index, this.choices.length, axis);\n if (next === undefined) return;\n event.preventDefault();\n this.choose(this.choices[next]!.value, true);\n });\n this.show();\n }\n\n /** The value of the control. */\n get value(): T {\n return this.current;\n }\n\n /** This function sets the value. The listener gets no event. */\n set(value: T): void {\n this.current = value;\n this.show();\n }\n\n private choose(value: T, focus: boolean): void {\n const changed = value !== this.current;\n this.set(value);\n if (focus) this.buttons[this.choices.findIndex((c) => c.value === value)]?.focus();\n if (changed) this.onChange(value);\n }\n\n private show(): void {\n this.choices.forEach((choice, i) => {\n const button = this.buttons[i]!;\n const on = choice.value === this.current;\n button.setAttribute(\"aria-checked\", String(on));\n button.tabIndex = on ? 0 : -1;\n });\n }\n}\n"],"mappings":";;;;;AAkBA,SAAgB,EACd,KACA,QAAkD,CAAC,GACnD,GAAG,UACuB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AAQ,QAAQ,IAAI;GACpE,IAAI,SAAS,KAAA,GAAW;GACxB,MAAM,eAAe;GACrB,KAAK,OAAO,KAAK,QAAQ,KAAK,CAAE,OAAO,IAAI;EAC7C,CAAC;EACD,KAAK,KAAK;CACZ;;CAGA,IAAI,QAAW;EACb,OAAO,KAAK;CACd;;CAGA,IAAI,OAAgB;EAClB,KAAK,UAAU;EACf,KAAK,KAAK;CACZ;CAEQ,OAAO,OAAU,OAAsB;EAC7C,MAAM,UAAU,UAAU,KAAK;EAC/B,KAAK,IAAI,KAAK;EACd,IAAI,OAAO,KAAK,QAAQ,KAAK,QAAQ,WAAW,MAAM,EAAE,UAAU,KAAK,EAAE,EAAE,MAAM;EACjF,IAAI,SAAS,KAAK,SAAS,KAAK;CAClC;CAEQ,OAAa;EACnB,KAAK,QAAQ,SAAS,QAAQ,MAAM;GAClC,MAAM,SAAS,KAAK,QAAQ;GAC5B,MAAM,KAAK,OAAO,UAAU,KAAK;GACjC,OAAO,aAAa,gBAAgB,OAAO,EAAE,CAAC;GAC9C,OAAO,WAAW,KAAK,IAAI;EAC7B,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"chrome.js","names":[],"sources":["../src/chrome.ts"],"sourcesContent":["/// <reference lib=\"dom\" />\n/**\n * The small helpers of a page in the browser: the element helpers, the element lookup, the theme\n * button, the copy button and the build stamp. It also has a radio group with one focus stop,\n * and the state of the offline copy of the site.\n * This module imports no Node.js module, so a site can bundle it. Import it from\n * `@mark1russell7/site-pages/chrome`, because the package root also has Node.js code.\n */\n\n/**\n * The states of the offline copy:\n * - `none`: the browser has no service worker, so the site has no offline copy.\n * - `outside`: the page is outside the scope of the worker, for example the address of the home with no slash at its end.\n * - `saving`: the worker keeps the files. The copy is not complete.\n * - `ready`: an active worker kept each file. The site opens with no network.\n * - `failed`: the browser refused the worker, or the worker did not keep each file.\n */\nexport const OFFLINE_STATES: readonly [\"none\", \"outside\", \"saving\", \"ready\", \"failed\"] = [\"none\", \"outside\", \"saving\", \"ready\", \"failed\"];\n\n/** A state of the offline copy. */\nexport type OfflineState = (typeof OFFLINE_STATES)[number];\n\n/** The event on `window` at each change of the state. Its `detail` is the state. */\nexport const OFFLINE_EVENT = \"site-offline\";\n\n/** The attribute of the root element with the current state, so a style can show it. */\nexport const OFFLINE_ATTRIBUTE = \"data-offline\";\n\n/** A child of `h`: a node or a text. The values `null`, `undefined` and `false` give no child. */\nexport type Child = Node | string | null | undefined | false;\n\n/** The value of an attribute of `h`. The value `true` gives an empty attribute. */\nexport type AttributeValue = string | number | boolean | null | undefined;\n\n/**\n * This function makes an element with attributes and children. An attribute with the value\n * `false`, `null` or `undefined` is not set. The attribute `class` sets the class name.\n */\nexport function h<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n attrs: Readonly<Record<string, AttributeValue>> = {},\n ...children: readonly (Child | readonly Child[])[]\n): HTMLElementTagNameMap[K] {\n const el = document.createElement(tag);\n return fill(el, attrs, children, (value) => {\n el.className = value;\n });\n}\n\n/** The namespace of the SVG elements. */\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\n/**\n * This function makes an SVG element with attributes and children, with the rules of `h`. The\n * attribute `class` sets the attribute `class`, because the class name of an SVG element is\n * read-only.\n */\nexport function svg<K extends keyof SVGElementTagNameMap>(\n tag: K,\n attrs: Readonly<Record<string, AttributeValue>> = {},\n ...children: readonly (Child | readonly Child[])[]\n): SVGElementTagNameMap[K] {\n const el = document.createElementNS(SVG_NS, tag);\n return fill(el, attrs, children, (value) => {\n el.setAttribute(\"class\", value);\n });\n}\n\n/** This function sets the attributes and adds the children of an element of `h` or `svg`. */\nfunction fill<E extends Element>(\n el: E,\n attrs: Readonly<Record<string, AttributeValue>>,\n children: readonly (Child | readonly Child[])[],\n setClass: (value: string) => void,\n): E {\n for (const [name, value] of Object.entries(attrs)) {\n if (value === false || value === null || value === undefined) continue;\n if (name === \"class\") setClass(String(value));\n else el.setAttribute(name, value === true ? \"\" : String(value));\n }\n for (const child of children.flat()) {\n if (child === null || child === undefined || child === false) continue;\n el.append(child);\n }\n return el;\n}\n\n/**\n * This function gives the element with the ID. The page has each ID that the code asks for. Thus\n * a missing ID is an error of the page, and the function throws an `Error`.\n */\nexport function byId<T extends HTMLElement = HTMLElement>(id: string): T {\n const el = document.getElementById(id);\n if (el === null) throw new Error(`The page has no element \"${id}\".`);\n return el as T;\n}\n\n/** The themes of the theme button, in the sequence of the clicks. `auto` follows the setting of the system. */\nexport const THEMES: readonly [\"auto\", \"light\", \"dark\"] = [\"auto\", \"light\", \"dark\"];\n\n/** A theme of the page. */\nexport type Theme = (typeof THEMES)[number];\n\n/**\n * This function gives the theme of the page from the attribute `data-theme` of the `html` element.\n * Without the attribute, or with another value, the theme is `auto`.\n */\nexport function currentTheme(): Theme {\n const theme = document.documentElement.dataset[\"theme\"];\n return theme === \"light\" || theme === \"dark\" ? theme : \"auto\";\n}\n\n/**\n * This function sets the theme of the page, and keeps it in `localStorage` under `storageKey`.\n * The theme `auto` removes the attribute `data-theme` and the stored value.\n */\nexport function applyTheme(theme: Theme, storageKey: string): void {\n const root = document.documentElement;\n if (theme === \"auto\") delete root.dataset[\"theme\"];\n else root.dataset[\"theme\"] = theme;\n try {\n if (theme === \"auto\") localStorage.removeItem(storageKey);\n else localStorage.setItem(storageKey, theme);\n } catch {\n // A browser with no storage keeps the theme until the page closes.\n }\n}\n\n/** This function sets the next theme after the current theme (auto, light, dark, auto), and gives it. */\nexport function nextTheme(storageKey: string): Theme {\n const next = THEMES[(THEMES.indexOf(currentTheme()) + 1) % THEMES.length] ?? \"auto\";\n applyTheme(next, storageKey);\n return next;\n}\n\n/**\n * This function makes a theme button. Each click sets the next theme. The text of the button is\n * \"Theme: auto\", \"Theme: light\" or \"Theme: dark\", and its `aria-label` tells the same theme.\n *\n * @remarks Before the first paint, a script in the `head` of the page reads `storageKey` from\n * `localStorage` and sets `data-theme`. Thus a dark page does not show white for a moment. The\n * plugin `siteShell` of the entry `./vite` adds that script.\n */\nexport function setupTheme(button: HTMLButtonElement, storageKey: string): void {\n const show = (theme: Theme): void => {\n button.textContent = `Theme: ${theme}`;\n button.setAttribute(\"aria-label\", `Color theme: ${theme}. Select to change.`);\n };\n show(currentTheme());\n button.addEventListener(\"click\", () => show(nextTheme(storageKey)));\n}\n\n/** The data of a build: `siteShell` writes it, and `showBuild` shows it. */\nexport interface BuildInfo {\n /** The first 7 characters of the commit, or `local` for a build outside CI. */\n readonly sha: string;\n /** The date of the build, as `YYYY-MM-DD`. */\n readonly date: string;\n /** The version of the package. A site without a version does not set it. */\n readonly version?: string | undefined;\n}\n\n/**\n * This function shows the version and the build of the site in an element. The text is \"Version\n * 1.2.3, build abc1234 of 2026-11-03\", and the commit is a link to GitHub. A build with no version\n * starts with \"Build\", and a local build has no link.\n *\n * @param repository - The repository as \"owner/name\".\n */\nexport function showBuild(element: HTMLElement, build: BuildInfo, repository: string): void {\n const commit = build.sha === \"local\" ? \"local\" : h(\"a\", { href: `https://github.com/${repository}/commit/${build.sha}` }, build.sha);\n element.append(build.version === undefined ? \"Build \" : `Version ${build.version}, build `, commit, ` of ${build.date}`);\n}\n\n/**\n * This function copies a text to the clipboard, and gives `true` when the copy is done. It uses\n * the Clipboard API. When that API is not available or refuses, it uses `document.execCommand`.\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n // An insecure page has no Clipboard API, and a browser can refuse the copy. The old command is the fallback.\n }\n try {\n const area = document.createElement(\"textarea\");\n area.value = text;\n area.setAttribute(\"readonly\", \"\");\n area.style.position = \"fixed\";\n area.style.opacity = \"0\";\n document.body.append(area);\n area.select();\n try {\n return document.execCommand(\"copy\");\n } finally {\n area.remove();\n }\n } catch {\n return false;\n }\n}\n\n/** The options of `copyText`. */\nexport interface CopyTextOptions {\n /** The text of the button after a copy. The default is \"Copied\". */\n readonly copied?: string;\n /** The text of the button after a failure. The default is \"Copy failed\". */\n readonly failed?: string;\n /** The time in milliseconds until the button shows its label again. The default is 1600. */\n readonly ms?: number;\n}\n\n/**\n * This function copies a text to the clipboard with `copyToClipboard`. The button tells the result\n * for a short time, then it shows its label again. The function gives the result of the copy.\n */\nexport async function copyText(button: HTMLButtonElement, text: string, options: CopyTextOptions = {}): Promise<boolean> {\n const label = button.textContent;\n const ok = await copyToClipboard(text);\n button.textContent = ok ? (options.copied ?? \"Copied\") : (options.failed ?? \"Copy failed\");\n window.setTimeout(() => {\n button.textContent = label;\n }, options.ms ?? 1600);\n return ok;\n}\n\n/** The arrow keys of a group: `horizontal` (Left and Right), `vertical` (Up and Down) or `both`. */\n/** The arrow keys of a group: left and right, up and down, or the four arrows. */\nexport type RovingAxis = \"horizontal\" | \"vertical\" | \"both\";\n\nconst ROVING_STEPS: Readonly<Record<RovingAxis, Readonly<Record<string, number>>>> = {\n horizontal: { ArrowRight: 1, ArrowLeft: -1 },\n vertical: { ArrowDown: 1, ArrowUp: -1 },\n both: { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 },\n};\n\n/**\n * This function gives the index of the next item after an arrow key, in a group of `count` items. The index\n * wraps at each end. A key that is not an arrow of the axis gives `undefined`, and so does an empty group. An\n * index outside the group goes to the first item on a step forward, and to the last item on a step back.\n */\nexport function rovingIndex(key: string, index: number, count: number, axis: RovingAxis = \"both\"): number | undefined {\n const step = ROVING_STEPS[axis][key];\n if (step === undefined || count <= 0) return undefined;\n if (!Number.isInteger(index) || index < 0 || index >= count) return step > 0 ? 0 : count - 1;\n return (index + step + count) % count;\n}\n\n/** A choice of a `Segmented` control. */\nexport interface Choice<T extends string> {\n /** The value of the choice. */\n readonly value: T;\n /** The text of the button. */\n readonly label: string;\n /** The tooltip and the accessible name of the button. Without it, the button has neither. */\n readonly title?: string;\n}\n\n/**\n * A group of radio buttons with one focus stop. The selected button has `tabIndex` 0, and the others have -1.\n * The arrow keys select the next button, with a wrap at each end, and move the focus to it. The container keeps\n * its own role and label, for example `role=\"radiogroup\"` in the HTML.\n */\nexport class Segmented<T extends string> {\n private readonly buttons: readonly HTMLButtonElement[];\n private readonly choices: readonly Choice<T>[];\n private readonly onChange: (value: T) => void;\n private current: T;\n\n /**\n * This constructor puts one button for each choice into the container, in place of its children. The listener\n * gets each change by a click or a key, and no event for the choice that is already selected.\n */\n constructor(container: HTMLElement, choices: readonly Choice<T>[], current: T, onChange: (value: T) => void, axis: RovingAxis = \"both\") {\n this.choices = choices;\n this.current = current;\n this.onChange = onChange;\n this.buttons = choices.map((choice) => {\n const button = h(\n \"button\",\n { type: \"button\", role: \"radio\", \"data-value\": choice.value, title: choice.title, \"aria-label\": choice.title },\n choice.label,\n );\n button.addEventListener(\"click\", () => this.choose(choice.value, false));\n return button;\n });\n container.replaceChildren(...this.buttons);\n container.addEventListener(\"keydown\", (event) => {\n const index = this.choices.findIndex((c) => c.value === this.current);\n const next = rovingIndex(event.key, index, this.choices.length, axis);\n if (next === undefined) return;\n event.preventDefault();\n this.choose(this.choices[next]!.value, true);\n });\n this.show();\n }\n\n /** The value of the control. */\n get value(): T {\n return this.current;\n }\n\n /** This function sets the value. The listener gets no event. */\n set(value: T): void {\n this.current = value;\n this.show();\n }\n\n private choose(value: T, focus: boolean): void {\n const changed = value !== this.current;\n this.set(value);\n if (focus) this.buttons[this.choices.findIndex((c) => c.value === value)]?.focus();\n if (changed) this.onChange(value);\n }\n\n private show(): void {\n this.choices.forEach((choice, i) => {\n const button = this.buttons[i]!;\n const on = choice.value === this.current;\n button.setAttribute(\"aria-checked\", String(on));\n button.tabIndex = on ? 0 : -1;\n });\n }\n}\n\n/** This function gives a value as a state of the offline copy, or `undefined` when it is not a state. */\nfunction offlineStateOf(value: unknown): OfflineState | undefined {\n return OFFLINE_STATES.find((state) => state === value);\n}\n\n/**\n * This function calls `listener` with the state of the offline copy of the site, and again at each change.\n * The register script of `siteOffline` tells the state. A page with no register script gets no call.\n * It gives the function that stops the calls.\n */\nexport function watchOffline(listener: (state: OfflineState) => void): () => void {\n const now = offlineStateOf(document.documentElement.getAttribute(OFFLINE_ATTRIBUTE));\n if (now !== undefined) listener(now);\n const changed = (event: Event): void => {\n const state = offlineStateOf((event as CustomEvent<unknown>).detail);\n if (state !== undefined) listener(state);\n };\n addEventListener(OFFLINE_EVENT, changed);\n return () => removeEventListener(OFFLINE_EVENT, changed);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,MAAa,iBAA4E;CAAC;CAAQ;CAAW;CAAU;CAAS;AAAQ;;AAMxI,MAAa,gBAAgB;;AAG7B,MAAa,oBAAoB;;;;;AAYjC,SAAgB,EACd,KACA,QAAkD,CAAC,GACnD,GAAG,UACuB;CAC1B,MAAM,KAAK,SAAS,cAAc,GAAG;CACrC,OAAO,KAAK,IAAI,OAAO,WAAW,UAAU;EAC1C,GAAG,YAAY;CACjB,CAAC;AACH;;AAGA,MAAM,SAAS;;;;;;AAOf,SAAgB,IACd,KACA,QAAkD,CAAC,GACnD,GAAG,UACsB;CACzB,MAAM,KAAK,SAAS,gBAAgB,QAAQ,GAAG;CAC/C,OAAO,KAAK,IAAI,OAAO,WAAW,UAAU;EAC1C,GAAG,aAAa,SAAS,KAAK;CAChC,CAAC;AACH;;AAGA,SAAS,KACP,IACA,OACA,UACA,UACG;CACH,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,KAAK,GAAG;EACjD,IAAI,UAAU,SAAS,UAAU,QAAQ,UAAU,KAAA,GAAW;EAC9D,IAAI,SAAS,SAAS,SAAS,OAAO,KAAK,CAAC;OACvC,GAAG,aAAa,MAAM,UAAU,OAAO,KAAK,OAAO,KAAK,CAAC;CAChE;CACA,KAAK,MAAM,SAAS,SAAS,KAAK,GAAG;EACnC,IAAI,UAAU,QAAQ,UAAU,KAAA,KAAa,UAAU,OAAO;EAC9D,GAAG,OAAO,KAAK;CACjB;CACA,OAAO;AACT;;;;;AAMA,SAAgB,KAA0C,IAAe;CACvE,MAAM,KAAK,SAAS,eAAe,EAAE;CACrC,IAAI,OAAO,MAAM,MAAM,IAAI,MAAM,4BA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AAC;CACnF,IAAI,QAAQ,KAAA,GAAW,SAAS,GAAG;CACnC,MAAM,WAAW,UAAuB;EACtC,MAAM,QAAQ,eAAgB,MAA+B,MAAM;EACnE,IAAI,UAAU,KAAA,GAAW,SAAS,KAAK;CACzC;CACA,iBAAiB,eAAe,OAAO;CACvC,aAAa,oBAAoB,eAAe,OAAO;AACzD"}
@@ -0,0 +1,11 @@
1
+ // src/check/offline-header.ts
2
+ /**
3
+ * The header of the home page that the service worker of the offline shell gives in place of a page that it does not keep.
4
+ * The gate `site-pages check --offline` reads it. Thus a page of the check that the worker does not keep fails.
5
+ *
6
+ * This file is in the folder of the check, because the site-pages action starts the check from a sparse checkout of this folder.
7
+ */
8
+ const FALLBACK_HEADER = "x-site-offline";
9
+ export { FALLBACK_HEADER as t };
10
+
11
+ //# sourceMappingURL=offline-header.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"offline-header.js","names":[],"sources":["../../src/check/offline-header.ts"],"sourcesContent":["/**\n * The header of the home page that the service worker of the offline shell gives in place of a page that it does not keep.\n * The gate `site-pages check --offline` reads it. Thus a page of the check that the worker does not keep fails.\n *\n * This file is in the folder of the check, because the site-pages action starts the check from a sparse checkout of this folder.\n */\nexport const FALLBACK_HEADER = \"x-site-offline\";\n"],"mappings":";;;;;;;AAMA,MAAa,kBAAkB"}
package/build/cli.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { T as safeUrl, b as escapeHtml, m as runFreshnessCli } from "./chunks/freshness.js";
3
3
  import { a as runCli, o as TYPESCRIPT_PROBE, s as probeScript } from "./chunks/build.js";
4
+ import { t as FALLBACK_HEADER } from "./chunks/offline-header.js";
4
5
  import { spawn } from "node:child_process";
5
6
  import { appendFileSync, createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
6
7
  import { delimiter, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
@@ -847,7 +848,10 @@ async function serve(root, base) {
847
848
  if (address === null || typeof address === "string") throw new Error("the server has no port");
848
849
  return {
849
850
  url: `http://127.0.0.1:${address.port}${base.endsWith("/") ? base : `${base}/`}`,
850
- close: () => new Promise((done) => server.close(() => done()))
851
+ close: () => new Promise((done) => {
852
+ server.close(() => done());
853
+ server.closeAllConnections();
854
+ })
851
855
  };
852
856
  }
853
857
  /**
@@ -935,6 +939,7 @@ async function checkSite(options) {
935
939
  if (options.pages.length === 0) throw new Error("no page to check");
936
940
  const probes = pageProbes(options);
937
941
  if (options.out === void 0 && options.url === void 0) throw new Error("give out or url");
942
+ if (options.offline === true && options.out === void 0) throw new Error("the offline check needs out: it stops the server of the folder to cut the network");
938
943
  const server = options.out !== void 0 ? await serve(options.out, options.base ?? "/") : void 0;
939
944
  const views = [];
940
945
  let homeUrl;
@@ -989,7 +994,41 @@ async function checkSite(options) {
989
994
  }
990
995
  }
991
996
  views.push(view);
992
- log(`${view.ok ? "PASS" : "FAIL"}${view.retried ? " (retried)" : ""} ${path} ${width} ${scheme}${view.measure ? ` scrollWidth=${view.measure.scrollWidth} innerWidth=${view.measure.innerWidth}` : ""}${view.probe ? ` probe ${view.probe.filter((c) => c.ok).length}/${view.probe.length}` : ""}${view.problems.length > 0 ? `\n - ${view.problems.join("\n - ")}` : ""}`);
997
+ log(viewLine(view));
998
+ }
999
+ }
1000
+ if (options.offline === true && server !== void 0) {
1001
+ ({page, events} = await restart());
1002
+ const notReady = await offlineReady(page, homeUrl.href, options.timeoutMs);
1003
+ await server.close();
1004
+ await page.send("Network.emulateNetworkConditions", {
1005
+ offline: true,
1006
+ latency: 0,
1007
+ downloadThroughput: -1,
1008
+ uploadThroughput: -1
1009
+ });
1010
+ const width = options.widths[0] ?? 1280;
1011
+ const scheme = options.schemes[0] ?? "light";
1012
+ for (const path of options.pages) {
1013
+ const target = new URL(path.replace(/^\/+/, ""), homeUrl).href;
1014
+ const view = notReady === void 0 ? (await checkView(page, events, {
1015
+ target,
1016
+ path,
1017
+ width,
1018
+ scheme,
1019
+ probe: void 0,
1020
+ options,
1021
+ offline: true
1022
+ })).view : {
1023
+ page: path,
1024
+ width,
1025
+ scheme,
1026
+ ok: false,
1027
+ problems: [notReady],
1028
+ offline: true
1029
+ };
1030
+ views.push(view);
1031
+ log(viewLine(view));
993
1032
  }
994
1033
  }
995
1034
  } finally {
@@ -1008,6 +1047,44 @@ async function checkSite(options) {
1008
1047
  }
1009
1048
  return result;
1010
1049
  }
1050
+ /** This function gives the log line of a view. */
1051
+ function viewLine(view) {
1052
+ const measure = view.measure ? ` scrollWidth=${view.measure.scrollWidth} innerWidth=${view.measure.innerWidth}` : "";
1053
+ const probe = view.probe ? ` probe ${view.probe.filter((c) => c.ok).length}/${view.probe.length}` : "";
1054
+ const problems = view.problems.length > 0 ? `\n - ${view.problems.join("\n - ")}` : "";
1055
+ return `${view.ok ? "PASS" : "FAIL"}${view.retried ? " (retried)" : ""} ${view.page} ${view.width} ${view.scheme}${view.offline ? " offline" : ""}${measure}${probe}${problems}`;
1056
+ }
1057
+ /**
1058
+ * This function gives a page expression that waits until a service worker of the site controls the page. The expression gives an
1059
+ * empty text when a worker controls the page, else the problem.
1060
+ */
1061
+ function offlineReadyExpression(limitMs) {
1062
+ return `(async () => {
1063
+ if (!("serviceWorker" in navigator)) return "the browser has no service worker API";
1064
+ const end = performance.now() + ${String(limitMs)};
1065
+ const later = new Promise((done) => setTimeout(() => done(false), ${String(limitMs)}));
1066
+ const ready = await Promise.race([navigator.serviceWorker.ready.then(() => true), later]);
1067
+ if (!ready) return "no service worker of the site became active in ${String(limitMs)} ms: the site has no offline copy";
1068
+ while (!navigator.serviceWorker.controller && performance.now() < end) await new Promise((done) => setTimeout(done, 50));
1069
+ return navigator.serviceWorker.controller ? "" : "the service worker of the site did not take control of the page in ${String(limitMs)} ms";
1070
+ })()`;
1071
+ }
1072
+ /** This function opens the home page with the network on, and waits for its service worker. It gives the problem, or undefined. */
1073
+ async function offlineReady(page, home, timeoutMs) {
1074
+ try {
1075
+ const loaded = page.once("Page.loadEventFired", timeoutMs);
1076
+ const navigation = await page.send("Page.navigate", { url: home });
1077
+ if (navigation.errorText) {
1078
+ loaded.catch(() => {});
1079
+ return `the home page did not open before the network went off: ${navigation.errorText}`;
1080
+ }
1081
+ await loaded;
1082
+ const problem = await page.evaluate(offlineReadyExpression(timeoutMs));
1083
+ return problem === "" ? void 0 : problem;
1084
+ } catch (error) {
1085
+ return `the check did not see the service worker of the site: ${error instanceof Error ? error.message : String(error)}`;
1086
+ }
1087
+ }
1011
1088
  /**
1012
1089
  * A script that each page starts before its own scripts. A script or a style sheet that does not load fires `error` on its
1013
1090
  * element. This script writes that event as a console error. Thus a module script whose imports do not load is a problem too.
@@ -1023,6 +1100,7 @@ const OTHER_PATHS = `document.querySelector('meta[name="site-check-other-paths"]
1023
1100
  function watch(page, origin) {
1024
1101
  let problems = [];
1025
1102
  let refused = [];
1103
+ let documents = /* @__PURE__ */ new Map();
1026
1104
  const urls = /* @__PURE__ */ new Map();
1027
1105
  const own = (url) => {
1028
1106
  try {
@@ -1047,6 +1125,13 @@ function watch(page, origin) {
1047
1125
  page.on("Network.responseReceived", (params) => {
1048
1126
  const response = params["response"];
1049
1127
  if (response.status >= 400 && own(response.url)) refused.push(response);
1128
+ if (params["type"] === "Document") {
1129
+ const header = Object.entries(response.headers ?? {}).find(([name]) => name.toLowerCase() === FALLBACK_HEADER)?.[1];
1130
+ documents.set(urls.get(String(params["requestId"])) ?? response.url, {
1131
+ fromServiceWorker: response.fromServiceWorker === true,
1132
+ fallback: header === "fallback"
1133
+ });
1134
+ }
1050
1135
  });
1051
1136
  page.on("Network.loadingFailed", (params) => {
1052
1137
  const url = urls.get(String(params["requestId"])) ?? "";
@@ -1056,7 +1141,9 @@ function watch(page, origin) {
1056
1141
  reset: () => {
1057
1142
  problems = [];
1058
1143
  refused = [];
1144
+ documents = /* @__PURE__ */ new Map();
1059
1145
  },
1146
+ document: (url) => documents.get(url),
1060
1147
  problems: (other) => {
1061
1148
  const shown = refused.filter((response) => other?.test(new URL(response.url).pathname) !== true);
1062
1149
  return [.../* @__PURE__ */ new Set([...problems, ...shown.map((response) => `HTTP ${response.status}: ${response.url}`)])];
@@ -1070,7 +1157,8 @@ async function checkView(page, events, input) {
1070
1157
  width,
1071
1158
  scheme,
1072
1159
  ok: false,
1073
- problems: []
1160
+ problems: [],
1161
+ ...input.offline === true ? { offline: true } : {}
1074
1162
  };
1075
1163
  let other;
1076
1164
  let hung = false;
@@ -1108,7 +1196,7 @@ async function checkView(page, events, input) {
1108
1196
  view.problems.push(...cutProblems(measure.cut, width));
1109
1197
  if (measure.text === 0) view.problems.push("the page shows no text");
1110
1198
  if (options.shots) {
1111
- const file = join(options.shots, `${pageSlug(path)}-${width}-${scheme}.png`);
1199
+ const file = join(options.shots, `${pageSlug(path)}-${width}-${scheme}${input.offline === true ? "-offline" : ""}.png`);
1112
1200
  const height = Math.min(Math.max(measure.height, 1), 8e3);
1113
1201
  const shot = await page.send("Page.captureScreenshot", {
1114
1202
  format: "png",
@@ -1134,6 +1222,7 @@ async function checkView(page, events, input) {
1134
1222
  hung = error instanceof NoReplyError;
1135
1223
  view.problems.push(error instanceof Error ? error.message : String(error));
1136
1224
  }
1225
+ if (input.offline === true && view.problems.length === 0) view.problems.push(...offlineProblems(events.document(target)));
1137
1226
  view.problems.push(...events.problems(other));
1138
1227
  view.ok = view.problems.length === 0;
1139
1228
  return {
@@ -1141,6 +1230,13 @@ async function checkView(page, events, input) {
1141
1230
  hung
1142
1231
  };
1143
1232
  }
1233
+ /** This function gives the problems of the answer of a page with the network off. A page with no seen answer is a problem: the check cannot tell. */
1234
+ function offlineProblems(answer) {
1235
+ if (answer === void 0) return ["the check saw no answer of the page, so it cannot tell if the service worker keeps the page"];
1236
+ if (!answer.fromServiceWorker) return ["the service worker did not answer the page"];
1237
+ if (answer.fallback) return ["the service worker does not keep the page: it gave the home page in its place"];
1238
+ return [];
1239
+ }
1144
1240
  /** This function makes a text safe for a cell of a Markdown table. It escapes `\`, `|`, `<` and `>`. It changes each new line to a space. */
1145
1241
  function cell(text) {
1146
1242
  return text.replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\r?\n/g, " ");
@@ -1156,7 +1252,7 @@ function summary(result) {
1156
1252
  "",
1157
1253
  "| Page | Width | Scheme | Result | Problems |",
1158
1254
  "| --- | ---: | --- | --- | --- |",
1159
- ...result.views.map((view) => `| \`${view.page}\` | ${view.width} | ${view.scheme} | ${view.ok ? "pass" : "**fail**"}${view.retried ? " (retried)" : ""}${view.probe ? ` (probe ${view.probe.filter((c) => c.ok).length}/${view.probe.length})` : ""} | ${view.problems.map(cell).join("<br>")} |`),
1255
+ ...result.views.map((view) => `| \`${view.page}\`${view.offline ? " (offline)" : ""} | ${view.width} | ${view.scheme} | ${view.ok ? "pass" : "**fail**"}${view.retried ? " (retried)" : ""}${view.probe ? ` (probe ${view.probe.filter((c) => c.ok).length}/${view.probe.length})` : ""} | ${view.problems.map(cell).join("<br>")} |`),
1160
1256
  ""
1161
1257
  ].join("\n");
1162
1258
  }
@@ -1190,6 +1286,10 @@ Options:
1190
1286
  Playwright, else Chrome or Edge)
1191
1287
  --settle <ms> The wait after the load event (default: 1500)
1192
1288
  --timeout <ms> The time limit of a page load (default: 30000)
1289
+ --offline Also opens each page with the network off, at the first width and scheme.
1290
+ A new browser opens the home page and waits for the service worker of the
1291
+ site. Then the check stops the server. A page fails when the worker does not
1292
+ answer it. It needs --out.
1193
1293
  --help Shows this text
1194
1294
 
1195
1295
  With $GITHUB_STEP_SUMMARY, the check adds its table to the job summary.
@@ -1218,6 +1318,7 @@ async function runCheckCli(argv, io) {
1218
1318
  browser: { type: "string" },
1219
1319
  settle: { type: "string" },
1220
1320
  timeout: { type: "string" },
1321
+ offline: { type: "boolean" },
1221
1322
  help: { type: "boolean" }
1222
1323
  }
1223
1324
  }));
@@ -1238,6 +1339,7 @@ async function runCheckCli(argv, io) {
1238
1339
  const out = text("out");
1239
1340
  const url = text("url");
1240
1341
  if (out === void 0 === (url === void 0)) return usage("give --out or --url, not both");
1342
+ if (values["offline"] === true && out === void 0) return usage("--offline needs --out: the check stops the server of the folder to cut the network");
1241
1343
  const widths = list("widths", "360,400,1280").map(Number);
1242
1344
  if (widths.length === 0 || widths.some((width) => !Number.isInteger(width) || width < 200 || width > 4e3)) return usage("--widths must be whole numbers from 200 to 4000");
1243
1345
  const schemes = list("schemes", "light,dark");
@@ -1313,6 +1415,7 @@ async function runCheckCli(argv, io) {
1313
1415
  browser: text("browser"),
1314
1416
  settleMs,
1315
1417
  timeoutMs,
1418
+ offline: values["offline"] === true,
1316
1419
  log: (line) => io.stdout(`${line}\n`)
1317
1420
  });
1318
1421
  const failed = result.views.filter((view) => !view.ok).length;