@mark1russell7/site-pages 0.8.2 → 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
@@ -721,6 +721,24 @@ The worker answers a request of a kept file from its cache. The path of a folder
721
721
 
722
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
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
+
724
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.
725
743
 
726
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.
@@ -732,7 +750,8 @@ The base of the site must be a path from the root of the origin, for example `/`
732
750
  | `offlineCacheName(base, files)` | Gives the name of the cache from the URLs and the contents of the kept files. |
733
751
  | `serviceWorkerSource({ base, cache, urls })` | Gives the source of the service worker. |
734
752
  | `webManifest(options, base)` | Gives the web manifest. |
735
- | `registerScript(base)` | Gives the script that registers the worker, for a page without the plugin. |
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. |
736
755
 
737
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:
738
757
 
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;CAC1B,MAAM,KAAK,SAAS,cAAc,GAAG;CACrC,OAAO,KAAK,IAAI,OAAO,WAAW,UAAU;EAC1C,GAAG,YAAY;CACjB,CAAC;AACH;;AAGA,MAAM,SAAS;;;;;;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AAK,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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,SAAS,KAAK;CACzC;CACA,iBAAiB,eAAe,OAAO;CACvC,aAAa,oBAAoB,eAAe,OAAO;AACzD"}
@@ -8,6 +8,7 @@
8
8
  *
9
9
  * The worker keeps only the built files. The data of a site goes offline through its own store, not through this module.
10
10
  */
11
+ import { OFFLINE_ATTRIBUTE, OFFLINE_EVENT, OFFLINE_STATES, OfflineState } from "../chrome.js";
11
12
  /**
12
13
  * 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.
13
14
  * The gate `site-pages check --offline` reads it. Thus a page of the check that the worker does not keep fails.
@@ -129,6 +130,10 @@ export declare function webManifest(options: WebManifestOptions, base: string):
129
130
  /**
130
131
  * This function gives the script that registers the service worker, for a `<script type="module">` of a page. A failure
131
132
  * goes to `console.warn`, because a browser with no service worker shows the page as usual.
133
+ *
134
+ * The script also tells the state of the offline copy (`OfflineState`) to the page. It sets the attribute `data-offline`
135
+ * of the root element, and it sends the event `site-offline` on `window` at each change. So a page can show the visitor
136
+ * when the site opens with no network. `watchOffline` of `@mark1russell7/site-pages/chrome` reads the state.
132
137
  */
133
138
  export declare function registerScript(base: string): string;
134
139
  /** The options of `siteOffline`. */
