@mark1russell7/site-pages 0.8.2 → 0.8.4

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
@@ -139,7 +139,11 @@ The check runs the probe on the first page, in the first scheme, at each width.
139
139
 
140
140
  To probe other pages, give `--page-probe <page>=<file>` one time for each page, for example `--page-probe /structures/=structures-probe.ts`. A page with no probe has none. The first page takes `--probe` or `--page-probe`, not both. In `checkSite`, the option `probes` is the same map, from a page to the code of its probe.
141
141
 
142
- The folder of `--shots` gets a screenshot of each view, `report.json` and `summary.md`. The exit code is 0 when each view passes, 1 when a view fails, and 2 for an incorrect command line.
142
+ To hold the size of the built files, give `--budget <glob>=<size>` one time for each budget, for example `--budget assets/index-*.js=280kB`. The glob starts at the folder of `--out`. Each file of the glob fails the check when its gzip size is larger than the size. A glob with no file also fails, so a new file name does not escape its budget.
143
+
144
+ The unit of a size is `B`, `kB` or `MB`, and a number with no unit is in kB. The option needs `--out`. The log, `report.json` and `summary.md` give the size of each budget.
145
+
146
+ The folder of `--shots` gets a screenshot of each view, `report.json` and `summary.md`. The exit code is 0 when each view and each budget passes. It is 1 when a view or a budget fails, and 2 for an incorrect command line.
143
147
 
144
148
  The check finds a browser in this order: `--browser`, `$SITE_CHECK_BROWSER`, the newest Chromium of Playwright, and then Chrome or Edge. The folder `src/check` imports only Node.js. Thus Node.js 22.18 or later can start `src/check/main.ts` with no install. The workflow `reusable-pages.yml` of the template uses it this way.
145
149
 
@@ -721,6 +725,24 @@ The worker answers a request of a kept file from its cache. The path of a folder
721
725
 
722
726
  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
727
 
728
+ 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.
729
+
730
+ | State | Meaning |
731
+ | --- | --- |
732
+ | `none` | The browser has no service worker. The site has no offline copy. |
733
+ | `outside` | The page is outside the scope of the worker, for example the home address with no slash at its end. |
734
+ | `saving` | The worker keeps the files. The copy is not complete. |
735
+ | `ready` | An active worker kept each file. The site opens with no network. |
736
+ | `failed` | The browser refused the worker, or the worker did not keep each file. |
737
+
738
+ `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.
739
+
740
+ ```ts
741
+ import { watchOffline } from "@mark1russell7/site-pages/chrome";
742
+
743
+ watchOffline((state) => (byId("offline").textContent = state === "ready" ? "This page opens with no network." : ""));
744
+ ```
745
+
724
746
  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
747
 
726
748
  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 +754,8 @@ The base of the site must be a path from the root of the origin, for example `/`
732
754
  | `offlineCacheName(base, files)` | Gives the name of the cache from the URLs and the contents of the kept files. |
733
755
  | `serviceWorkerSource({ base, cache, urls })` | Gives the source of the service worker. |
734
756
  | `webManifest(options, base)` | Gives the web manifest. |
735
- | `registerScript(base)` | Gives the script that registers the worker, for a page without the plugin. |
757
+ | `registerScript(base)` | Gives the script that registers the worker and tells the state of the copy, for a page without the plugin. |
758
+ | `OFFLINE_STATES`, `OFFLINE_EVENT`, `OFFLINE_ATTRIBUTE` | Give the states of the copy, the name of the event and the name of the attribute. |
736
759
 
737
760
  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
761
 
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,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AEA;;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;;;;;;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,OA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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,UACs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;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;;AAGA,SAAS,eAAe,OAA0C;CAChE,OAAO,eAAe,MAAM,UAAU,UAAU,KAAK;AACvD;;;;;;AAOA,SAAgB,aAAa,UAAqD;CAChF,MAAM,MAAM,eAAe,SAAS,gBAAgB,aAAa,iBAAiB,CAAC;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"}
package/build/cli.js CHANGED
@@ -3,10 +3,11 @@ import { T as safeUrl, b as escapeHtml, m as runFreshnessCli } from "./chunks/fr
3
3
  import { a as runCli, o as TYPESCRIPT_PROBE, s as probeScript } from "./chunks/build.js";
4
4
  import { t as FALLBACK_HEADER } from "./chunks/offline-header.js";
5
5
  import { spawn } from "node:child_process";
6
- import { appendFileSync, createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
6
+ import { appendFileSync, createReadStream, existsSync, globSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
7
7
  import { delimiter, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
8
8
  import { parseArgs } from "node:util";
9
9
  import { homedir, tmpdir } from "node:os";
10
+ import { gzipSync } from "node:zlib";
10
11
  import { createServer } from "node:http";
11
12
  // src/bar/bar.ts
12
13
  /**
@@ -760,6 +761,59 @@ ${code}
760
761
  return __checks;
761
762
  })()`;
762
763
  }
