extension-stale-check 0.0.0-stage → 0.1.0

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.
Files changed (87) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE +21 -0
  3. package/README.md +162 -2
  4. package/dist/cli/bin.d.ts +2 -0
  5. package/dist/cli/bin.js +6 -0
  6. package/dist/cli/helpText.d.ts +2 -0
  7. package/dist/cli/helpText.js +25 -0
  8. package/dist/cli/parseCliArguments.d.ts +8 -0
  9. package/dist/cli/parseCliArguments.js +67 -0
  10. package/dist/cli/runCli.d.ts +9 -0
  11. package/dist/cli/runCli.js +61 -0
  12. package/dist/cli/types.d.ts +30 -0
  13. package/dist/cli/types.js +1 -0
  14. package/dist/cli/version.d.ts +2 -0
  15. package/dist/cli/version.js +3 -0
  16. package/dist/errors/StaleExtensionError.d.ts +12 -0
  17. package/dist/errors/StaleExtensionError.js +15 -0
  18. package/dist/hash/computeBuildHash.d.ts +23 -0
  19. package/dist/hash/computeBuildHash.js +25 -0
  20. package/dist/hash/listFiles.d.ts +7 -0
  21. package/dist/hash/listFiles.js +16 -0
  22. package/dist/index.d.ts +15 -0
  23. package/dist/index.js +9 -0
  24. package/dist/manifest/collectDifferences.d.ts +15 -0
  25. package/dist/manifest/collectDifferences.js +35 -0
  26. package/dist/manifest/diffManifests.d.ts +16 -0
  27. package/dist/manifest/diffManifests.js +15 -0
  28. package/dist/manifest/isLocalePlaceholder.d.ts +8 -0
  29. package/dist/manifest/isLocalePlaceholder.js +8 -0
  30. package/dist/manifest/isPlainObject.d.ts +8 -0
  31. package/dist/manifest/isPlainObject.js +7 -0
  32. package/dist/manifest/readDiskManifest.d.ts +9 -0
  33. package/dist/manifest/readDiskManifest.js +24 -0
  34. package/dist/manifest/readVersion.d.ts +8 -0
  35. package/dist/manifest/readVersion.js +7 -0
  36. package/dist/playwright/createExtensionTest.d.ts +42 -0
  37. package/dist/playwright/createExtensionTest.js +61 -0
  38. package/dist/playwright/index.d.ts +7 -0
  39. package/dist/playwright/index.js +5 -0
  40. package/dist/playwright/launchExtension.d.ts +50 -0
  41. package/dist/playwright/launchExtension.js +49 -0
  42. package/dist/playwright/startBrowser.d.ts +22 -0
  43. package/dist/playwright/startBrowser.js +36 -0
  44. package/dist/profile/browserFolders.d.ts +10 -0
  45. package/dist/profile/browserFolders.js +26 -0
  46. package/dist/profile/canonicalPath.d.ts +7 -0
  47. package/dist/profile/canonicalPath.js +16 -0
  48. package/dist/profile/checkProfileFreshness.d.ts +26 -0
  49. package/dist/profile/checkProfileFreshness.js +69 -0
  50. package/dist/profile/compareSets.d.ts +10 -0
  51. package/dist/profile/compareSets.js +11 -0
  52. package/dist/profile/findExtensionEntry.d.ts +17 -0
  53. package/dist/profile/findExtensionEntry.js +21 -0
  54. package/dist/profile/findNewerFiles.d.ts +9 -0
  55. package/dist/profile/findNewerFiles.js +20 -0
  56. package/dist/profile/isHostPattern.d.ts +8 -0
  57. package/dist/profile/isHostPattern.js +8 -0
  58. package/dist/profile/permissionDifferences.d.ts +14 -0
  59. package/dist/profile/permissionDifferences.js +30 -0
  60. package/dist/profile/readExtensionSettings.d.ts +13 -0
  61. package/dist/profile/readExtensionSettings.js +40 -0
  62. package/dist/profile/resolveUserDataDir.d.ts +20 -0
  63. package/dist/profile/resolveUserDataDir.js +23 -0
  64. package/dist/profile/samePath.d.ts +9 -0
  65. package/dist/profile/samePath.js +14 -0
  66. package/dist/profile/toSortedStrings.d.ts +7 -0
  67. package/dist/profile/toSortedStrings.js +9 -0
  68. package/dist/profile/webkitTimeToDate.d.ts +7 -0
  69. package/dist/profile/webkitTimeToDate.js +22 -0
  70. package/dist/report/formatProfileMessage.d.ts +8 -0
  71. package/dist/report/formatProfileMessage.js +24 -0
  72. package/dist/report/formatProfileReport.d.ts +8 -0
  73. package/dist/report/formatProfileReport.js +24 -0
  74. package/dist/report/formatRuntimeMessage.d.ts +11 -0
  75. package/dist/report/formatRuntimeMessage.js +19 -0
  76. package/dist/runtime/assertExtensionFresh.d.ts +11 -0
  77. package/dist/runtime/assertExtensionFresh.js +16 -0
  78. package/dist/runtime/checkRuntimeFreshness.d.ts +17 -0
  79. package/dist/runtime/checkRuntimeFreshness.js +33 -0
  80. package/dist/runtime/chromeAddedPaths.d.ts +6 -0
  81. package/dist/runtime/chromeAddedPaths.js +6 -0
  82. package/dist/runtime/readLoadedManifest.d.ts +13 -0
  83. package/dist/runtime/readLoadedManifest.js +23 -0
  84. package/dist/types.d.ts +62 -0
  85. package/dist/types.js +1 -0
  86. package/docs/how-it-works.md +92 -0
  87. package/package.json +105 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,23 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project follows
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [0.1.0] - 2026-11-24
8
+
9
+ ### Added
10
+
11
+ - Runtime check: `checkRuntimeFreshness` and `assertExtensionFresh` compare the manifest a running
12
+ extension holds (`chrome.runtime.getManifest()`) with `dist/manifest.json`, and report every
13
+ difference by path. `StaleExtensionError` carries the report.
14
+ - `createExtensionTest` (`extension-stale-check/playwright`): a Playwright `test` with the extension
15
+ loaded in headless Chromium and a stale check before every test. `onStale: "restart"` relaunches the
16
+ browser on the same profile instead of failing.
17
+ - `launchExtension` with `restart()` and `close()`.
18
+ - Profile check: `checkProfileFreshness` and the `extension-stale-check` command read a real Chrome,
19
+ Chromium, Brave or Edge profile and report `fresh`, `possibly-stale`, `stale` or `not-loaded`.
20
+ - `computeBuildHash` and `extension-stale-check hash`: a SHA-256 over every file in `dist/`.
21
+ - `diffManifests`, `readDiskManifest`, `resolveUserDataDir`.
22
+
23
+ [0.1.0]: https://github.com/Vaporjawn/extension-stale-check/releases/tag/v0.1.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Victor Williams
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,163 @@
1
- # Temporary Holding Version
1
+ # extension-stale-check
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/extension-stale-check.svg)](https://www.npmjs.com/package/extension-stale-check)
4
+ [![CI](https://github.com/Vaporjawn/extension-stale-check/actions/workflows/ci.yml/badge.svg)](https://github.com/Vaporjawn/extension-stale-check/actions/workflows/ci.yml)
5
+ [![license](https://img.shields.io/npm/l/extension-stale-check.svg)](LICENSE)
6
+
7
+ **Is the extension your browser is running the one in `dist/`?**
8
+
9
+ A Chrome extension is parsed once, when it loads. Rebuild it, and the browser keeps running the old
10
+ manifest, with the old version and the old permissions, until something reloads it. Files such as
11
+ content scripts are re-read, so the extension runs a mix of old and new, and the popup (read fresh from
12
+ disk) looks current while the service worker is not. Tests then pass or fail against code that is not
13
+ the code you just built.
14
+
15
+ `extension-stale-check` compares what the browser loaded with what is on disk, and says so when they
16
+ differ. It works in two places:
17
+
18
+ | | **Playwright run** | **Your real browser** |
19
+ | --------- | --------------------------------------------------- | -------------------------------------------------------------------------------------------- |
20
+ | Reads | `chrome.runtime.getManifest()` from the live worker | The profile's `Preferences` files |
21
+ | Tells you | Exactly which manifest fields differ | Version, permissions and content-script hosts that differ; files changed since the last load |
22
+ | Use it as | A Playwright fixture, or `checkRuntimeFreshness()` | The `extension-stale-check` command |
23
+
24
+ > Node.js `^20.19.0 || ^22.13.0 || >=24`. Playwright is optional and only needed for the first column.
25
+
26
+ ## Install
27
+
28
+ ```sh
29
+ npm install --save-dev extension-stale-check
30
+ # for the Playwright features:
31
+ npm install --save-dev @playwright/test
32
+ npx playwright install chromium
33
+ ```
34
+
35
+ ## In Playwright tests
36
+
37
+ ```ts
38
+ // e2e/extension.spec.ts
39
+ import path from "node:path";
40
+ import { createExtensionTest } from "extension-stale-check/playwright";
41
+
42
+ const test = createExtensionTest({ dist: path.resolve("dist") });
43
+ const { expect } = test;
44
+
45
+ test("the popup opens", async ({ context, extensionId, page }) => {
46
+ await page.goto(`chrome-extension://${extensionId}/popup.html`);
47
+ await expect(page.locator("h1")).toBeVisible();
48
+ });
49
+ ```
50
+
51
+ `createExtensionTest` starts one headless Chromium per worker with your extension loaded, hands every
52
+ test the usual `context` and `page`, and **before each test** compares the manifest the browser holds
53
+ with `dist/manifest.json`. If a rebuild changed it, the test fails with:
54
+
55
+ ```
56
+ Extension is stale, reload needed: the browser is running version 1.4.0 but dist/ has 1.4.1.
57
+ 2 manifest fields differ: permissions[2], version.
58
+ ```
59
+
60
+ Or restart the browser and carry on:
61
+
62
+ ```ts
63
+ const test = createExtensionTest({ dist: "dist", onStale: "restart" });
64
+ ```
65
+
66
+ | Option | Default | Meaning |
67
+ | ----------------- | -------------- | -------------------------------------------------------------------------------- |
68
+ | `dist` | required | The built extension folder. |
69
+ | `onStale` | `"fail"` | `"fail"` stops the test; `"restart"` relaunches the browser on the same profile. |
70
+ | `ignorePaths` | `[]` | Manifest paths to skip, e.g. `["key"]`. |
71
+ | `headless` | `true` | Extensions load in Chromium's new headless mode. |
72
+ | `channel` | `"chromium"` | Playwright channel. The headless shell cannot load extensions. |
73
+ | `executablePath` | `$CHROME_PATH` | A specific Chromium or Chrome for Testing binary. |
74
+ | `userDataDir` | temp folder | Profile folder. A temporary one is removed when the run ends. |
75
+ | `args`, `timeout` | | Extra browser flags; how long to wait for the service worker (15 s). |
76
+
77
+ Fixtures it adds: `extensionId`, `serviceWorker`, and `freshness` (`{ report, restarted }`).
78
+
79
+ ### Without the fixture
80
+
81
+ Every piece works on its own, with any browser automation that can `evaluate` in the extension's
82
+ service worker:
83
+
84
+ ```ts
85
+ import { checkRuntimeFreshness, assertExtensionFresh } from "extension-stale-check";
86
+
87
+ const report = await checkRuntimeFreshness({ target: serviceWorker, dist: "dist" });
88
+ // { status: "stale", loadedVersion: "1.4.0", diskVersion: "1.4.1", differences: [...], diskHash, message }
89
+
90
+ await assertExtensionFresh({ target: serviceWorker, dist: "dist" }); // throws StaleExtensionError
91
+ ```
92
+
93
+ `target` is anything with `evaluate(fn)`: a Playwright `Worker`, or a `Page` open on a
94
+ `chrome-extension://` URL.
95
+
96
+ ## In your real browser
97
+
98
+ ```sh
99
+ npx extension-stale-check dist
100
+ ```
101
+
102
+ ```
103
+ Stale, reload needed: the browser's record of extension demeknbliimndeeiapmoagalkabkmhfp (last loaded 2026-11-25T00:30:18.052Z) differs from dist/ in permissions.
104
+ extension id: demeknbliimndeeiapmoagalkabkmhfp
105
+ profile: ~/Library/Application Support/Google/Chrome/Default
106
+ last loaded: 2026-11-25T00:30:18.052Z
107
+ dist version: 0.0.2
108
+ worker version: 0.0.1
109
+ differs: version: browser "0.0.1", dist "0.0.2"
110
+ ```
111
+
112
+ The folder is the one `chrome://extensions` shows under "Loaded from". A profile does not cache the
113
+ manifest, so this mode judges from what Chrome does record: when the extension last loaded, the
114
+ version its service worker registered with, and the permissions in force.
115
+
116
+ | Status | Meaning | Exit |
117
+ | ---------------- | -------------------------------------------------------------------------------- | ----------------------- |
118
+ | `fresh` | The profile agrees with `dist/` and no file is newer than the last load. | 0 |
119
+ | `possibly-stale` | Version and permissions match, but files in `dist/` changed after the last load. | 0, or 1 with `--strict` |
120
+ | `stale` | Version, permissions or content-script hosts differ from `dist/manifest.json`. | 1 |
121
+ | `not-loaded` | The profile has no extension loaded from that folder (or a usage or read error). | 2 |
122
+
123
+ ```
124
+ extension-stale-check [check] <dist> [--browser chrome|chromium|brave|edge]
125
+ [--user-data-dir <dir>] [--profile <name>] [--tolerance-ms <n>]
126
+ [--strict] [--json]
127
+ extension-stale-check hash <dist> [--json]
128
+ ```
129
+
130
+ `--json` prints the full report. `hash` prints a SHA-256 of every file in `dist/`, so a report can be
131
+ tied to one build. Use `--tolerance-ms` so a build that finishes a moment after the reload does not
132
+ count as newer.
133
+
134
+ The same check is available as a function: `checkProfileFreshness({ dist, browser, userDataDir, profile })`.
135
+
136
+ ## Good to know
137
+
138
+ - **A runtime check sees the manifest, not your scripts.** Chrome re-reads content scripts and popup
139
+ files from disk, so editing one does not make the loaded manifest differ. The check catches what
140
+ Chrome fixes at load time: `version`, `permissions`, `host_permissions`, `content_scripts` matches,
141
+ the service-worker path, and the rest of the manifest.
142
+ - **Chrome adds `current_locale` to `getManifest()`** for extensions with a `default_locale`. It is
143
+ ignored by default, as are `__MSG_name__` placeholders that Chrome translates on load.
144
+ - **Why `restart` and not `chrome.runtime.reload()`.** In a browser started with `--load-extension`,
145
+ `chrome.runtime.reload()` unloads the extension and does not bring it back (checked on Chromium 159
146
+ headless: the content script stopped running and the extension URL was blocked). `restart` closes
147
+ the browser and starts it again on the same profile, which does load the new build.
148
+ - **The profile mode can lag.** Chrome writes `Preferences` a few seconds after a change and when it
149
+ exits, so a result can trail what the browser is doing right now. Profile mode only compares fields it
150
+ can find in the profile; it cannot see edits to files the manifest does not describe, which is why
151
+ those show up as `possibly-stale` through file times.
152
+ - **Permission strings compared as sets.** If a Chrome version rewrites a host pattern when it records
153
+ it, profile mode could report a difference that is not real. Use `--json` to see exactly what it compared.
154
+
155
+ More detail on how each mode decides is in [docs/how-it-works.md](docs/how-it-works.md).
156
+
157
+ ## Contributing
158
+
159
+ See [CONTRIBUTING.md](CONTRIBUTING.md). Changes are listed in [CHANGELOG.md](CHANGELOG.md).
160
+
161
+ ## License
162
+
163
+ [MIT](LICENSE) © Victor Williams
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from "./runCli.js";
3
+ process.exitCode = await runCli(process.argv.slice(2), {
4
+ out: (text) => process.stdout.write(text),
5
+ err: (text) => process.stderr.write(text),
6
+ });
@@ -0,0 +1,2 @@
1
+ /** The text `extension-stale-check --help` prints. */
2
+ export declare const HELP_TEXT = "extension-stale-check: is the extension your browser runs the one in dist/?\n\nUsage\n extension-stale-check [check] <dist> [options] Read a real browser profile and compare it with dist/\n extension-stale-check hash <dist> [--json] Print a SHA-256 of every file in dist/\n\nOptions for check\n --browser <name> chrome (default), chromium, brave or edge\n --user-data-dir <dir> Browser user-data folder (default: the browser's standard location)\n --profile <name> Profile folder inside it (default: Default)\n --tolerance-ms <n> Ignore files modified within n ms after the load (default: 0)\n --strict Treat \"possibly stale\" as a failure too\n --json Print the report as JSON\n\n -h, --help Show this help\n -v, --version Show the version\n\nExit codes\n 0 fresh (or possibly stale, without --strict)\n 1 stale (or possibly stale, with --strict)\n 2 not loaded in that profile, or a usage or read error\n\nTo compare a running extension in a Playwright run, use the library; see the README.\n";
@@ -0,0 +1,25 @@
1
+ /** The text `extension-stale-check --help` prints. */
2
+ export const HELP_TEXT = `extension-stale-check: is the extension your browser runs the one in dist/?
3
+
4
+ Usage
5
+ extension-stale-check [check] <dist> [options] Read a real browser profile and compare it with dist/
6
+ extension-stale-check hash <dist> [--json] Print a SHA-256 of every file in dist/
7
+
8
+ Options for check
9
+ --browser <name> chrome (default), chromium, brave or edge
10
+ --user-data-dir <dir> Browser user-data folder (default: the browser's standard location)
11
+ --profile <name> Profile folder inside it (default: Default)
12
+ --tolerance-ms <n> Ignore files modified within n ms after the load (default: 0)
13
+ --strict Treat "possibly stale" as a failure too
14
+ --json Print the report as JSON
15
+
16
+ -h, --help Show this help
17
+ -v, --version Show the version
18
+
19
+ Exit codes
20
+ 0 fresh (or possibly stale, without --strict)
21
+ 1 stale (or possibly stale, with --strict)
22
+ 2 not loaded in that profile, or a usage or read error
23
+
24
+ To compare a running extension in a Playwright run, use the library; see the README.
25
+ `;
@@ -0,0 +1,8 @@
1
+ import type { CliCommand } from "./types.js";
2
+ /**
3
+ * Turns command-line arguments into a command.
4
+ *
5
+ * @param argv - The arguments after the program name.
6
+ * @returns The command to run, or `{ kind: "error" }` with a message when the arguments are wrong.
7
+ */
8
+ export declare const parseCliArguments: (argv: readonly string[]) => CliCommand;
@@ -0,0 +1,67 @@
1
+ import { parseArgs } from "node:util";
2
+ const BROWSERS = ["chrome", "chromium", "brave", "edge"];
3
+ /**
4
+ * Turns command-line arguments into a command.
5
+ *
6
+ * @param argv - The arguments after the program name.
7
+ * @returns The command to run, or `{ kind: "error" }` with a message when the arguments are wrong.
8
+ */
9
+ export const parseCliArguments = (argv) => {
10
+ let parsed;
11
+ try {
12
+ parsed = parseArgs({
13
+ args: [...argv],
14
+ allowPositionals: true,
15
+ options: {
16
+ browser: { type: "string" },
17
+ "user-data-dir": { type: "string" },
18
+ profile: { type: "string" },
19
+ "tolerance-ms": { type: "string" },
20
+ strict: { type: "boolean", default: false },
21
+ json: { type: "boolean", default: false },
22
+ help: { type: "boolean", short: "h", default: false },
23
+ version: { type: "boolean", short: "v", default: false },
24
+ },
25
+ });
26
+ }
27
+ catch (error) {
28
+ return { kind: "error", message: error instanceof Error ? error.message : String(error) };
29
+ }
30
+ const { values, positionals } = parsed;
31
+ if (values.help)
32
+ return { kind: "help" };
33
+ if (values.version)
34
+ return { kind: "version" };
35
+ const [first, ...rest] = positionals;
36
+ const isSubcommand = first === "check" || first === "hash";
37
+ const dist = isSubcommand ? rest[0] : first;
38
+ const extra = isSubcommand ? rest.slice(1) : rest;
39
+ if (!dist)
40
+ return { kind: "error", message: "Missing <dist>: the folder the extension is loaded from." };
41
+ if (extra.length > 0)
42
+ return { kind: "error", message: `Unexpected argument: ${extra[0] ?? ""}` };
43
+ if (first === "hash")
44
+ return { kind: "hash", dist, json: values.json };
45
+ const browser = values.browser;
46
+ if (browser !== undefined && !BROWSERS.includes(browser)) {
47
+ return { kind: "error", message: `--browser must be one of ${BROWSERS.join(", ")}.` };
48
+ }
49
+ const tolerance = values["tolerance-ms"];
50
+ const toleranceMs = tolerance === undefined ? undefined : Number(tolerance);
51
+ if (toleranceMs !== undefined && (!Number.isFinite(toleranceMs) || toleranceMs < 0)) {
52
+ return {
53
+ kind: "error",
54
+ message: "--tolerance-ms must be a number of milliseconds, 0 or more.",
55
+ };
56
+ }
57
+ return {
58
+ kind: "check",
59
+ dist,
60
+ json: values.json,
61
+ strict: values.strict,
62
+ ...(browser !== undefined ? { browser: browser } : {}),
63
+ ...(values["user-data-dir"] !== undefined ? { userDataDir: values["user-data-dir"] } : {}),
64
+ ...(values.profile !== undefined ? { profile: values.profile } : {}),
65
+ ...(toleranceMs !== undefined ? { toleranceMs } : {}),
66
+ };
67
+ };
@@ -0,0 +1,9 @@
1
+ import type { CliIo } from "./types.js";
2
+ /**
3
+ * Runs the command line.
4
+ *
5
+ * @param argv - The arguments after the program name.
6
+ * @param io - Where to write output.
7
+ * @returns The exit code: 0 fresh, 1 stale, 2 not loaded or an error.
8
+ */
9
+ export declare const runCli: (argv: readonly string[], io: CliIo) => Promise<number>;
@@ -0,0 +1,61 @@
1
+ import { computeBuildHash } from "../hash/computeBuildHash.js";
2
+ import { checkProfileFreshness } from "../profile/checkProfileFreshness.js";
3
+ import { formatProfileReport } from "../report/formatProfileReport.js";
4
+ import { HELP_TEXT } from "./helpText.js";
5
+ import { parseCliArguments } from "./parseCliArguments.js";
6
+ import { VERSION } from "./version.js";
7
+ /**
8
+ * Runs the command line.
9
+ *
10
+ * @param argv - The arguments after the program name.
11
+ * @param io - Where to write output.
12
+ * @returns The exit code: 0 fresh, 1 stale, 2 not loaded or an error.
13
+ */
14
+ export const runCli = async (argv, io) => {
15
+ const command = parseCliArguments(argv);
16
+ switch (command.kind) {
17
+ case "help":
18
+ io.out(HELP_TEXT);
19
+ return 0;
20
+ case "version":
21
+ io.out(`${VERSION}\n`);
22
+ return 0;
23
+ case "error":
24
+ io.err(`extension-stale-check: ${command.message}\nRun with --help for usage.\n`);
25
+ return 2;
26
+ case "hash": {
27
+ try {
28
+ const build = await computeBuildHash(command.dist);
29
+ io.out(command.json
30
+ ? `${JSON.stringify(build)}\n`
31
+ : `${build.hash} ${String(build.fileCount)} files\n`);
32
+ return 0;
33
+ }
34
+ catch (error) {
35
+ io.err(`extension-stale-check: ${error instanceof Error ? error.message : String(error)}\n`);
36
+ return 2;
37
+ }
38
+ }
39
+ case "check": {
40
+ try {
41
+ const report = await checkProfileFreshness({
42
+ dist: command.dist,
43
+ ...(command.browser ? { browser: command.browser } : {}),
44
+ ...(command.userDataDir ? { userDataDir: command.userDataDir } : {}),
45
+ ...(command.profile ? { profile: command.profile } : {}),
46
+ ...(command.toleranceMs !== undefined ? { toleranceMs: command.toleranceMs } : {}),
47
+ });
48
+ io.out(command.json ? `${JSON.stringify(report, null, 2)}\n` : formatProfileReport(report));
49
+ if (report.status === "not-loaded")
50
+ return 2;
51
+ if (report.status === "stale")
52
+ return 1;
53
+ return report.status === "possibly-stale" && command.strict ? 1 : 0;
54
+ }
55
+ catch (error) {
56
+ io.err(`extension-stale-check: ${error instanceof Error ? error.message : String(error)}\n`);
57
+ return 2;
58
+ }
59
+ }
60
+ }
61
+ };
@@ -0,0 +1,30 @@
1
+ import type { BrowserName } from "../types.js";
2
+ /** What the command line asked for, after parsing. */
3
+ export type CliCommand = {
4
+ readonly kind: "help";
5
+ } | {
6
+ readonly kind: "version";
7
+ } | {
8
+ readonly kind: "error";
9
+ readonly message: string;
10
+ } | {
11
+ readonly kind: "hash";
12
+ readonly dist: string;
13
+ readonly json: boolean;
14
+ } | {
15
+ readonly kind: "check";
16
+ readonly dist: string;
17
+ readonly json: boolean;
18
+ readonly strict: boolean;
19
+ readonly browser?: BrowserName;
20
+ readonly userDataDir?: string;
21
+ readonly profile?: string;
22
+ readonly toleranceMs?: number;
23
+ };
24
+ /** Where the CLI writes. Tests pass their own; the binary passes the process streams. */
25
+ export interface CliIo {
26
+ /** Writes to standard output. */
27
+ out(text: string): void;
28
+ /** Writes to standard error. */
29
+ err(text: string): void;
30
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ /** This package's version, read from its own `package.json`. */
2
+ export declare const VERSION: string;
@@ -0,0 +1,3 @@
1
+ import { createRequire } from "node:module";
2
+ /** This package's version, read from its own `package.json`. */
3
+ export const VERSION = createRequire(import.meta.url)("../../package.json").version;
@@ -0,0 +1,12 @@
1
+ import type { RuntimeReport } from "../types.js";
2
+ /** Thrown when the extension a browser is running no longer matches `dist/`. */
3
+ export declare class StaleExtensionError extends Error {
4
+ /** The full comparison that found the difference. */
5
+ readonly report: RuntimeReport;
6
+ /**
7
+ * Builds the error from the comparison that found the extension stale, using its message.
8
+ *
9
+ * @param report - The comparison that found the extension stale.
10
+ */
11
+ constructor(report: RuntimeReport);
12
+ }
@@ -0,0 +1,15 @@
1
+ /** Thrown when the extension a browser is running no longer matches `dist/`. */
2
+ export class StaleExtensionError extends Error {
3
+ /** The full comparison that found the difference. */
4
+ report;
5
+ /**
6
+ * Builds the error from the comparison that found the extension stale, using its message.
7
+ *
8
+ * @param report - The comparison that found the extension stale.
9
+ */
10
+ constructor(report) {
11
+ super(report.message);
12
+ this.name = "StaleExtensionError";
13
+ this.report = report;
14
+ }
15
+ }
@@ -0,0 +1,23 @@
1
+ /** What {@link computeBuildHash} returns. */
2
+ export interface BuildHash {
3
+ /** Hex SHA-256 over every file's relative path and contents. */
4
+ readonly hash: string;
5
+ /** How many files went into the hash. */
6
+ readonly fileCount: number;
7
+ }
8
+ /** Options for {@link computeBuildHash}. */
9
+ export interface BuildHashOptions {
10
+ /** Return `true` for a relative path (`/` separators) to leave that file out, e.g. source maps. */
11
+ readonly exclude?: (relativePath: string) => boolean;
12
+ }
13
+ /**
14
+ * Hashes a built extension folder, so two builds can be told apart (or shown identical) by one string.
15
+ *
16
+ * The hash covers each file's relative path and bytes in sorted order, so it does not depend on
17
+ * modification times, the platform, or the order the file system lists entries in.
18
+ *
19
+ * @param dist - The built extension folder.
20
+ * @param options - An optional filter for files to leave out.
21
+ * @returns The hash and the number of files it covers.
22
+ */
23
+ export declare const computeBuildHash: (dist: string, options?: BuildHashOptions) => Promise<BuildHash>;
@@ -0,0 +1,25 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { listFiles } from "./listFiles.js";
5
+ /**
6
+ * Hashes a built extension folder, so two builds can be told apart (or shown identical) by one string.
7
+ *
8
+ * The hash covers each file's relative path and bytes in sorted order, so it does not depend on
9
+ * modification times, the platform, or the order the file system lists entries in.
10
+ *
11
+ * @param dist - The built extension folder.
12
+ * @param options - An optional filter for files to leave out.
13
+ * @returns The hash and the number of files it covers.
14
+ */
15
+ export const computeBuildHash = async (dist, options = {}) => {
16
+ const files = (await listFiles(dist)).filter((file) => !options.exclude?.(file));
17
+ const hash = createHash("sha256");
18
+ for (const file of files) {
19
+ hash.update(file);
20
+ hash.update("\0");
21
+ hash.update(await readFile(path.join(dist, file)));
22
+ hash.update("\0");
23
+ }
24
+ return { hash: hash.digest("hex"), fileCount: files.length };
25
+ };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Lists every file under a folder, recursively.
3
+ *
4
+ * @param root - The folder to walk.
5
+ * @returns Paths relative to `root`, with `/` separators on every platform, sorted.
6
+ */
7
+ export declare const listFiles: (root: string) => Promise<string[]>;
@@ -0,0 +1,16 @@
1
+ import { readdir } from "node:fs/promises";
2
+ import path from "node:path";
3
+ /**
4
+ * Lists every file under a folder, recursively.
5
+ *
6
+ * @param root - The folder to walk.
7
+ * @returns Paths relative to `root`, with `/` separators on every platform, sorted.
8
+ */
9
+ export const listFiles = async (root) => {
10
+ const entries = await readdir(root, { recursive: true, withFileTypes: true });
11
+ return entries
12
+ .filter((entry) => entry.isFile())
13
+ .map((entry) => path.relative(root, path.join(entry.parentPath, entry.name)))
14
+ .map((relative) => relative.split(path.sep).join("/"))
15
+ .sort();
16
+ };
@@ -0,0 +1,15 @@
1
+ export { StaleExtensionError } from "./errors/StaleExtensionError.js";
2
+ export { computeBuildHash } from "./hash/computeBuildHash.js";
3
+ export type { BuildHash, BuildHashOptions } from "./hash/computeBuildHash.js";
4
+ export { diffManifests } from "./manifest/diffManifests.js";
5
+ export type { DiffOptions } from "./manifest/diffManifests.js";
6
+ export { readDiskManifest } from "./manifest/readDiskManifest.js";
7
+ export { checkProfileFreshness } from "./profile/checkProfileFreshness.js";
8
+ export type { ProfileCheckOptions } from "./profile/checkProfileFreshness.js";
9
+ export { resolveUserDataDir } from "./profile/resolveUserDataDir.js";
10
+ export type { ResolveUserDataDirOptions } from "./profile/resolveUserDataDir.js";
11
+ export { assertExtensionFresh } from "./runtime/assertExtensionFresh.js";
12
+ export { checkRuntimeFreshness } from "./runtime/checkRuntimeFreshness.js";
13
+ export type { RuntimeCheckOptions } from "./runtime/checkRuntimeFreshness.js";
14
+ export { readLoadedManifest } from "./runtime/readLoadedManifest.js";
15
+ export type { BrowserName, Evaluable, JsonObject, ManifestDifference, ProfileReport, RuntimeReport, } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export { StaleExtensionError } from "./errors/StaleExtensionError.js";
2
+ export { computeBuildHash } from "./hash/computeBuildHash.js";
3
+ export { diffManifests } from "./manifest/diffManifests.js";
4
+ export { readDiskManifest } from "./manifest/readDiskManifest.js";
5
+ export { checkProfileFreshness } from "./profile/checkProfileFreshness.js";
6
+ export { resolveUserDataDir } from "./profile/resolveUserDataDir.js";
7
+ export { assertExtensionFresh } from "./runtime/assertExtensionFresh.js";
8
+ export { checkRuntimeFreshness } from "./runtime/checkRuntimeFreshness.js";
9
+ export { readLoadedManifest } from "./runtime/readLoadedManifest.js";
@@ -0,0 +1,15 @@
1
+ import type { ManifestDifference } from "../types.js";
2
+ /**
3
+ * Walks two JSON values together and records every place they differ.
4
+ *
5
+ * Objects are compared key by key (a missing key and `undefined` are the same), arrays index by
6
+ * index, everything else with `Object.is`. A disk value that is a `__MSG_x__` locale placeholder is
7
+ * skipped, and so is any path listed in `ignore`.
8
+ *
9
+ * @param loaded - The value the browser is running.
10
+ * @param disk - The value on disk.
11
+ * @param path - The path of these two values from the manifest root (`""` at the root).
12
+ * @param ignore - Paths to skip, such as `"key"` or `"content_scripts[0].js"`.
13
+ * @param out - The list differences are appended to.
14
+ */
15
+ export declare const collectDifferences: (loaded: unknown, disk: unknown, path: string, ignore: ReadonlySet<string>, out: ManifestDifference[]) => void;
@@ -0,0 +1,35 @@
1
+ import { isLocalePlaceholder } from "./isLocalePlaceholder.js";
2
+ import { isPlainObject } from "./isPlainObject.js";
3
+ /**
4
+ * Walks two JSON values together and records every place they differ.
5
+ *
6
+ * Objects are compared key by key (a missing key and `undefined` are the same), arrays index by
7
+ * index, everything else with `Object.is`. A disk value that is a `__MSG_x__` locale placeholder is
8
+ * skipped, and so is any path listed in `ignore`.
9
+ *
10
+ * @param loaded - The value the browser is running.
11
+ * @param disk - The value on disk.
12
+ * @param path - The path of these two values from the manifest root (`""` at the root).
13
+ * @param ignore - Paths to skip, such as `"key"` or `"content_scripts[0].js"`.
14
+ * @param out - The list differences are appended to.
15
+ */
16
+ export const collectDifferences = (loaded, disk, path, ignore, out) => {
17
+ if (ignore.has(path) || isLocalePlaceholder(disk))
18
+ return;
19
+ if (Array.isArray(loaded) && Array.isArray(disk)) {
20
+ const length = Math.max(loaded.length, disk.length);
21
+ for (let index = 0; index < length; index += 1) {
22
+ collectDifferences(loaded[index], disk[index], `${path}[${String(index)}]`, ignore, out);
23
+ }
24
+ return;
25
+ }
26
+ if (isPlainObject(loaded) && isPlainObject(disk)) {
27
+ const keys = new Set([...Object.keys(loaded), ...Object.keys(disk)]);
28
+ for (const key of [...keys].sort()) {
29
+ collectDifferences(loaded[key], disk[key], path ? `${path}.${key}` : key, ignore, out);
30
+ }
31
+ return;
32
+ }
33
+ if (!Object.is(loaded, disk))
34
+ out.push({ path: path || "(root)", loaded, disk });
35
+ };