@@ -194,5 +199,5 @@ interface SiteOfflinePlugin {
194
199
  * @throws Error at the start of the build when the base of the site is not a path. Examples are `./` and a URL of another origin.
195
200
  */
196
201
  export declare function siteOffline(options: SiteOfflineOptions): SiteOfflinePlugin;
197
- export type { OfflineFile, OfflineIcon, PrecacheList, PrecacheOptions, ServiceWorkerInput, SiteOfflineConfig, SiteOfflineOptions, SiteOfflinePlugin, SiteOfflineTag, SkippedFile, WebManifest, WebManifestOptions };
202
+ export { OFFLINE_ATTRIBUTE, OFFLINE_EVENT, OFFLINE_STATES, type OfflineFile, type OfflineIcon, type OfflineState, type PrecacheList, type PrecacheOptions, type ServiceWorkerInput, type SiteOfflineConfig, type SiteOfflineOptions, type SiteOfflinePlugin, type SiteOfflineTag, type SkippedFile, type WebManifest, type WebManifestOptions };
198
203
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/check/offline-header.ts","../../src/offline/shell.ts","../../src/offline/plugin.ts"],"mappings":";;;;;;;;;;;;;;;;qBAMa;;qBCOA;;qBAGA;;qBAGA;;UAGI;WACN;WACA;;;UAIM;;WAEN;;WAEA;;WAEA,mBAAmB;;;UAIb;WACN;WACA;;;UAIM;WACN;WACA,kBAAkB;;;wBAIb,YAAY;;;;;;;;wBAiBZ,aAAa,gBAAgB,eAAe,SAAS,kBAAkB;;;;;;wBAmCvE,iBAAiB,cAAc;WAA2B;WAAsB,SAAS;;;wBAYzF,YAAY;;UAKX;;WAEN;;WAEA;;WAEA;;;;;;;;;;;wBAYK,oBAAoB,OAAO;;UAoD1B;;WAEN;;WAEA;;WAEA;WACA;;;UAIM;;WAEN;;WAEA;WACA;;WAEA;;WAEA;WACA,iBAAiB;;;UAIX;WACN;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA,gBAAgB;;;;;;;wBAQX,YAAY,SAAS,oBAAoB,eAAe;;;;;wBAqBxD,eAAe;;UCrOd;;WAEN,UAAU;;WAEV;;WAEA,mBAAmB;;WAEnB,WAAW,MAAM;aAA0B;;;;UAIrC;WACN;WACA;;WAEA;aAAkB;aAAyB;;WAC3C;IAAW,KAAK;;;;KAIf;WACG;WAAsB;aAAkB;aAA0B;;WAAyB;;WAC3F;WAAwB;aAAkB;;WAA2B;WAA2B;;;UAG9F;WACN;WACA;WACA;EACT,eAAe,QAAQ;EACvB,sBAAsB;EACtB;;;;;;;;;;;;;wBAcc,YAAY,SAAS,qBAAqB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/check/offline-header.ts","../../src/offline/shell.ts","../../src/offline/plugin.ts"],"mappings":";;;;;;;;;;;;;;;;;qBAMa;;qBCQA;;qBAGA;;qBAGA;;UAGI;WACN;WACA;;;UAIM;;WAEN;;WAEA;;WAEA,mBAAmB;;;UAIb;WACN;WACA;;;UAIM;WACN;WACA,kBAAkB;;;wBAIb,YAAY;;;;;;;;wBAiBZ,aAAa,gBAAgB,eAAe,SAAS,kBAAkB;;;;;;wBAmCvE,iBAAiB,cAAc;WAA2B;WAAsB,SAAS;;;wBAYzF,YAAY;;UAKX;;WAEN;;WAEA;;WAEA;;;;;;;;;;;wBAYK,oBAAoB,OAAO;;UAoD1B;;WAEN;;WAEA;;WAEA;WACA;;;UAIM;;WAEN;;WAEA;WACA;;WAEA;;WAEA;WACA,iBAAiB;;;UAIX;WACN;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA,gBAAgB;;;;;;;wBAQX,YAAY,SAAS,oBAAoB,eAAe;;;;;;;;;wBAyBxD,eAAe;;UC1Od;;WAEN,UAAU;;WAEV;;WAEA,mBAAmB;;WAEnB,WAAW,MAAM;aAA0B;;;;UAIrC;WACN;WACA;;WAEA;aAAkB;aAAyB;;WAC3C;IAAW,KAAK;;;;KAIf;WACG;WAAsB;aAAkB;aAA0B;;WAAyB;;WAC3F;WAAwB;aAAkB;;WAA2B;WAA2B;;;UAG9F;WACN;WACA;WACA;EACT,eAAe,QAAQ;EACvB,sBAAsB;EACtB;;;;;;;;;;;;;wBAcc,YAAY,SAAS,qBAAqB"}
@@ -1,4 +1,5 @@
1
1
  import { t as FALLBACK_HEADER } from "../chunks/offline-header.js";
2
+ import { OFFLINE_ATTRIBUTE, OFFLINE_EVENT, OFFLINE_STATES } from "../chrome.js";
2
3
  import { readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
3
4
  import { join, relative, resolve, sep } from "node:path";
4
5
  import { createHash } from "node:crypto";
@@ -160,10 +161,39 @@ function webManifest(options, base) {
160
161
  /**
161
162
  * This function gives the script that registers the service worker, for a `<script type="module">` of a page. A failure
162
163
  * goes to `console.warn`, because a browser with no service worker shows the page as usual.
164
+ *
165
+ * The script also tells the state of the offline copy (`OfflineState`) to the page. It sets the attribute `data-offline`
166
+ * of the root element, and it sends the event `site-offline` on `window` at each change. So a page can show the visitor
167
+ * when the site opens with no network. `watchOffline` of `@mark1russell7/site-pages/chrome` reads the state.
163
168
  */
164
169
  function registerScript(base) {
165
170
  const home = offlineBase(base);
166
- return `if ("serviceWorker" in navigator) navigator.serviceWorker.register(${JSON.stringify(home + SERVICE_WORKER_FILE)}, { scope: ${JSON.stringify(home)} }).catch((error) => console.warn("The offline copy of the site is not ready:", error));`;
171
+ return [
172
+ `{`,
173
+ `const home = ${JSON.stringify(home)};`,
174
+ `const root = globalThis.document?.documentElement;`,
175
+ `const tell = (state) => {`,
176
+ ` if (root) root.setAttribute(${JSON.stringify(OFFLINE_ATTRIBUTE)}, state);`,
177
+ ` if (typeof CustomEvent === "function") globalThis.dispatchEvent?.(new CustomEvent(${JSON.stringify(OFFLINE_EVENT)}, { detail: state }));`,
178
+ `};`,
179
+ `if (!("serviceWorker" in navigator)) tell("none");`,
180
+ `else {`,
181
+ ` const outside = !(globalThis.location?.pathname ?? home).startsWith(home);`,
182
+ ` tell(outside ? "outside" : navigator.serviceWorker.controller ? "ready" : "saving");`,
183
+ ` navigator.serviceWorker.register(${JSON.stringify(home + SERVICE_WORKER_FILE)}, { scope: home }).then((registration) => {`,
184
+ ` if (outside || !registration) return;`,
185
+ ` const watch = (worker) => worker?.addEventListener?.("statechange", () => { if (worker.state === "redundant" && !registration.active) tell("failed"); });`,
186
+ ` watch(registration.installing);`,
187
+ ` registration.addEventListener?.("updatefound", () => watch(registration.installing));`,
188
+ ` if (registration.active) tell("ready");`,
189
+ ` else navigator.serviceWorker.ready?.then(() => tell("ready"));`,
190
+ ` }).catch((error) => {`,
191
+ ` if (!outside) tell("failed");`,
192
+ ` console.warn("The offline copy of the site is not ready:", error);`,
193
+ ` });`,
194
+ `}`,
195
+ `}`
196
+ ].join(String.fromCharCode(10));
167
197
  }
168
198
  // src/offline/plugin.ts
169
199
  /**
@@ -249,6 +279,6 @@ function siteOffline(options) {
249
279
  }
250
280
  };
251
281
  }
252
- export { FALLBACK_HEADER, MANIFEST_FILE, MAX_FILE_BYTES, SERVICE_WORKER_FILE, cachePrefix, offlineBase, offlineCacheName, precacheList, registerScript, serviceWorkerSource, siteOffline, webManifest };
282
+ export { FALLBACK_HEADER, MANIFEST_FILE, MAX_FILE_BYTES, OFFLINE_ATTRIBUTE, OFFLINE_EVENT, OFFLINE_STATES, SERVICE_WORKER_FILE, cachePrefix, offlineBase, offlineCacheName, precacheList, registerScript, serviceWorkerSource, siteOffline, webManifest };
253
283
 
254
284
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/offline/shell.ts","../../src/offline/plugin.ts"],"sourcesContent":["/**\n * The parts of the offline shell of a built site, as pure functions. They give the list of the files that the service worker\n * keeps and the name of its cache. They also give the source of the worker, the web manifest and the script that registers the worker.\n *\n * The service worker keeps only the built files. It keeps no data of the site.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { FALLBACK_HEADER } from \"../check/offline-header.ts\";\n\nexport { FALLBACK_HEADER };\n\n/** The file of the service worker, in the root of the built site. */\nexport const SERVICE_WORKER_FILE = \"service-worker.js\";\n\n/** The file of the web manifest, in the root of the built site. */\nexport const MANIFEST_FILE = \"manifest.webmanifest\";\n\n/** The default limit of the size of one kept file: 10 MiB. A larger file stays out of the cache. */\nexport const MAX_FILE_BYTES: number = 10 * 1024 * 1024;\n\n/** One file of the built site: its path from the root of the folder, with `/`, and its size. */\nexport interface OfflineFile {\n readonly path: string;\n readonly bytes: number;\n}\n\n/** The options of `precacheList`. */\nexport interface PrecacheOptions {\n /** The path of the site home, for example `/` or `/client/`. */\n readonly base: string;\n /** The limit of the size of one kept file. The default is `MAX_FILE_BYTES`. */\n readonly maxFileBytes?: number | undefined;\n /** The patterns of the paths that stay out of the cache. A pattern examines the path from the root, for example `media/big.mp4`. */\n readonly exclude?: readonly RegExp[] | undefined;\n}\n\n/** A file that stays out of the cache, and the reason. */\nexport interface SkippedFile {\n readonly path: string;\n readonly reason: string;\n}\n\n/** The result of `precacheList`: the URL paths that the worker keeps, in order, and the files that stay out. */\nexport interface PrecacheList {\n readonly urls: readonly string[];\n readonly skipped: readonly SkippedFile[];\n}\n\n/** This function gives the base with one `/` at the start and one `/` at the end. */\nexport function offlineBase(base: string): string {\n // A loop, not a regular expression: the time of /\\/+$/ grows as the square of the count of \"/\" (CodeQL js/polynomial-redos).\n let start = 0;\n let end = base.length;\n while (start < end && base[start] === \"/\") start += 1;\n while (end > start && base[end - 1] === \"/\") end -= 1;\n const inner = base.slice(start, end);\n return inner === \"\" ? \"/\" : `/${inner}/`;\n}\n\n/**\n * This function gives the list of the files that the service worker keeps. The list has the URL path of each file, in\n * order. These files stay out: a source map, the worker, and a file with a dot at the start of a name in its path.\n * A file larger than the limit and a file that a pattern of `exclude` matches also stay out.\n *\n * @throws RangeError when a path is absolute or goes up a folder, or when the limit is not a positive number\n */\nexport function precacheList(files: readonly OfflineFile[], options: PrecacheOptions): PrecacheList {\n const base = offlineBase(options.base);\n const limit = options.maxFileBytes ?? MAX_FILE_BYTES;\n if (!(limit > 0)) throw new RangeError(\"The limit of the size of a file is not a positive number\");\n const urls: string[] = [];\n const skipped: SkippedFile[] = [];\n for (const file of files) {\n const path = file.path.replaceAll(\"\\\\\", \"/\");\n const parts = path.split(\"/\");\n if (path.startsWith(\"/\") || /^[A-Za-z]:/.test(path) || parts.includes(\"..\")) throw new RangeError(`The path ${path} is not a path in the folder of the site`);\n const reason =\n path === SERVICE_WORKER_FILE\n ? \"the service worker\"\n : path.endsWith(\".map\")\n ? \"a source map\"\n : parts.some((part) => part.startsWith(\".\"))\n ? \"a name that starts with a dot\"\n : file.bytes > limit\n ? `larger than ${limit} bytes`\n : options.exclude?.some((pattern) => pattern.test(path))\n ? \"a pattern of exclude\"\n : undefined;\n if (reason === undefined) urls.push(base + path);\n else skipped.push({ path, reason });\n }\n urls.sort();\n skipped.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n return { urls, skipped };\n}\n\n/**\n * This function gives the name of the cache of a build. The name has a prefix with the base. Then it has the first 16\n * hexadecimal digits of the SHA-256 hash of the kept files. A change of a kept file gives a new name. The worker of the new build then removes the old\n * cache of the same base, and only that cache.\n */\nexport function offlineCacheName(base: string, files: readonly { readonly url: string; readonly content: Uint8Array | string }[]): string {\n const hash = createHash(\"sha256\");\n for (const file of [...files].sort((a, b) => (a.url < b.url ? -1 : a.url > b.url ? 1 : 0))) {\n hash.update(file.url);\n hash.update(\"\\0\");\n hash.update(file.content);\n hash.update(\"\\0\");\n }\n return `${cachePrefix(base)}${hash.digest(\"hex\").slice(0, 16)}`;\n}\n\n/** This function gives the prefix of the names of the caches of a base. The worker removes an old cache only when it has this prefix. */\nexport function cachePrefix(base: string): string {\n return `site-offline ${offlineBase(base)} `;\n}\n\n/** The input of `serviceWorkerSource`. */\nexport interface ServiceWorkerInput {\n /** The path of the site home, for example `/` or `/client/`. */\n readonly base: string;\n /** The name of the cache, from `offlineCacheName`. */\n readonly cache: string;\n /** The URL paths that the worker keeps, from `precacheList`. */\n readonly urls: readonly string[];\n}\n\n/**\n * This function gives the source of the service worker. The worker keeps each URL of the list when it installs. Then it\n * answers a request of a kept URL from the cache. A page of a folder (a path that ends with `/`) is its `index.html`.\n *\n * A navigation to a URL that is not kept goes to the network. With no network, it gets the home page from the cache, with the\n * header `FALLBACK_HEADER`. The worker does not answer other requests, so they go to the network as usual.\n *\n * @throws RangeError when the cache name does not start with the prefix of the base\n */\nexport function serviceWorkerSource(input: ServiceWorkerInput): string {\n const base = offlineBase(input.base);\n const prefix = cachePrefix(base);\n if (!input.cache.startsWith(prefix)) throw new RangeError(`The cache name does not start with \"${prefix}\"`);\n const start = `${base}index.html`;\n return `// The service worker of the offline copy of this site. @mark1russell7/site-pages/offline made it at the build.\nconst CACHE = ${JSON.stringify(input.cache)};\nconst PREFIX = ${JSON.stringify(prefix)};\nconst START = ${JSON.stringify(start)};\nconst URLS = ${JSON.stringify(input.urls)};\nconst KEPT = new Set(URLS);\nconst FALLBACK = ${JSON.stringify(FALLBACK_HEADER)};\n\nfunction keyOf(url) {\n return url.pathname.endsWith(\"/\") ? url.pathname + \"index.html\" : url.pathname;\n}\n\nfunction marked(response) {\n const headers = new Headers(response.headers);\n headers.set(FALLBACK, \"fallback\");\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers });\n}\n\nself.addEventListener(\"install\", (event) => {\n event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(URLS)).then(() => self.skipWaiting()));\n});\n\nself.addEventListener(\"activate\", (event) => {\n event.waitUntil(\n caches\n .keys()\n .then((names) => Promise.all(names.filter((name) => name.startsWith(PREFIX) && name !== CACHE).map((name) => caches.delete(name))))\n .then(() => self.clients.claim()),\n );\n});\n\nself.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method !== \"GET\") return;\n const url = new URL(request.url);\n if (url.origin !== self.location.origin) return;\n const key = keyOf(url);\n if (KEPT.has(key)) {\n event.respondWith(caches.open(CACHE).then((cache) => cache.match(key)).then((kept) => kept || fetch(request)));\n } else if (request.mode === \"navigate\") {\n event.respondWith(fetch(request).catch(() => caches.open(CACHE).then((cache) => cache.match(START)).then((kept) => (kept ? marked(kept) : Response.error()))));\n }\n});\n`;\n}\n\n/** An icon of the web manifest. */\nexport interface OfflineIcon {\n /** The URL of the icon. A path with no `/` at the start is a path from the site home. */\n readonly src: string;\n /** The sizes, for example `192x192`, or `any` for an SVG file. */\n readonly sizes: string;\n /** The media type, for example `image/png` or `image/svg+xml`. */\n readonly type: string;\n readonly purpose?: \"any\" | \"maskable\" | \"monochrome\" | undefined;\n}\n\n/** The options of `webManifest`. */\nexport interface WebManifestOptions {\n /** The name of the app on the screen of the phone. */\n readonly name: string;\n /** The short name, under the icon. The default is the name. */\n readonly shortName?: string | undefined;\n readonly description?: string | undefined;\n /** The color of the bar of the app, a CSS color. */\n readonly themeColor?: string | undefined;\n /** The color of the screen before the first paint, a CSS color. */\n readonly backgroundColor?: string | undefined;\n readonly icons?: readonly OfflineIcon[] | undefined;\n}\n\n/** The web manifest of a site, as a JSON value. */\nexport interface WebManifest {\n readonly name: string;\n readonly short_name: string;\n readonly description?: string;\n readonly start_url: string;\n readonly scope: string;\n readonly display: \"standalone\";\n readonly theme_color?: string;\n readonly background_color?: string;\n readonly icons: readonly OfflineIcon[];\n}\n\n/**\n * This function gives the web manifest of the site: the app starts at the site home, and its scope is the site home.\n *\n * @throws RangeError when the name is empty\n */\nexport function webManifest(options: WebManifestOptions, base: string): WebManifest {\n const home = offlineBase(base);\n if (options.name.trim() === \"\") throw new RangeError(\"The web manifest has no name\");\n const icons = (options.icons ?? []).map((icon) => ({ ...icon, src: /^(\\/|[a-z][a-z0-9+.-]*:)/i.test(icon.src) ? icon.src : home + icon.src }));\n return {\n name: options.name,\n short_name: options.shortName ?? options.name,\n ...(options.description === undefined ? {} : { description: options.description }),\n start_url: home,\n scope: home,\n display: \"standalone\",\n ...(options.themeColor === undefined ? {} : { theme_color: options.themeColor }),\n ...(options.backgroundColor === undefined ? {} : { background_color: options.backgroundColor }),\n icons,\n };\n}\n\n/**\n * This function gives the script that registers the service worker, for a `<script type=\"module\">` of a page. A failure\n * goes to `console.warn`, because a browser with no service worker shows the page as usual.\n */\nexport function registerScript(base: string): string {\n const home = offlineBase(base);\n return `if (\"serviceWorker\" in navigator) navigator.serviceWorker.register(${JSON.stringify(home + SERVICE_WORKER_FILE)}, { scope: ${JSON.stringify(home)} }).catch((error) => console.warn(\"The offline copy of the site is not ready:\", error));`;\n}\n","/**\n * The Vite plugin of the offline shell. After the build, it writes the web manifest and the service worker into the\n * folder of the site. The worker keeps the built files, so the site opens with no network.\n *\n * This module does not import Vite. The types of the plugin are the small part that it uses.\n */\n\nimport { readdirSync, readFileSync, statSync, writeFileSync } from \"node:fs\";\nimport { join, relative, resolve, sep } from \"node:path\";\nimport {\n MANIFEST_FILE,\n offlineBase,\n offlineCacheName,\n precacheList,\n registerScript,\n serviceWorkerSource,\n SERVICE_WORKER_FILE,\n webManifest,\n type PrecacheList,\n type WebManifestOptions,\n} from \"./shell.ts\";\n\n/** The options of `siteOffline`. */\nexport interface SiteOfflineOptions {\n /** The fields of the web manifest. The value `false` writes no manifest and adds no manifest link. */\n readonly manifest: WebManifestOptions | false;\n /** The limit of the size of one kept file. The default is `MAX_FILE_BYTES`. */\n readonly maxFileBytes?: number | undefined;\n /** The patterns of the paths, from the root of the folder, that stay out of the cache. */\n readonly exclude?: readonly RegExp[] | undefined;\n /** This function gets the list of the kept files and of the files that stay out, after each build. */\n readonly onList?: ((list: PrecacheList & { readonly cache: string }) => void) | undefined;\n}\n\n/** The part of the resolved Vite config that `siteOffline` reads. */\nexport interface SiteOfflineConfig {\n readonly root: string;\n readonly base: string;\n /** The build options. With `write: false`, Vite writes no folder, so the plugin writes no file. */\n readonly build: { readonly outDir: string; readonly write?: boolean | undefined };\n readonly logger?: { info(message: string): void } | undefined;\n}\n\n/** A tag that `siteOffline` adds to each HTML page. */\nexport type SiteOfflineTag =\n | { readonly tag: \"link\"; readonly attrs: { readonly rel: \"manifest\"; readonly href: string }; readonly injectTo: \"head\" }\n | { readonly tag: \"script\"; readonly attrs: { readonly type: \"module\" }; readonly children: string; readonly injectTo: \"body\" };\n\n/** The Vite plugin that `siteOffline` gives. */\nexport interface SiteOfflinePlugin {\n readonly name: string;\n readonly apply: \"build\";\n readonly enforce: \"post\";\n configResolved(config: SiteOfflineConfig): void;\n transformIndexHtml(): SiteOfflineTag[];\n closeBundle(): void;\n}\n\n/**\n * This function makes the Vite plugin of the offline shell. The plugin operates only in a build. It does these three operations:\n *\n * - It adds a manifest link and the script that registers the service worker to each HTML page.\n * - It writes `manifest.webmanifest` into the root of the built site.\n * - It writes `service-worker.js` into the root of the built site. The worker keeps each file of the folder, also the files of the public folder and of later plugins.\n *\n * Put the plugin last. A file that a step after the Vite build adds is not in the list of the worker.\n *\n * @throws Error at the start of the build when the base of the site is not a path. Examples are `./` and a URL of another origin.\n */\nexport function siteOffline(options: SiteOfflineOptions): SiteOfflinePlugin {\n let config: SiteOfflineConfig | undefined;\n const base = (): string => offlineBase(config?.base ?? \"/\");\n return {\n name: \"site-pages-offline\",\n apply: \"build\",\n enforce: \"post\",\n configResolved(resolved) {\n if (!resolved.base.startsWith(\"/\")) throw new Error(`The offline shell needs a base that is a path from the root of the origin, not \"${resolved.base}\".`);\n config = resolved;\n },\n transformIndexHtml() {\n const tags: SiteOfflineTag[] = [];\n if (options.manifest !== false) tags.push({ tag: \"link\", attrs: { rel: \"manifest\", href: base() + MANIFEST_FILE }, injectTo: \"head\" });\n tags.push({ tag: \"script\", attrs: { type: \"module\" }, children: registerScript(base()), injectTo: \"body\" });\n return tags;\n },\n closeBundle() {\n if (config === undefined) throw new Error(\"The offline shell has no config: Vite did not call configResolved.\");\n if (config.build.write === false) return;\n const folder = resolve(config.root, config.build.outDir);\n if (options.manifest !== false) writeFileSync(join(folder, MANIFEST_FILE), `${JSON.stringify(webManifest(options.manifest, base()), null, 2)}\\n`);\n const files = readdirSync(folder, { recursive: true, encoding: \"utf8\" })\n .map((name) => join(folder, name))\n .filter((file) => statSync(file).isFile())\n .map((file) => ({ file, path: relative(folder, file).split(sep).join(\"/\"), bytes: statSync(file).size }));\n const list = precacheList(files, { base: base(), maxFileBytes: options.maxFileBytes, exclude: options.exclude });\n const kept = new Set(list.urls);\n const contents = files.filter((file) => kept.has(base() + file.path)).map((file) => ({ url: base() + file.path, content: readFileSync(file.file) }));\n const cache = offlineCacheName(base(), contents);\n writeFileSync(join(folder, SERVICE_WORKER_FILE), serviceWorkerSource({ base: base(), cache, urls: list.urls }));\n config.logger?.info(`site-pages offline: the service worker keeps ${list.urls.length} files, and ${list.skipped.length} files stay out.`);\n options.onList?.({ ...list, cache });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AAaA,MAAa,sBAAsB;;AAGnC,MAAa,gBAAgB;;AAG7B,MAAa,iBAAyB;;AA+BtC,SAAgB,YAAY,MAAsB;CAEhD,IAAI,QAAQ;CACZ,IAAI,MAAM,KAAK;CACf,OA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G,KAAK,UAAU,YAAY,QAAQ,UAAU,KAAK,CAAC,GAAG,MAAM,CAAC,EAAE,GAAG;GAChJ,MAAM,QAAQ,YAAY,QAAQ;IAAE,WAAW;IAAM,UAAU;GAAO,CAAC,CAAC,CACrE,KAAK,SAAS,KAAK,QAAQ,IAAI,CAAC,CAAC,CACjC,QAAQ,SAAS,SAAS,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CACzC,KAAK,UAAU;IAAE;IAAM,MAAM,SAAS,QAAQ,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;IAAG,OAAO,SAAS,IAAI,CAAC,CAAC;GAAK,EAAE;GAC1G,MAAM,OAAO,aAAa,OAAO;IAAE,MAAM,KAAK;IAAG,cAAc,QAAQ;IAAc,SAAS,QAAQ;GAAQ,CAAC;GAC/G,MAAM,OAAO,IAAI,IAAI,KAAK,IAAI;GAC9B,MAAM,WAAW,MAAM,QAAQ,SAAS,KAAK,IAAI,KAAK,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK,UAAU;IAAE,KAAK,KAAK,IAAI,KAAK;IAAM,SAAS,aAAa,KAAK,IAAI;GAAE,EAAE;GACnJ,MAAM,QAAQ,iBAAiB,KAAK,GAAG,QAAQ;GAC/C,cAAc,KAAK,QAAQ,mBAAmB,GAAG,oBAAoB;IAAE,MAAM,KAAK;IAAG;IAAO,MAAM,KAAK;GAAK,CAAC,CAAC;GAC9G,OAAO,QAAQ,KAAK,gDAAgD,KAAK,KAAK,OAAO,cAAc,KAAK,QAAQ,OAAO,iBAAiB;GACxI,QAAQ,SAAS;IAAE,GAAG;IAAM;GAAM,CAAC;EACrC;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/offline/shell.ts","../../src/offline/plugin.ts"],"sourcesContent":["/**\n * The parts of the offline shell of a built site, as pure functions. They give the list of the files that the service worker\n * keeps and the name of its cache. They also give the source of the worker, the web manifest and the script that registers the worker.\n *\n * The service worker keeps only the built files. It keeps no data of the site.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { FALLBACK_HEADER } from \"../check/offline-header.ts\";\nimport { OFFLINE_ATTRIBUTE, OFFLINE_EVENT } from \"../chrome.ts\";\n\nexport { FALLBACK_HEADER };\n\n/** The file of the service worker, in the root of the built site. */\nexport const SERVICE_WORKER_FILE = \"service-worker.js\";\n\n/** The file of the web manifest, in the root of the built site. */\nexport const MANIFEST_FILE = \"manifest.webmanifest\";\n\n/** The default limit of the size of one kept file: 10 MiB. A larger file stays out of the cache. */\nexport const MAX_FILE_BYTES: number = 10 * 1024 * 1024;\n\n/** One file of the built site: its path from the root of the folder, with `/`, and its size. */\nexport interface OfflineFile {\n readonly path: string;\n readonly bytes: number;\n}\n\n/** The options of `precacheList`. */\nexport interface PrecacheOptions {\n /** The path of the site home, for example `/` or `/client/`. */\n readonly base: string;\n /** The limit of the size of one kept file. The default is `MAX_FILE_BYTES`. */\n readonly maxFileBytes?: number | undefined;\n /** The patterns of the paths that stay out of the cache. A pattern examines the path from the root, for example `media/big.mp4`. */\n readonly exclude?: readonly RegExp[] | undefined;\n}\n\n/** A file that stays out of the cache, and the reason. */\nexport interface SkippedFile {\n readonly path: string;\n readonly reason: string;\n}\n\n/** The result of `precacheList`: the URL paths that the worker keeps, in order, and the files that stay out. */\nexport interface PrecacheList {\n readonly urls: readonly string[];\n readonly skipped: readonly SkippedFile[];\n}\n\n/** This function gives the base with one `/` at the start and one `/` at the end. */\nexport function offlineBase(base: string): string {\n // A loop, not a regular expression: the time of /\\/+$/ grows as the square of the count of \"/\" (CodeQL js/polynomial-redos).\n let start = 0;\n let end = base.length;\n while (start < end && base[start] === \"/\") start += 1;\n while (end > start && base[end - 1] === \"/\") end -= 1;\n const inner = base.slice(start, end);\n return inner === \"\" ? \"/\" : `/${inner}/`;\n}\n\n/**\n * This function gives the list of the files that the service worker keeps. The list has the URL path of each file, in\n * order. These files stay out: a source map, the worker, and a file with a dot at the start of a name in its path.\n * A file larger than the limit and a file that a pattern of `exclude` matches also stay out.\n *\n * @throws RangeError when a path is absolute or goes up a folder, or when the limit is not a positive number\n */\nexport function precacheList(files: readonly OfflineFile[], options: PrecacheOptions): PrecacheList {\n const base = offlineBase(options.base);\n const limit = options.maxFileBytes ?? MAX_FILE_BYTES;\n if (!(limit > 0)) throw new RangeError(\"The limit of the size of a file is not a positive number\");\n const urls: string[] = [];\n const skipped: SkippedFile[] = [];\n for (const file of files) {\n const path = file.path.replaceAll(\"\\\\\", \"/\");\n const parts = path.split(\"/\");\n if (path.startsWith(\"/\") || /^[A-Za-z]:/.test(path) || parts.includes(\"..\")) throw new RangeError(`The path ${path} is not a path in the folder of the site`);\n const reason =\n path === SERVICE_WORKER_FILE\n ? \"the service worker\"\n : path.endsWith(\".map\")\n ? \"a source map\"\n : parts.some((part) => part.startsWith(\".\"))\n ? \"a name that starts with a dot\"\n : file.bytes > limit\n ? `larger than ${limit} bytes`\n : options.exclude?.some((pattern) => pattern.test(path))\n ? \"a pattern of exclude\"\n : undefined;\n if (reason === undefined) urls.push(base + path);\n else skipped.push({ path, reason });\n }\n urls.sort();\n skipped.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n return { urls, skipped };\n}\n\n/**\n * This function gives the name of the cache of a build. The name has a prefix with the base. Then it has the first 16\n * hexadecimal digits of the SHA-256 hash of the kept files. A change of a kept file gives a new name. The worker of the new build then removes the old\n * cache of the same base, and only that cache.\n */\nexport function offlineCacheName(base: string, files: readonly { readonly url: string; readonly content: Uint8Array | string }[]): string {\n const hash = createHash(\"sha256\");\n for (const file of [...files].sort((a, b) => (a.url < b.url ? -1 : a.url > b.url ? 1 : 0))) {\n hash.update(file.url);\n hash.update(\"\\0\");\n hash.update(file.content);\n hash.update(\"\\0\");\n }\n return `${cachePrefix(base)}${hash.digest(\"hex\").slice(0, 16)}`;\n}\n\n/** This function gives the prefix of the names of the caches of a base. The worker removes an old cache only when it has this prefix. */\nexport function cachePrefix(base: string): string {\n return `site-offline ${offlineBase(base)} `;\n}\n\n/** The input of `serviceWorkerSource`. */\nexport interface ServiceWorkerInput {\n /** The path of the site home, for example `/` or `/client/`. */\n readonly base: string;\n /** The name of the cache, from `offlineCacheName`. */\n readonly cache: string;\n /** The URL paths that the worker keeps, from `precacheList`. */\n readonly urls: readonly string[];\n}\n\n/**\n * This function gives the source of the service worker. The worker keeps each URL of the list when it installs. Then it\n * answers a request of a kept URL from the cache. A page of a folder (a path that ends with `/`) is its `index.html`.\n *\n * A navigation to a URL that is not kept goes to the network. With no network, it gets the home page from the cache, with the\n * header `FALLBACK_HEADER`. The worker does not answer other requests, so they go to the network as usual.\n *\n * @throws RangeError when the cache name does not start with the prefix of the base\n */\nexport function serviceWorkerSource(input: ServiceWorkerInput): string {\n const base = offlineBase(input.base);\n const prefix = cachePrefix(base);\n if (!input.cache.startsWith(prefix)) throw new RangeError(`The cache name does not start with \"${prefix}\"`);\n const start = `${base}index.html`;\n return `// The service worker of the offline copy of this site. @mark1russell7/site-pages/offline made it at the build.\nconst CACHE = ${JSON.stringify(input.cache)};\nconst PREFIX = ${JSON.stringify(prefix)};\nconst START = ${JSON.stringify(start)};\nconst URLS = ${JSON.stringify(input.urls)};\nconst KEPT = new Set(URLS);\nconst FALLBACK = ${JSON.stringify(FALLBACK_HEADER)};\n\nfunction keyOf(url) {\n return url.pathname.endsWith(\"/\") ? url.pathname + \"index.html\" : url.pathname;\n}\n\nfunction marked(response) {\n const headers = new Headers(response.headers);\n headers.set(FALLBACK, \"fallback\");\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers });\n}\n\nself.addEventListener(\"install\", (event) => {\n event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(URLS)).then(() => self.skipWaiting()));\n});\n\nself.addEventListener(\"activate\", (event) => {\n event.waitUntil(\n caches\n .keys()\n .then((names) => Promise.all(names.filter((name) => name.startsWith(PREFIX) && name !== CACHE).map((name) => caches.delete(name))))\n .then(() => self.clients.claim()),\n );\n});\n\nself.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method !== \"GET\") return;\n const url = new URL(request.url);\n if (url.origin !== self.location.origin) return;\n const key = keyOf(url);\n if (KEPT.has(key)) {\n event.respondWith(caches.open(CACHE).then((cache) => cache.match(key)).then((kept) => kept || fetch(request)));\n } else if (request.mode === \"navigate\") {\n event.respondWith(fetch(request).catch(() => caches.open(CACHE).then((cache) => cache.match(START)).then((kept) => (kept ? marked(kept) : Response.error()))));\n }\n});\n`;\n}\n\n/** An icon of the web manifest. */\nexport interface OfflineIcon {\n /** The URL of the icon. A path with no `/` at the start is a path from the site home. */\n readonly src: string;\n /** The sizes, for example `192x192`, or `any` for an SVG file. */\n readonly sizes: string;\n /** The media type, for example `image/png` or `image/svg+xml`. */\n readonly type: string;\n readonly purpose?: \"any\" | \"maskable\" | \"monochrome\" | undefined;\n}\n\n/** The options of `webManifest`. */\nexport interface WebManifestOptions {\n /** The name of the app on the screen of the phone. */\n readonly name: string;\n /** The short name, under the icon. The default is the name. */\n readonly shortName?: string | undefined;\n readonly description?: string | undefined;\n /** The color of the bar of the app, a CSS color. */\n readonly themeColor?: string | undefined;\n /** The color of the screen before the first paint, a CSS color. */\n readonly backgroundColor?: string | undefined;\n readonly icons?: readonly OfflineIcon[] | undefined;\n}\n\n/** The web manifest of a site, as a JSON value. */\nexport interface WebManifest {\n readonly name: string;\n readonly short_name: string;\n readonly description?: string;\n readonly start_url: string;\n readonly scope: string;\n readonly display: \"standalone\";\n readonly theme_color?: string;\n readonly background_color?: string;\n readonly icons: readonly OfflineIcon[];\n}\n\n/**\n * This function gives the web manifest of the site: the app starts at the site home, and its scope is the site home.\n *\n * @throws RangeError when the name is empty\n */\nexport function webManifest(options: WebManifestOptions, base: string): WebManifest {\n const home = offlineBase(base);\n if (options.name.trim() === \"\") throw new RangeError(\"The web manifest has no name\");\n const icons = (options.icons ?? []).map((icon) => ({ ...icon, src: /^(\\/|[a-z][a-z0-9+.-]*:)/i.test(icon.src) ? icon.src : home + icon.src }));\n return {\n name: options.name,\n short_name: options.shortName ?? options.name,\n ...(options.description === undefined ? {} : { description: options.description }),\n start_url: home,\n scope: home,\n display: \"standalone\",\n ...(options.themeColor === undefined ? {} : { theme_color: options.themeColor }),\n ...(options.backgroundColor === undefined ? {} : { background_color: options.backgroundColor }),\n icons,\n };\n}\n\n/**\n * This function gives the script that registers the service worker, for a `<script type=\"module\">` of a page. A failure\n * goes to `console.warn`, because a browser with no service worker shows the page as usual.\n *\n * The script also tells the state of the offline copy (`OfflineState`) to the page. It sets the attribute `data-offline`\n * of the root element, and it sends the event `site-offline` on `window` at each change. So a page can show the visitor\n * when the site opens with no network. `watchOffline` of `@mark1russell7/site-pages/chrome` reads the state.\n */\nexport function registerScript(base: string): string {\n const home = offlineBase(base);\n return [\n `{`,\n `const home = ${JSON.stringify(home)};`,\n `const root = globalThis.document?.documentElement;`,\n `const tell = (state) => {`,\n ` if (root) root.setAttribute(${JSON.stringify(OFFLINE_ATTRIBUTE)}, state);`,\n ` if (typeof CustomEvent === \"function\") globalThis.dispatchEvent?.(new CustomEvent(${JSON.stringify(OFFLINE_EVENT)}, { detail: state }));`,\n `};`,\n `if (!(\"serviceWorker\" in navigator)) tell(\"none\");`,\n `else {`,\n ` const outside = !(globalThis.location?.pathname ?? home).startsWith(home);`,\n ` tell(outside ? \"outside\" : navigator.serviceWorker.controller ? \"ready\" : \"saving\");`,\n ` navigator.serviceWorker.register(${JSON.stringify(home + SERVICE_WORKER_FILE)}, { scope: home }).then((registration) => {`,\n ` if (outside || !registration) return;`,\n ` const watch = (worker) => worker?.addEventListener?.(\"statechange\", () => { if (worker.state === \"redundant\" && !registration.active) tell(\"failed\"); });`,\n ` watch(registration.installing);`,\n ` registration.addEventListener?.(\"updatefound\", () => watch(registration.installing));`,\n ` if (registration.active) tell(\"ready\");`,\n ` else navigator.serviceWorker.ready?.then(() => tell(\"ready\"));`,\n ` }).catch((error) => {`,\n ` if (!outside) tell(\"failed\");`,\n ` console.warn(\"The offline copy of the site is not ready:\", error);`,\n ` });`,\n `}`,\n `}`,\n ].join(String.fromCharCode(10));\n}\n","/**\n * The Vite plugin of the offline shell. After the build, it writes the web manifest and the service worker into the\n * folder of the site. The worker keeps the built files, so the site opens with no network.\n *\n * This module does not import Vite. The types of the plugin are the small part that it uses.\n */\n\nimport { readdirSync, readFileSync, statSync, writeFileSync } from \"node:fs\";\nimport { join, relative, resolve, sep } from \"node:path\";\nimport {\n MANIFEST_FILE,\n offlineBase,\n offlineCacheName,\n precacheList,\n registerScript,\n serviceWorkerSource,\n SERVICE_WORKER_FILE,\n webManifest,\n type PrecacheList,\n type WebManifestOptions,\n} from \"./shell.ts\";\n\n/** The options of `siteOffline`. */\nexport interface SiteOfflineOptions {\n /** The fields of the web manifest. The value `false` writes no manifest and adds no manifest link. */\n readonly manifest: WebManifestOptions | false;\n /** The limit of the size of one kept file. The default is `MAX_FILE_BYTES`. */\n readonly maxFileBytes?: number | undefined;\n /** The patterns of the paths, from the root of the folder, that stay out of the cache. */\n readonly exclude?: readonly RegExp[] | undefined;\n /** This function gets the list of the kept files and of the files that stay out, after each build. */\n readonly onList?: ((list: PrecacheList & { readonly cache: string }) => void) | undefined;\n}\n\n/** The part of the resolved Vite config that `siteOffline` reads. */\nexport interface SiteOfflineConfig {\n readonly root: string;\n readonly base: string;\n /** The build options. With `write: false`, Vite writes no folder, so the plugin writes no file. */\n readonly build: { readonly outDir: string; readonly write?: boolean | undefined };\n readonly logger?: { info(message: string): void } | undefined;\n}\n\n/** A tag that `siteOffline` adds to each HTML page. */\nexport type SiteOfflineTag =\n | { readonly tag: \"link\"; readonly attrs: { readonly rel: \"manifest\"; readonly href: string }; readonly injectTo: \"head\" }\n | { readonly tag: \"script\"; readonly attrs: { readonly type: \"module\" }; readonly children: string; readonly injectTo: \"body\" };\n\n/** The Vite plugin that `siteOffline` gives. */\nexport interface SiteOfflinePlugin {\n readonly name: string;\n readonly apply: \"build\";\n readonly enforce: \"post\";\n configResolved(config: SiteOfflineConfig): void;\n transformIndexHtml(): SiteOfflineTag[];\n closeBundle(): void;\n}\n\n/**\n * This function makes the Vite plugin of the offline shell. The plugin operates only in a build. It does these three operations:\n *\n * - It adds a manifest link and the script that registers the service worker to each HTML page.\n * - It writes `manifest.webmanifest` into the root of the built site.\n * - It writes `service-worker.js` into the root of the built site. The worker keeps each file of the folder, also the files of the public folder and of later plugins.\n *\n * Put the plugin last. A file that a step after the Vite build adds is not in the list of the worker.\n *\n * @throws Error at the start of the build when the base of the site is not a path. Examples are `./` and a URL of another origin.\n */\nexport function siteOffline(options: SiteOfflineOptions): SiteOfflinePlugin {\n let config: SiteOfflineConfig | undefined;\n const base = (): string => offlineBase(config?.base ?? \"/\");\n return {\n name: \"site-pages-offline\",\n apply: \"build\",\n enforce: \"post\",\n configResolved(resolved) {\n if (!resolved.base.startsWith(\"/\")) throw new Error(`The offline shell needs a base that is a path from the root of the origin, not \"${resolved.base}\".`);\n config = resolved;\n },\n transformIndexHtml() {\n const tags: SiteOfflineTag[] = [];\n if (options.manifest !== false) tags.push({ tag: \"link\", attrs: { rel: \"manifest\", href: base() + MANIFEST_FILE }, injectTo: \"head\" });\n tags.push({ tag: \"script\", attrs: { type: \"module\" }, children: registerScript(base()), injectTo: \"body\" });\n return tags;\n },\n closeBundle() {\n if (config === undefined) throw new Error(\"The offline shell has no config: Vite did not call configResolved.\");\n if (config.build.write === false) return;\n const folder = resolve(config.root, config.build.outDir);\n if (options.manifest !== false) writeFileSync(join(folder, MANIFEST_FILE), `${JSON.stringify(webManifest(options.manifest, base()), null, 2)}\\n`);\n const files = readdirSync(folder, { recursive: true, encoding: \"utf8\" })\n .map((name) => join(folder, name))\n .filter((file) => statSync(file).isFile())\n .map((file) => ({ file, path: relative(folder, file).split(sep).join(\"/\"), bytes: statSync(file).size }));\n const list = precacheList(files, { base: base(), maxFileBytes: options.maxFileBytes, exclude: options.exclude });\n const kept = new Set(list.urls);\n const contents = files.filter((file) => kept.has(base() + file.path)).map((file) => ({ url: base() + file.path, content: readFileSync(file.file) }));\n const cache = offlineCacheName(base(), contents);\n writeFileSync(join(folder, SERVICE_WORKER_FILE), serviceWorkerSource({ base: base(), cache, urls: list.urls }));\n config.logger?.info(`site-pages offline: the service worker keeps ${list.urls.length} files, and ${list.skipped.length} files stay out.`);\n options.onList?.({ ...list, cache });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,MAAa,sBAAsB;;AAGnC,MAAa,gBAAgB;;AAG7B,MAAa,iBAAyB;;AA+BtC,SAAgB,YAAY,MAAsB;CAEhD,IAAI,QAAQ;CACZ,IAAI,MAAM,KAAK;CACf,OAAO,QAAQ,OAAO,KAAK,WAAW,KAAK,SAAS;CACpD,OAAO,MAAM,SAAS,KAAK,MAAM,OAAO,KAAK,OAAO;CACpD,MAAM,QAAQ,KAAK,MAAM,OAAO,GAAG;CACnC,OAAO,UAAU,KAAK,MAAM,IAAI,MAAM;AACxC;;;;;;;;AASA,SAAgB,aAAa,OAA+B,SAAwC;CAClG,MAAM,OAAO,YAAY,QAAQ,IAAI;CACrC,MAAM,QAAQ,QAAQ,gBAAA;CACtB,IAAI,EAAE,QAAQ,IAAI,MAAM,IAAI,WAAW,0DAA0D;CACjG,MAAM,OAAiB,CAAC;CACxB,MAAM,UAAyB,CAAC;CAChC,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,OAAO,KAAK,KAAK,WAAW,MAAM,GAAG;EAC3C,MAAM,QAAQ,KAAK,MAAM,GAAG;EAC5B,IAAI,KAAK,WAAW,GAAG,KAAK,aAAa,KAAK,IAAI,KAAK,MAAM,SAAS,IAAI,GAAG,MAAM,IAAI,WAAW,YAAY,KAAK,yCAAyC;EAC5J,MAAM,SACJ,SAAA,sBACI,uBACA,KAAK,SAAS,MAAM,IAClB,iBACA,MAAM,MAAM,SAAS,KAAK,WAAW,GAAG,CAAC,IACvC,kCACA,KAAK,QAAQ,QACX,eAAe,MAAM,UACrB,QAAQ,SAAS,MAAM,YAAY,QAAQ,KAAK,IAAI,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AAK,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK,UAAU;IAAE,KAAK,KAAK,IAAI,KAAK;IAAM,SAAS,aAAa,KAAK,IAAI;GAAE,EAAE;GACnJ,MAAM,QAAQ,iBAAiB,KAAK,GAAG,QAAQ;GAC/C,cAAc,KAAK,QAAQ,mBAAmB,GAAG,oBAAoB;IAAE,MAAM,KAAK;IAAG;IAAO,MAAM,KAAK;GAAK,CAAC,CAAC;GAC9G,OAAO,QAAQ,KAAK,gDAAgD,KAAK,KAAK,OAAO,cAAc,KAAK,QAAQ,OAAO,iBAAiB;GACxI,QAAQ,SAAS;IAAE,GAAG;IAAM;GAAM,CAAC;EACrC;CACF;AACF"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/site-pages",
4
- "version": "0.8.2",
4
+ "version": "0.8.3",
5
5
  "description": "A release timeline page and a live status page for the site of a GitHub repository: JSON data and standalone HTML, made at deploy time.",
6
6
  "keywords": [
7
7
  "github-pages",