764
+ // src/check/budget.ts
765
+ /**
766
+ * The size budgets of `site-pages check`. A budget is a glob of the files of the built site and a limit of the gzip size of each
767
+ * file. A file over its limit fails the check. A budget with no file fails too, so a new file name does not escape its limit.
768
+ * The code reads the files on disk. It needs no browser.
769
+ */
770
+ /**
771
+ * This function reads a budget of the form `<glob>=<size>`, for example `assets/index-*.js=280kB`. The size is a number with
772
+ * the unit `B`, `kB` (1000 bytes) or `MB` (1000000 bytes). A number with no unit is in kB. A bad entry gives an Error.
773
+ */
774
+ function parseBudget(entry) {
775
+ const split = entry.lastIndexOf("=");
776
+ const pattern = entry.slice(0, split).trim();
777
+ const size = /^(\d+(?:\.\d+)?)\s*(B|kB|MB)?$/.exec(entry.slice(split + 1).trim());
778
+ if (split <= 0 || pattern === "" || size === null) return /* @__PURE__ */ new Error(`--budget must be <glob>=<size>, for example assets/*.js=280kB, not "${entry}"`);
779
+ const unit = size[2] === "B" ? 1 : size[2] === "MB" ? 1e6 : 1e3;
780
+ return {
781
+ pattern: pattern.replace(/\\/g, "/").replace(/^\/+/, ""),
782
+ limit: Math.round(Number(size[1]) * unit)
783
+ };
784
+ }
785
+ /** This function gives a size in bytes as text in kB, with one decimal. */
786
+ function kilobytes(bytes) {
787
+ return `${(bytes / 1e3).toFixed(1)} kB`;
788
+ }
789
+ /** This function measures each file of each budget in the site folder `out`, and gives the result of each budget. */
790
+ function checkBudgets(out, budgets) {
791
+ return budgets.map(({ pattern, limit }) => {
792
+ const files = globSync(pattern, { cwd: out }).map((file) => file.replace(/\\/g, "/")).sort().map((file) => {
793
+ const body = readFileSync(join(out, file));
794
+ return {
795
+ file,
796
+ bytes: body.length,
797
+ gzip: gzipSync(body, { level: 9 }).length
798
+ };
799
+ }).sort((a, b) => b.gzip - a.gzip);
800
+ const problems = files.length === 0 ? [`no file of the site matches the budget ${pattern}`] : files.filter((file) => file.gzip > limit).map((file) => `${file.file} is ${kilobytes(file.gzip)} (gzip), over the budget ${pattern} of ${kilobytes(limit)}`);
801
+ return {
802
+ pattern,
803
+ limit,
804
+ files,
805
+ ok: problems.length === 0,
806
+ problems
807
+ };
808
+ });
809
+ }
810
+ /** This function gives the log line of a budget. */
811
+ function budgetLine(result) {
812
+ const largest = result.files[0];
813
+ const size = largest === void 0 ? "no file" : `${kilobytes(largest.gzip)} (gzip) in ${largest.file}`;
814
+ const problems = result.problems.length > 0 ? `\n - ${result.problems.join("\n - ")}` : "";
815
+ return `${result.ok ? "PASS" : "FAIL"} budget ${result.pattern}: ${size}, the limit is ${kilobytes(result.limit)}, ${result.files.length} file(s)${problems}`;
816
+ }
763
817
  // src/check/serve.ts
764
818
  /**
765
819
  * A static file server for the `check` command. It serves a built site folder at the path of the
@@ -940,6 +994,10 @@ async function checkSite(options) {
940
994
  const probes = pageProbes(options);
941
995
  if (options.out === void 0 && options.url === void 0) throw new Error("give out or url");
942
996
  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");
997
+ const budgetList = options.budgets ?? [];
998
+ if (budgetList.length > 0 && options.out === void 0) throw new Error("a size budget needs out: it reads the files of the folder");
999
+ const budgets = options.out === void 0 || budgetList.length === 0 ? void 0 : checkBudgets(options.out, budgetList);
1000
+ for (const budget of budgets ?? []) log(budgetLine(budget));
943
1001
  const server = options.out !== void 0 ? await serve(options.out, options.base ?? "/") : void 0;
944
1002
  const views = [];
945
1003
  let homeUrl;
@@ -1036,10 +1094,11 @@ async function checkSite(options) {
1036
1094
  await server?.close();
1037
1095
  }
1038
1096
  const result = {
1039
- ok: views.length > 0 && views.every((view) => view.ok),
1097
+ ok: views.length > 0 && views.every((view) => view.ok) && (budgets ?? []).every((budget) => budget.ok),
1040
1098
  url: homeUrl.href,
1041
1099
  browser: executable,
1042
- views
1100
+ views,
1101
+ ...budgets === void 0 ? {} : { budgets }
1043
1102
  };
1044
1103
  if (options.shots) {
1045
1104
  writeFileSync(join(options.shots, "report.json"), `${JSON.stringify(result, null, 2)}\n`);
@@ -1245,7 +1304,7 @@ function cell(text) {
1245
1304
  function summary(result) {
1246
1305
  const failed = result.views.filter((view) => !view.ok);
1247
1306
  const retried = result.views.filter((view) => view.ok && view.retried !== void 0);
1248
- return [
1307
+ const lines = [
1249
1308
  `### Site check: ${result.ok ? "passed" : "failed"}`,
1250
1309
  "",
1251
1310
  `${result.views.length - failed.length} of ${result.views.length} views passed, at ${result.url}.` + (retried.length > 0 ? ` ${retried.length} of them passed only on a second try, after the browser did not answer.` : ""),
@@ -1254,7 +1313,14 @@ function summary(result) {
1254
1313
  "| --- | ---: | --- | --- | --- |",
1255
1314
  ...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>")} |`),
1256
1315
  ""
1257
- ].join("\n");
1316
+ ];
1317
+ if (result.budgets !== void 0 && result.budgets.length > 0) lines.push("| Size budget | Largest file | Gzip | Limit | Result |", "| --- | --- | ---: | ---: | --- |", ...result.budgets.map((budget) => {
1318
+ const largest = budget.files[0];
1319
+ const file = largest === void 0 ? "none" : `\`${cell(largest.file)}\``;
1320
+ const problems = budget.problems.length > 0 ? `<br>${budget.problems.map(cell).join("<br>")}` : "";
1321
+ return `| \`${cell(budget.pattern)}\` | ${file} | ${largest === void 0 ? "" : kilobytes(largest.gzip)} | ${kilobytes(budget.limit)} | ${budget.ok ? "pass" : "**fail**"}${problems} |`;
1322
+ }), "");
1323
+ return lines.join("\n");
1258
1324
  }
1259
1325
  const CHECK_HELP = `Usage: site-pages check (--out <dir> | --url <url>) [options]
1260
1326
 
@@ -1290,6 +1356,11 @@ Options:
1290
1356
  A new browser opens the home page and waits for the service worker of the
1291
1357
  site. Then the check stops the server. A page fails when the worker does not
1292
1358
  answer it. It needs --out.
1359
+ --budget <glob>=<size>
1360
+ A size budget of the files of --out, for example assets/*.js=280kB. A
1361
+ file of the glob fails the check when its gzip size is over the size. A
1362
+ glob with no file fails too. The unit is B, kB or MB (default kB). Give
1363
+ the option one time for each budget. It needs --out.
1293
1364
  --help Shows this text
1294
1365
 
1295
1366
  With $GITHUB_STEP_SUMMARY, the check adds its table to the job summary.
@@ -1319,6 +1390,10 @@ async function runCheckCli(argv, io) {
1319
1390
  settle: { type: "string" },
1320
1391
  timeout: { type: "string" },
1321
1392
  offline: { type: "boolean" },
1393
+ budget: {
1394
+ type: "string",
1395
+ multiple: true
1396
+ },
1322
1397
  help: { type: "boolean" }
1323
1398
  }
1324
1399
  }));
@@ -1340,6 +1415,13 @@ async function runCheckCli(argv, io) {
1340
1415
  const url = text("url");
1341
1416
  if (out === void 0 === (url === void 0)) return usage("give --out or --url, not both");
1342
1417
  if (values["offline"] === true && out === void 0) return usage("--offline needs --out: the check stops the server of the folder to cut the network");
1418
+ const budgets = [];
1419
+ for (const entry of values["budget"] ?? []) {
1420
+ const budget = parseBudget(entry);
1421
+ if (budget instanceof Error) return usage(budget.message);
1422
+ budgets.push(budget);
1423
+ }
1424
+ if (budgets.length > 0 && out === void 0) return usage("--budget needs --out: the check reads the files of the folder");
1343
1425
  const widths = list("widths", "360,400,1280").map(Number);
1344
1426
  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");
1345
1427
  const schemes = list("schemes", "light,dark");
@@ -1416,10 +1498,13 @@ async function runCheckCli(argv, io) {
1416
1498
  settleMs,
1417
1499
  timeoutMs,
1418
1500
  offline: values["offline"] === true,
1501
+ budgets,
1419
1502
  log: (line) => io.stdout(`${line}\n`)
1420
1503
  });
1421
1504
  const failed = result.views.filter((view) => !view.ok).length;
1422
- io.stdout(`site-pages check: ${result.views.length - failed} of ${result.views.length} views passed (${result.browser}).\n`);
1505
+ const overBudget = (result.budgets ?? []).filter((budget) => !budget.ok).length;
1506
+ const budgetText = overBudget > 0 ? ` ${overBudget} size budget(s) failed.` : "";
1507
+ io.stdout(`site-pages check: ${result.views.length - failed} of ${result.views.length} views passed (${result.browser}).${budgetText}\n`);
1423
1508
  const step = io.env["GITHUB_STEP_SUMMARY"];
1424
1509
  if (step) appendFileSync(step, summary(result));
1425
1510
  return result.ok ? 0 : 1;