camoucore 0.3.0 → 0.6.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 (171) hide show
  1. package/LICENSE +4 -3
  2. package/dist/camoufox/__main__.d.ts +10 -0
  3. package/dist/camoufox/__main__.js +1175 -0
  4. package/dist/camoufox/__version__.d.ts +31 -0
  5. package/dist/camoufox/__version__.js +32 -0
  6. package/dist/camoufox/_humanize_playwright.d.ts +54 -0
  7. package/dist/camoufox/_humanize_playwright.js +429 -0
  8. package/dist/camoufox/addons.d.ts +21 -0
  9. package/dist/camoufox/addons.js +56 -0
  10. package/dist/camoufox/async_api.d.ts +9 -0
  11. package/dist/camoufox/async_api.js +9 -0
  12. package/dist/camoufox/browser-pin.d.ts +46 -0
  13. package/dist/camoufox/browser-pin.js +96 -0
  14. package/dist/camoufox/cli.d.ts +7 -0
  15. package/dist/camoufox/cli.js +20 -0
  16. package/dist/camoufox/coherence.d.ts +141 -0
  17. package/dist/camoufox/coherence.js +708 -0
  18. package/dist/camoufox/data-files/audio-output-latency.json +15 -0
  19. package/dist/camoufox/data-files/browser-pin.json +7 -0
  20. package/dist/camoufox/data-files/display-profiles.json +6 -0
  21. package/dist/camoufox/data-files/essential-fonts.json +5 -0
  22. package/dist/camoufox/data-files/fingerprint-presets-v150.json +14544 -0
  23. package/dist/camoufox/data-files/fingerprint-presets.json +5192 -0
  24. package/dist/camoufox/data-files/font-bases.json +1888 -0
  25. package/dist/camoufox/data-files/font-groups.json +716 -0
  26. package/dist/camoufox/data-files/font-prefs.json +1046 -0
  27. package/dist/camoufox/data-files/fonts.json +240 -0
  28. package/dist/camoufox/data-files/fpgen.yml +44 -0
  29. package/dist/camoufox/data-files/launcher-constants.json +136 -0
  30. package/dist/camoufox/data-files/media-devices.json +180 -0
  31. package/dist/camoufox/data-files/repos.yml +40 -0
  32. package/dist/camoufox/data-files/voice-manifests.json +1864 -0
  33. package/dist/camoufox/data-files/voice-uris.json +188 -0
  34. package/dist/camoufox/data-files/warnings.yml +146 -0
  35. package/dist/camoufox/display_profile.d.ts +21 -0
  36. package/dist/camoufox/display_profile.js +129 -0
  37. package/dist/camoufox/driver_defaults.d.ts +27 -0
  38. package/dist/camoufox/driver_defaults.js +119 -0
  39. package/dist/camoufox/exceptions.d.ts +68 -0
  40. package/dist/camoufox/exceptions.js +122 -0
  41. package/dist/camoufox/fingerprints.d.ts +434 -0
  42. package/dist/camoufox/fingerprints.js +1936 -0
  43. package/dist/camoufox/gpudisplay.d.ts +158 -0
  44. package/dist/camoufox/gpudisplay.js +695 -0
  45. package/dist/camoufox/host_rendering.d.ts +38 -0
  46. package/dist/camoufox/host_rendering.js +180 -0
  47. package/dist/camoufox/humanize.d.ts +89 -0
  48. package/dist/camoufox/humanize.js +143 -0
  49. package/dist/camoufox/index.d.ts +21 -0
  50. package/dist/camoufox/index.js +21 -0
  51. package/dist/camoufox/ip.d.ts +45 -0
  52. package/dist/camoufox/ip.js +114 -0
  53. package/dist/camoufox/multiversion.d.ts +131 -0
  54. package/dist/camoufox/multiversion.js +490 -0
  55. package/dist/camoufox/node-floor.d.ts +5 -0
  56. package/dist/camoufox/node-floor.js +17 -0
  57. package/dist/camoufox/paths.d.ts +45 -0
  58. package/dist/camoufox/paths.js +62 -0
  59. package/dist/camoufox/pkgman.d.ts +361 -0
  60. package/dist/camoufox/pkgman.js +1066 -0
  61. package/dist/camoufox/product.d.ts +8 -0
  62. package/dist/camoufox/product.js +8 -0
  63. package/dist/camoufox/pycompat.d.ts +97 -0
  64. package/dist/camoufox/pycompat.js +458 -0
  65. package/dist/camoufox/server.d.ts +36 -0
  66. package/dist/camoufox/server.js +82 -0
  67. package/dist/camoufox/sync_api.d.ts +77 -0
  68. package/dist/camoufox/sync_api.js +207 -0
  69. package/dist/camoufox/utils.d.ts +638 -0
  70. package/dist/camoufox/utils.js +2507 -0
  71. package/dist/camoufox/warnings.d.ts +16 -0
  72. package/dist/camoufox/warnings.js +65 -0
  73. package/dist/camoufox/webgl.d.ts +52 -0
  74. package/dist/camoufox/webgl.js +264 -0
  75. package/dist/camouwolf/__main__.d.ts +10 -0
  76. package/dist/camouwolf/__main__.js +1180 -0
  77. package/dist/camouwolf/__version__.d.ts +31 -0
  78. package/dist/camouwolf/__version__.js +32 -0
  79. package/dist/camouwolf/_humanize_playwright.d.ts +53 -0
  80. package/dist/camouwolf/_humanize_playwright.js +427 -0
  81. package/dist/camouwolf/addons.d.ts +42 -0
  82. package/dist/camouwolf/addons.js +113 -0
  83. package/dist/camouwolf/async_api.d.ts +9 -0
  84. package/dist/camouwolf/async_api.js +9 -0
  85. package/dist/camouwolf/browser-pin.d.ts +46 -0
  86. package/dist/camouwolf/browser-pin.js +96 -0
  87. package/dist/camouwolf/cli.d.ts +7 -0
  88. package/dist/camouwolf/cli.js +20 -0
  89. package/dist/camouwolf/clienthints.d.ts +61 -0
  90. package/dist/camouwolf/clienthints.js +176 -0
  91. package/dist/camouwolf/coherence.d.ts +152 -0
  92. package/dist/camouwolf/coherence.js +554 -0
  93. package/dist/camouwolf/data-files/browser-pin.json +7 -0
  94. package/dist/camouwolf/data-files/camouwolf.defaults.json +118 -0
  95. package/dist/camouwolf/data-files/data/bundle-fonts.json +1983 -0
  96. package/dist/camouwolf/data-files/data/chrome-languages.json +517 -0
  97. package/dist/camouwolf/data-files/data/properties.json +321 -0
  98. package/dist/camouwolf/data-files/data/system-colors.json +35 -0
  99. package/dist/camouwolf/data-files/data/ubo.json +6 -0
  100. package/dist/camouwolf/data-files/fpgen.yml +41 -0
  101. package/dist/camouwolf/data-files/launcher-constants.json +26 -0
  102. package/dist/camouwolf/data-files/repos.yml +23 -0
  103. package/dist/camouwolf/data-files/warnings.yml +96 -0
  104. package/dist/camouwolf/driver_defaults.d.ts +25 -0
  105. package/dist/camouwolf/driver_defaults.js +114 -0
  106. package/dist/camouwolf/exceptions.d.ts +95 -0
  107. package/dist/camouwolf/exceptions.js +150 -0
  108. package/dist/camouwolf/fingerprints.d.ts +227 -0
  109. package/dist/camouwolf/fingerprints.js +753 -0
  110. package/dist/camouwolf/gpudisplay.d.ts +171 -0
  111. package/dist/camouwolf/gpudisplay.js +711 -0
  112. package/dist/camouwolf/host_rendering.d.ts +18 -0
  113. package/dist/camouwolf/host_rendering.js +114 -0
  114. package/dist/camouwolf/humanize.d.ts +84 -0
  115. package/dist/camouwolf/humanize.js +128 -0
  116. package/dist/camouwolf/index.d.ts +22 -0
  117. package/dist/camouwolf/index.js +21 -0
  118. package/dist/camouwolf/multiversion.d.ts +131 -0
  119. package/dist/camouwolf/multiversion.js +491 -0
  120. package/dist/camouwolf/node-floor.d.ts +5 -0
  121. package/dist/camouwolf/node-floor.js +17 -0
  122. package/dist/camouwolf/paths.d.ts +34 -0
  123. package/dist/camouwolf/paths.js +58 -0
  124. package/dist/camouwolf/pkgman.d.ts +331 -0
  125. package/dist/camouwolf/pkgman.js +972 -0
  126. package/dist/camouwolf/product.d.ts +3 -0
  127. package/dist/camouwolf/product.js +3 -0
  128. package/dist/camouwolf/pycompat.d.ts +92 -0
  129. package/dist/camouwolf/pycompat.js +461 -0
  130. package/dist/camouwolf/server.d.ts +36 -0
  131. package/dist/camouwolf/server.js +81 -0
  132. package/dist/camouwolf/switches.d.ts +77 -0
  133. package/dist/camouwolf/switches.js +222 -0
  134. package/dist/camouwolf/sync_api.d.ts +84 -0
  135. package/dist/camouwolf/sync_api.js +173 -0
  136. package/dist/camouwolf/utils.d.ts +644 -0
  137. package/dist/camouwolf/utils.js +2057 -0
  138. package/dist/camouwolf/warnings.d.ts +14 -0
  139. package/dist/camouwolf/warnings.js +59 -0
  140. package/dist/camouwolf/webgl.d.ts +41 -0
  141. package/dist/camouwolf/webgl.js +198 -0
  142. package/dist/data.d.ts +1 -1
  143. package/dist/data.js +3 -3
  144. package/dist/download.js +1 -1
  145. package/dist/exceptions.d.ts +1 -1
  146. package/dist/exceptions.js +1 -1
  147. package/dist/geolocation.js +1 -1
  148. package/dist/host.js +1 -1
  149. package/dist/ip.js +1 -1
  150. package/dist/locales.js +1 -1
  151. package/dist/mcp/cli.d.ts +15 -0
  152. package/dist/mcp/cli.js +108 -0
  153. package/dist/mcp/index.d.ts +8 -0
  154. package/dist/mcp/index.js +8 -0
  155. package/dist/mcp/main.d.ts +2 -0
  156. package/dist/mcp/main.js +8 -0
  157. package/dist/mcp/secrets.d.ts +50 -0
  158. package/dist/mcp/secrets.js +193 -0
  159. package/dist/mcp/server.d.ts +48 -0
  160. package/dist/mcp/server.js +653 -0
  161. package/dist/mcp/tree.d.ts +10 -0
  162. package/dist/mcp/tree.js +36 -0
  163. package/dist/passthrough.d.ts +1 -1
  164. package/dist/product.js +1 -1
  165. package/dist/settings.js +1 -1
  166. package/dist/telemetry.d.ts +0 -1
  167. package/dist/telemetry.js +5 -4
  168. package/dist/virtdisplay.d.ts +1 -1
  169. package/dist/virtdisplay.js +1 -1
  170. package/dist/warnings.js +1 -1
  171. package/package.json +57 -13
@@ -0,0 +1,1066 @@
1
+ /**
2
+ * Browser package management: version resolution, GitHub release discovery,
3
+ * download/extract, and path lookup.
4
+ *
5
+ * TypeScript twin of python/camoucore/src/camoucore/camoufox/pkgman.py.
6
+ */
7
+ import { execFileSync } from "node:child_process";
8
+ import { once } from "node:events";
9
+ import * as fs from "node:fs";
10
+ import { createRequire } from "node:module";
11
+ import * as os from "node:os";
12
+ import * as path from "node:path";
13
+ import cliProgress from "cli-progress";
14
+ import prettyBytes from "pretty-bytes";
15
+ import { githubHeaders, raiseForStatus, request, } from "../download.js";
16
+ import { CONSTRAINTS, LIBRARY_VERSION } from "./__version__.js";
17
+ import { effectivePin, pinMatches, pinSpec, warnIfUnpaired, } from "./browser-pin.js";
18
+ import { CamoufoxNotInstalled, FileNotFoundError, MissingRelease, ProfileDirectoryError, UnsupportedArchitecture, UnsupportedOS, UnsupportedVersion, } from "./exceptions.js";
19
+ // pkgman and multiversion are mutually dependent, exactly as the Python twin's
20
+ // function-local imports are. Every use below sits inside a function body, so
21
+ // the ESM cycle resolves before any binding is read.
22
+ import { COMPAT_FLAG, findInstalledVersion, getActivePath, getDefaultChannel, installVersioned, loadConfig, loadRepoCache, } from "./multiversion.js";
23
+ import { ARCH_MAP, INSTALL_DIR, LAUNCH_FILE, loadDataFile, OS_ARCH_MATRIX, OS_MAP, OS_NAME, rprint, } from "./paths.js";
24
+ import { comparePyStr, ValueError } from "./pycompat.js";
25
+ import { warn } from "./warnings.js";
26
+ export { GITHUB_TOKEN, unzip, verifySha256, } from "../download.js";
27
+ /**
28
+ * Ensure Firefox's Linux application directory exists before startup.
29
+ *
30
+ * Firefox probes ~/.camoufox even when Playwright supplies a temporary profile.
31
+ * On a read-only HOME -- the normal shape for a container that bakes the bundle
32
+ * in as root and runs as a non-root user -- a missing directory makes startup
33
+ * stall with no diagnostic, surfacing as a launch timeout rather than as a
34
+ * permissions error. An existing directory may itself still be read-only, which
35
+ * is fine: Firefox only needs it to be there.
36
+ */
37
+ export function ensureBrowserProfileDir(env) {
38
+ if (OS_NAME !== "lin")
39
+ return undefined;
40
+ const environment = env ?? process.env;
41
+ const configuredHome = environment.HOME;
42
+ const home = configuredHome
43
+ ? expandUser(String(configuredHome))
44
+ : os.homedir();
45
+ const profileDir = path.join(home, ".camoufox");
46
+ if (fs.existsSync(profileDir) && fs.statSync(profileDir).isDirectory()) {
47
+ return profileDir;
48
+ }
49
+ try {
50
+ fs.mkdirSync(profileDir, { recursive: true, mode: 0o700 });
51
+ }
52
+ catch (error) {
53
+ throw new ProfileDirectoryError(`Camoufox requires '${profileDir}' to exist before launch, but it could ` +
54
+ "not be created. For a read-only runtime, create this directory " +
55
+ "before making HOME read-only.", { cause: error });
56
+ }
57
+ if (!fs.statSync(profileDir).isDirectory()) {
58
+ throw new ProfileDirectoryError(`Camoufox requires '${profileDir}' to be a directory before launch.`);
59
+ }
60
+ return profileDir;
61
+ }
62
+ /** os.path.expanduser for the forms a HOME value can take. */
63
+ function expandUser(p) {
64
+ if (p === "~")
65
+ return os.homedir();
66
+ if (p.startsWith("~/"))
67
+ return path.join(os.homedir(), p.slice(2));
68
+ return p;
69
+ }
70
+ /**
71
+ * Parse a semver string into a comparable tuple.
72
+ */
73
+ export function parseSemver(version) {
74
+ // A prerelease compares as its release: 0.5.8b1 (PEP 440) and 0.5.8-beta.1
75
+ // (semver) are both 0.5.8, exactly as in the Python twin.
76
+ const release = version
77
+ .replace(/^[\^~]+/, "")
78
+ .split(/(?<=\d)(?:[-+]|(?:a|b|rc|dev|\.dev|\.post)\d*)/)[0];
79
+ const parts = release.split(".");
80
+ // int() semantics: the whole part must be an integer ("1a" -> 0).
81
+ const out = parts.map((part) => /^\s*[+-]?\d+\s*$/.test(part) ? Number.parseInt(part, 10) : 0);
82
+ while (out.length < 3)
83
+ out.push(0);
84
+ return out;
85
+ }
86
+ function compareTuples(a, b) {
87
+ const len = Math.max(a.length, b.length);
88
+ for (let i = 0; i < len; i++) {
89
+ const x = a[i] ?? 0;
90
+ const y = b[i] ?? 0;
91
+ if (x < y)
92
+ return -1;
93
+ if (x > y)
94
+ return 1;
95
+ }
96
+ return 0;
97
+ }
98
+ /**
99
+ * A comparable browser version string (up to 5 parts).
100
+ */
101
+ export class Version {
102
+ build;
103
+ version;
104
+ sortedRel;
105
+ constructor(build, version) {
106
+ this.build = build;
107
+ this.version = version;
108
+ // Mirrors the Python twin: digits stay numeric, a leading letter becomes
109
+ // ord(c) - 1024 so "alpha" < "beta" < numeric builds sort sanely.
110
+ const parts = build
111
+ .split(".")
112
+ .map((x) => (/^\d+$/.test(x) ? Number(x) : x.charCodeAt(0) - 1024));
113
+ const padding = 5 - (build.split(".").length - 1);
114
+ for (let i = 0; i < padding; i++)
115
+ parts.push(0);
116
+ this.sortedRel = parts;
117
+ }
118
+ get fullString() {
119
+ return `${this.version}-${this.build}`;
120
+ }
121
+ /** Whether the build channel is alpha (like "alpha.26"). */
122
+ get isAlpha() {
123
+ return this.build.split(".")[0].toLowerCase() === "alpha";
124
+ }
125
+ compare(other) {
126
+ return compareTuples(this.sortedRel, other.sortedRel);
127
+ }
128
+ equals(other) {
129
+ return this.compare(other) === 0;
130
+ }
131
+ lessThan(other) {
132
+ return this.compare(other) < 0;
133
+ }
134
+ greaterOrEqual(other) {
135
+ return this.compare(other) >= 0;
136
+ }
137
+ isSupported() {
138
+ return (this.compare(effectiveVersionMin()) >= 0 && this.compare(VERSION_MAX) < 0);
139
+ }
140
+ /**
141
+ * Read the version from version.json at the given path.
142
+ */
143
+ static fromPath(dir = INSTALL_DIR) {
144
+ const versionPath = path.join(dir, "version.json");
145
+ if (!fs.existsSync(versionPath)) {
146
+ throw new FileNotFoundError(`Version information not found at ${versionPath}. ` +
147
+ "Please run `camoufox fetch` to install.");
148
+ }
149
+ const data = JSON.parse(fs.readFileSync(versionPath, "utf-8"));
150
+ // "release" and then "tag" win over "build", as the Python twin's pops do.
151
+ const build = "release" in data ? data.release : "tag" in data ? data.tag : data.build;
152
+ if (build === undefined) {
153
+ throw new Error(`KeyError: 'build' (in ${versionPath})`);
154
+ }
155
+ return new Version(build, data.version ?? undefined);
156
+ }
157
+ static buildMinMax() {
158
+ return [
159
+ new Version(CONSTRAINTS.MIN_VERSION),
160
+ new Version(CONSTRAINTS.MAX_VERSION),
161
+ ];
162
+ }
163
+ }
164
+ export const [VERSION_MIN, VERSION_MAX] = Version.buildMinMax();
165
+ /**
166
+ * Seams the Python tests reach with monkeypatch (VERSION_MIN,
167
+ * _resolved_playwright_version, CamoufoxFetcher). Production code never
168
+ * reassigns these.
169
+ */
170
+ export const pkgmanDeps = {
171
+ versionMin: () => VERSION_MIN,
172
+ resolvedPlaywrightVersion: () => resolvedPlaywrightVersion(),
173
+ /** The fetcher the auto-install path runs `install()` on. */
174
+ newFetcher: async () => new CamoufoxFetcher().init(),
175
+ };
176
+ /**
177
+ * The resolved playwright-core version string, or null when it cannot be read.
178
+ * The Python twin asks importlib.metadata for `playwright`; the npm package
179
+ * that plays that role here is playwright-core.
180
+ */
181
+ export function resolvedPlaywrightVersionRaw() {
182
+ return installedPackageVersion("playwright-core");
183
+ }
184
+ /** An installed npm package's version, or null if it cannot be read. */
185
+ export function installedPackageVersion(name) {
186
+ try {
187
+ const require = createRequire(import.meta.url);
188
+ const pkg = JSON.parse(fs.readFileSync(require.resolve(`${name}/package.json`), "utf-8"));
189
+ return typeof pkg.version === "string" ? pkg.version : null;
190
+ }
191
+ catch {
192
+ return null;
193
+ }
194
+ }
195
+ /** The installed Playwright version, or null if it cannot be determined. */
196
+ export function resolvedPlaywrightVersion() {
197
+ const raw = resolvedPlaywrightVersionRaw();
198
+ return raw === null ? null : parseSemver(raw);
199
+ }
200
+ /** The installed Playwright version for messages ("the installed version"
201
+ * when it cannot be read). */
202
+ export function resolvedPlaywrightVersionStr() {
203
+ return resolvedPlaywrightVersionRaw() ?? "the installed version";
204
+ }
205
+ /**
206
+ * The lowest browser build this install can actually talk to.
207
+ *
208
+ * VERSION_MIN, raised by whatever the resolved Playwright requires. When the
209
+ * Playwright version cannot be read we fall back to VERSION_MIN rather than
210
+ * assuming the worst: a spurious forced re-download is worse than leaving a
211
+ * working install alone, and package.json caps Playwright anyway.
212
+ */
213
+ export function effectiveVersionMin() {
214
+ let floor = pkgmanDeps.versionMin();
215
+ const playwrightVersion = pkgmanDeps.resolvedPlaywrightVersion();
216
+ if (playwrightVersion === null)
217
+ return floor;
218
+ for (const [requiredPlaywright, build,] of CONSTRAINTS.PLAYWRIGHT_BROWSER_FLOORS) {
219
+ if (compareTuples(playwrightVersion, [...requiredPlaywright]) >= 0 &&
220
+ floor.lessThan(new Version(build))) {
221
+ floor = new Version(build);
222
+ }
223
+ }
224
+ return floor;
225
+ }
226
+ /**
227
+ * Find the browser build constraint for the current library version.
228
+ */
229
+ function findVersionConstraints(versions, libraryVersion) {
230
+ const libParts = parseSemver(libraryVersion);
231
+ let newest;
232
+ let newestMin;
233
+ for (const entry of versions) {
234
+ const pyLib = entry.python_library ?? {};
235
+ const libMin = parseSemver(pyLib.min ?? "0");
236
+ const libMax = parseSemver(pyLib.max ?? "999");
237
+ if (compareTuples(libMin, libParts) <= 0 &&
238
+ compareTuples(libParts, libMax) < 0) {
239
+ return entry.browser;
240
+ }
241
+ if (newestMin === undefined || compareTuples(libMin, newestMin) > 0) {
242
+ newestMin = libMin;
243
+ newest = entry.browser;
244
+ }
245
+ }
246
+ return newest;
247
+ }
248
+ /**
249
+ * Get the min and max build bounds for a channel.
250
+ */
251
+ function channelBounds(browser, channel) {
252
+ if (!browser)
253
+ return [undefined, undefined];
254
+ if ("stable" in browser || "prerelease" in browser) {
255
+ const section = browser[channel] ?? {};
256
+ return [section.min, section.max];
257
+ }
258
+ return [browser.min, browser.max];
259
+ }
260
+ /**
261
+ * Configuration for a Camoufox repository.
262
+ */
263
+ export class RepoConfig {
264
+ repos;
265
+ name;
266
+ pattern;
267
+ stableMin;
268
+ stableMax;
269
+ prereleaseMin;
270
+ prereleaseMax;
271
+ constructor(init) {
272
+ this.repos = init.repos;
273
+ this.name = init.name;
274
+ this.pattern = init.pattern;
275
+ this.stableMin = init.stableMin;
276
+ this.stableMax = init.stableMax;
277
+ this.prereleaseMin = init.prereleaseMin;
278
+ this.prereleaseMax = init.prereleaseMax;
279
+ }
280
+ /** Primary GitHub repo. */
281
+ get repo() {
282
+ return this.repos[0];
283
+ }
284
+ static loadRepos(spoofLibraryVersion) {
285
+ const data = loadDataFile("repos.yml");
286
+ return (data.browsers ?? []).map((r) => RepoConfig.fromEntry(r, spoofLibraryVersion));
287
+ }
288
+ static getDefaultName() {
289
+ return loadDataFile("repos.yml").default?.browser ?? "Official";
290
+ }
291
+ static fromEntry(entry, spoofLibraryVersion) {
292
+ if (!("pattern" in entry) || entry.pattern == null) {
293
+ throw new Error(`Repo '${entry.name ?? "unknown"}' missing required pattern`);
294
+ }
295
+ let browser;
296
+ if (entry.versions?.length) {
297
+ browser = findVersionConstraints(entry.versions, spoofLibraryVersion || LIBRARY_VERSION);
298
+ }
299
+ const [stableMin, stableMax] = channelBounds(browser, "stable");
300
+ const [prereleaseMin, prereleaseMax] = channelBounds(browser, "prerelease");
301
+ // Parse comma separated repos list (primary + fallbacks)
302
+ const repos = typeof entry.repo === "string"
303
+ ? entry.repo.split(",").map((r) => r.trim())
304
+ : entry.repo;
305
+ return new RepoConfig({
306
+ repos,
307
+ name: entry.name,
308
+ pattern: String(entry.pattern),
309
+ stableMin,
310
+ stableMax,
311
+ prereleaseMin,
312
+ prereleaseMax,
313
+ });
314
+ }
315
+ static getDefault() {
316
+ const found = RepoConfig.findByName(RepoConfig.getDefaultName());
317
+ return found ?? RepoConfig.loadRepos()[0];
318
+ }
319
+ static findByName(name) {
320
+ const lower = name.toLowerCase();
321
+ return RepoConfig.loadRepos().find((r) => r.name.toLowerCase() === lower);
322
+ }
323
+ getOsName(spoofOs) {
324
+ if (spoofOs)
325
+ return spoofOs;
326
+ const osName = OS_MAP[process.platform];
327
+ if (!osName) {
328
+ throw new UnsupportedOS(`OS ${process.platform} is not supported`);
329
+ }
330
+ return osName;
331
+ }
332
+ getArch(spoofArch) {
333
+ if (spoofArch)
334
+ return spoofArch;
335
+ const platArch = os.arch().toLowerCase();
336
+ const arch = ARCH_MAP[platArch];
337
+ if (!arch) {
338
+ throw new UnsupportedArchitecture(`Architecture ${platArch} is not supported`);
339
+ }
340
+ return arch;
341
+ }
342
+ /**
343
+ * Build the asset regex from the config pattern string.
344
+ */
345
+ buildPattern(spoofOs, spoofArch) {
346
+ const replacements = {
347
+ name: "(?<name>\\w+)",
348
+ version: "(?<version>[^-]+)",
349
+ build: "(?<build>[^-]+)",
350
+ os: escapeRegExp(this.getOsName(spoofOs)),
351
+ arch: escapeRegExp(this.getArch(spoofArch)),
352
+ };
353
+ const pattern = this.pattern.replace(/\./g, "\\.");
354
+ const regex = pattern.replace(/\{(\w+)\}/g, (match, key) => replacements[key] ?? match);
355
+ return new RegExp(`^${regex}`);
356
+ }
357
+ /**
358
+ * Check if a build is within the supported range for its channel.
359
+ */
360
+ isVersionSupported(version, isPrerelease = false) {
361
+ const buildMin = isPrerelease ? this.prereleaseMin : this.stableMin;
362
+ const buildMax = isPrerelease ? this.prereleaseMax : this.stableMax;
363
+ if (buildMin == null || buildMax == null) {
364
+ return true;
365
+ }
366
+ return (new Version(buildMin).compare(version) <= 0 &&
367
+ version.compare(new Version(buildMax)) <= 0);
368
+ }
369
+ }
370
+ function escapeRegExp(value) {
371
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
372
+ }
373
+ /** Whether this library speaks a browser's declared interface. */
374
+ export function interfaceSupported(iface) {
375
+ return CONSTRAINTS.MIN_INTERFACE <= iface && iface <= CONSTRAINTS.INTERFACE;
376
+ }
377
+ const releaseInterfaces = new Map();
378
+ /**
379
+ * The browser interface a GitHub release declares in its manifest.json. A
380
+ * release without a manifest, or a manifest without the field, predates the
381
+ * field and is interface 1.
382
+ */
383
+ export async function releaseInterface(release) {
384
+ const manifest = (release.assets ?? []).find((a) => a.name === "manifest.json");
385
+ if (!manifest)
386
+ return 1;
387
+ const key = manifest.id ?? manifest.browser_download_url;
388
+ let iface = releaseInterfaces.get(key);
389
+ if (iface === undefined) {
390
+ const url = manifest.browser_download_url;
391
+ const response = await request(url, {
392
+ signal: AbortSignal.timeout(20_000),
393
+ });
394
+ raiseForStatus(response, url);
395
+ iface = Number((await response.json()).interface ?? 1);
396
+ releaseInterfaces.set(key, iface);
397
+ }
398
+ return iface;
399
+ }
400
+ /** The interface recorded in an install's version.json at install time. */
401
+ export function installedInterface(installPath) {
402
+ const data = JSON.parse(fs.readFileSync(path.join(installPath, "version.json"), "utf-8"));
403
+ return Number(data.interface ?? 1);
404
+ }
405
+ /** Why a browser needs a newer package, and the command that gets one. */
406
+ export function upgradeMessage(version, iface) {
407
+ return (`Camoufox v${version.fullString} needs a newer camoufox package: it uses browser interface ` +
408
+ `${iface}, and this package supports ${CONSTRAINTS.MIN_INTERFACE}-` +
409
+ `${CONSTRAINTS.INTERFACE}. Upgrade with \`npm install camoufox@latest\`.`);
410
+ }
411
+ export function incompatibleMessage(version, iface) {
412
+ return (`${upgradeMessage(version, iface)} ` +
413
+ "Or run `camoufox fetch` to install a browser this package supports.");
414
+ }
415
+ let outdatedWarned = false;
416
+ /**
417
+ * Warn once when the last `camoufox sync` found a browser release that needs
418
+ * a newer package. Reads the sync cache, so a launch makes no request.
419
+ */
420
+ export function warnIfPackageOutdated() {
421
+ if (outdatedWarned)
422
+ return;
423
+ const newer = (loadRepoCache().incompatible ?? []);
424
+ if (!newer.length)
425
+ return;
426
+ outdatedWarned = true;
427
+ const versionOf = (v) => new Version(v.build, v.version);
428
+ const newest = newer.reduce((a, b) => versionOf(b).compare(versionOf(a)) > 0 ? b : a);
429
+ warn(upgradeMessage(versionOf(newest), newest.interface));
430
+ }
431
+ /** Test hook: forget that the warning was already issued. */
432
+ export function resetOutdatedWarning() {
433
+ outdatedWarned = false;
434
+ }
435
+ /** A GitHub repo's releases, newest first. */
436
+ async function githubReleases(repo) {
437
+ const apiUrl = `https://api.github.com/repos/${repo}/releases`;
438
+ const response = await request(apiUrl, {
439
+ headers: githubHeaders(apiUrl),
440
+ signal: AbortSignal.timeout(20_000),
441
+ });
442
+ raiseForStatus(response, apiUrl);
443
+ return (await response.json());
444
+ }
445
+ /**
446
+ * Information about an available Camoufox version on GitHub.
447
+ */
448
+ export class AvailableVersion {
449
+ version;
450
+ url;
451
+ isPrerelease;
452
+ assetId;
453
+ assetSize;
454
+ assetUpdatedAt;
455
+ sha256;
456
+ assetCreatedAt;
457
+ interface = 1;
458
+ constructor(init) {
459
+ Object.assign(this, init);
460
+ this.version = init.version;
461
+ this.url = init.url;
462
+ this.isPrerelease = init.isPrerelease;
463
+ }
464
+ /** First 8 hex chars of the sha256, or empty when unknown. */
465
+ get sha8() {
466
+ return (this.sha256 ?? "").slice(0, 8);
467
+ }
468
+ get display() {
469
+ const pre = this.isPrerelease ? " (prerelease)" : "";
470
+ return `v${this.version.fullString}${pre}`;
471
+ }
472
+ toMetadata() {
473
+ return {
474
+ version: this.version.version ?? null,
475
+ build: this.version.build,
476
+ prerelease: this.isPrerelease,
477
+ asset_id: this.assetId ?? null,
478
+ asset_size: this.assetSize ?? null,
479
+ asset_updated_at: this.assetUpdatedAt ?? null,
480
+ sha256: this.sha256 ?? null,
481
+ created_at: this.assetCreatedAt ?? null,
482
+ interface: this.interface,
483
+ };
484
+ }
485
+ }
486
+ /**
487
+ * Handles fetching and installing Camoufox.
488
+ */
489
+ export class CamoufoxFetcher {
490
+ githubRepos;
491
+ githubRepo;
492
+ isPrerelease = false;
493
+ repoConfig;
494
+ arch;
495
+ pattern;
496
+ installedSha256;
497
+ installedCreatedAt;
498
+ installedInterface = 1;
499
+ _versionObj;
500
+ _selectedVersion;
501
+ _url;
502
+ /**
503
+ * Where the download is kept between runs, so that a later fetch resumes
504
+ * it; unset downloads into a temporary file.
505
+ */
506
+ partial;
507
+ constructor(repoConfig, selectedVersion) {
508
+ this.repoConfig = repoConfig ?? RepoConfig.getDefault();
509
+ this.githubRepos = this.repoConfig.repos;
510
+ this.githubRepo = this.githubRepos[0];
511
+ this.arch = this.getPlatformArch();
512
+ this.pattern = this.repoConfig.buildPattern();
513
+ if (selectedVersion) {
514
+ this._selectedVersion = selectedVersion;
515
+ this._versionObj = selectedVersion.version;
516
+ this._url = selectedVersion.url;
517
+ this.isPrerelease = selectedVersion.isPrerelease;
518
+ this.installedSha256 = selectedVersion.sha256;
519
+ this.installedCreatedAt = selectedVersion.assetCreatedAt;
520
+ this.installedInterface = selectedVersion.interface;
521
+ }
522
+ }
523
+ /**
524
+ * The Python constructor calls fetch_latest() inline; downloads are async in
525
+ * JS, so callers do `await new CamoufoxFetcher().init()` instead.
526
+ */
527
+ async init() {
528
+ if (!this._versionObj) {
529
+ await this.fetchLatest();
530
+ }
531
+ return this;
532
+ }
533
+ /** First 8 hex chars of the installed asset sha, or empty. */
534
+ get installedSha8() {
535
+ return (this.installedSha256 ?? "").slice(0, 8);
536
+ }
537
+ /**
538
+ * Match a release asset against version constraints, OS, and arch.
539
+ */
540
+ checkAsset(asset, release) {
541
+ const match = this.pattern.exec(asset.name);
542
+ if (!match?.groups)
543
+ return null;
544
+ const version = new Version(match.groups.build, match.groups.version);
545
+ // A released library installs exactly the browser it was released with
546
+ // (browser-pin.ts), unless the user explicitly chose something else.
547
+ const pin = effectivePin(loadConfig());
548
+ if (pin &&
549
+ !pinMatches(pin, this.repoConfig.name, match.groups.version, match.groups.build)) {
550
+ return null;
551
+ }
552
+ const isPrerelease = Boolean(release?.prerelease) || version.isAlpha;
553
+ if (!pin && !this.repoConfig.isVersionSupported(version, isPrerelease)) {
554
+ return null;
555
+ }
556
+ const digest = asset.digest ?? "";
557
+ if (digest.startsWith("sha256:")) {
558
+ this.installedSha256 = digest.slice("sha256:".length);
559
+ }
560
+ this.installedCreatedAt = asset.created_at;
561
+ return [version, asset.browser_download_url];
562
+ }
563
+ /**
564
+ * Whether a release whose asset checkAsset() matched may be used. The
565
+ * Python twin decides this inside check_asset(); reading a manifest is
566
+ * async here, so it is a separate step.
567
+ */
568
+ async acceptRelease(release, [version]) {
569
+ const iface = await releaseInterface(release);
570
+ if (!interfaceSupported(iface)) {
571
+ rprint(incompatibleMessage(version, iface), "yellow");
572
+ return false;
573
+ }
574
+ this.installedInterface = iface;
575
+ return true;
576
+ }
577
+ missingAssetError() {
578
+ throw new MissingRelease(`No matching release found for ${OS_NAME} ${this.arch} in the ` +
579
+ "supported range. Please update the camoufox package.");
580
+ }
581
+ getReleases(githubRepo) {
582
+ return githubReleases(githubRepo);
583
+ }
584
+ /**
585
+ * Fetch the first matching release asset, trying fallback repos on failure.
586
+ */
587
+ async getAsset() {
588
+ let lastError;
589
+ for (const repo of this.githubRepos) {
590
+ try {
591
+ const releases = await this.getReleases(repo);
592
+ for (const release of releases) {
593
+ for (const asset of release.assets ?? []) {
594
+ const data = this.checkAsset(asset, release);
595
+ if (data && (await this.acceptRelease(release, data))) {
596
+ this.githubRepo = repo;
597
+ this.isPrerelease = release.prerelease ?? false;
598
+ return data;
599
+ }
600
+ }
601
+ }
602
+ }
603
+ catch (error) {
604
+ lastError = error;
605
+ }
606
+ }
607
+ if (lastError)
608
+ throw lastError;
609
+ this.missingAssetError();
610
+ }
611
+ getPlatformArch() {
612
+ const arch = (this.repoConfig ?? RepoConfig.getDefault()).getArch();
613
+ if (!OS_ARCH_MATRIX[OS_NAME].includes(arch)) {
614
+ throw new UnsupportedArchitecture(`Architecture ${arch} is not supported for ${OS_NAME}`);
615
+ }
616
+ return arch;
617
+ }
618
+ /**
619
+ * Fetch the latest camoufox release for the current platform.
620
+ */
621
+ async fetchLatest() {
622
+ const [versionObj, url] = await this.getAsset();
623
+ this._versionObj = versionObj;
624
+ this._url = url;
625
+ }
626
+ static async downloadFile(file, url) {
627
+ rprint(`Downloading package: ${url}`);
628
+ await webdl(url, undefined, true, file);
629
+ }
630
+ /**
631
+ * Download this build's archive into `file`. Through the instance's class,
632
+ * as Python's fetcher.download_file(), so a subclass can override either.
633
+ */
634
+ download(file) {
635
+ return this.constructor.downloadFile(file, this.url);
636
+ }
637
+ /**
638
+ * Download and install camoufox to a versioned subdirectory.
639
+ */
640
+ async install(replace = false) {
641
+ const installed = await installVersioned(this, replace);
642
+ ensureBrowserProfileDir();
643
+ return installed;
644
+ }
645
+ get url() {
646
+ if (!this._url) {
647
+ throw new ValueError("Url is not available. Make sure to run init() first.");
648
+ }
649
+ return this._url;
650
+ }
651
+ get version() {
652
+ if (!this._versionObj?.version) {
653
+ throw new ValueError("Version is not available. Make sure to run init() first.");
654
+ }
655
+ return this._versionObj.version;
656
+ }
657
+ get build() {
658
+ if (!this._versionObj) {
659
+ throw new ValueError("Build information is not available. Make sure to run init() first.");
660
+ }
661
+ return this._versionObj.build;
662
+ }
663
+ get verstr() {
664
+ if (!this._versionObj) {
665
+ throw new ValueError("Version is not available. Make sure to run init() first.");
666
+ }
667
+ return this._versionObj.fullString;
668
+ }
669
+ }
670
+ /**
671
+ * Fetch all supported versions from GitHub for the current platform. With
672
+ * includeIncompatible, builds that need a newer package are returned too
673
+ * (check `interfaceSupported(v.interface)`) instead of being reported.
674
+ */
675
+ export async function listAvailableVersions(repoConfig, includePrerelease = true, spoofOs, spoofArch, includeIncompatible = false) {
676
+ const config = repoConfig ?? RepoConfig.getDefault();
677
+ const pattern = config.buildPattern(spoofOs, spoofArch);
678
+ const osName = spoofOs ?? OS_NAME;
679
+ const arch = config.getArch(spoofArch);
680
+ if (!(OS_ARCH_MATRIX[osName] ?? []).includes(arch)) {
681
+ throw new UnsupportedArchitecture(`Architecture ${arch} is not supported for ${osName}`);
682
+ }
683
+ let releases = [];
684
+ let lastError;
685
+ for (const repo of config.repos) {
686
+ try {
687
+ releases = await githubReleases(repo);
688
+ break;
689
+ }
690
+ catch (error) {
691
+ lastError = error;
692
+ }
693
+ }
694
+ if (!releases.length && lastError)
695
+ throw lastError;
696
+ const versions = [];
697
+ for (const release of releases) {
698
+ versions.push(...(await releaseVersions(release, config, pattern, includePrerelease, includeIncompatible)));
699
+ }
700
+ versions.sort((a, b) => {
701
+ const byVersion = b.version.compare(a.version);
702
+ if (byVersion !== 0)
703
+ return byVersion;
704
+ return comparePyStr(b.assetCreatedAt ?? "", a.assetCreatedAt ?? "");
705
+ });
706
+ return versions;
707
+ }
708
+ /**
709
+ * The supported builds the release tagged `tag` holds for this platform, read
710
+ * with one API call per repo of the source. Empty when no repo has the tag.
711
+ */
712
+ export async function taggedVersions(repoConfig, tag) {
713
+ for (const repo of repoConfig.repos) {
714
+ const apiUrl = `https://api.github.com/repos/${repo}/releases/tags/${tag}`;
715
+ const response = await request(apiUrl, {
716
+ headers: githubHeaders(apiUrl),
717
+ signal: AbortSignal.timeout(20_000),
718
+ });
719
+ if (response.status === 404)
720
+ continue;
721
+ raiseForStatus(response, apiUrl);
722
+ return releaseVersions((await response.json()), repoConfig, repoConfig.buildPattern());
723
+ }
724
+ return [];
725
+ }
726
+ /**
727
+ * The release's assets that match `pattern` and the source's version range.
728
+ */
729
+ async function releaseVersions(release, config, pattern, includePrerelease = true, includeIncompatible = false) {
730
+ const isPrerelease = release.prerelease ?? false;
731
+ if (isPrerelease && !includePrerelease)
732
+ return [];
733
+ const versions = [];
734
+ for (const asset of release.assets ?? []) {
735
+ const match = pattern.exec(asset.name);
736
+ if (!match?.groups)
737
+ continue;
738
+ const version = new Version(match.groups.build, match.groups.version);
739
+ const assetPrerelease = isPrerelease || version.isAlpha;
740
+ if (assetPrerelease && !includePrerelease)
741
+ continue;
742
+ if (!config.isVersionSupported(version, assetPrerelease))
743
+ continue;
744
+ const iface = await releaseInterface(release);
745
+ if (!interfaceSupported(iface) && !includeIncompatible) {
746
+ rprint(incompatibleMessage(version, iface), "yellow");
747
+ continue;
748
+ }
749
+ const digest = asset.digest ?? "";
750
+ const sha256 = digest.startsWith("sha256:")
751
+ ? digest.slice("sha256:".length)
752
+ : undefined;
753
+ versions.push(new AvailableVersion({
754
+ version,
755
+ url: asset.browser_download_url,
756
+ isPrerelease: assetPrerelease,
757
+ assetId: asset.id,
758
+ assetSize: asset.size,
759
+ assetUpdatedAt: asset.updated_at,
760
+ sha256,
761
+ assetCreatedAt: asset.created_at,
762
+ interface: iface,
763
+ }));
764
+ }
765
+ return versions;
766
+ }
767
+ /**
768
+ * Get the full version string of the active install.
769
+ */
770
+ export function installedVerStr(fromDir) {
771
+ // An explicit directory (the folder holding a sandbox/alt-version
772
+ // executable_path) reads that build's version.json instead of the active
773
+ // install's. Mac-bundle aware: an executable inside
774
+ // Camoufox.app/Contents/MacOS/ belongs to an install whose version.json sits
775
+ // three levels up -- unless a deployment stamped one beside the binary.
776
+ if (fromDir) {
777
+ let dir = fromDir;
778
+ if (path.basename(dir) === "MacOS" &&
779
+ !fs.existsSync(path.join(dir, "version.json"))) {
780
+ dir = path.dirname(path.dirname(path.dirname(dir)));
781
+ }
782
+ return Version.fromPath(dir).fullString;
783
+ }
784
+ const active = getActivePath();
785
+ if (active === null)
786
+ throw notInstalledError();
787
+ const version = Version.fromPath(active);
788
+ if (path.basename(path.dirname(path.dirname(active))) === "browsers") {
789
+ warnIfUnpaired(path.basename(path.dirname(active)), version.version ?? "", version.build);
790
+ }
791
+ return version.fullString;
792
+ }
793
+ /**
794
+ * Whether INSTALL_DIR's root holds a supported build.
795
+ *
796
+ * Only the pre-multiversion flat layout wrote version.json at the root; the
797
+ * versioned layout keeps it under browsers/<repo>/<version>/. A missing root
798
+ * version.json means "no legacy install here", so the caller should fall
799
+ * through to a fetch rather than raise. The alpha.1 floor masked this: no
800
+ * install was ever unsupported, so this branch was never reached.
801
+ */
802
+ export function rootInstallSupported() {
803
+ try {
804
+ return Version.fromPath().isSupported();
805
+ }
806
+ catch (error) {
807
+ if (error instanceof FileNotFoundError)
808
+ return false;
809
+ throw error;
810
+ }
811
+ }
812
+ /** What is missing -- the paired build, a pin, or a channel -- and how to get it. */
813
+ function notInstalledError() {
814
+ const config = loadConfig();
815
+ const pin = effectivePin(config);
816
+ const pinned = config.pinned;
817
+ const channel = config.channel || getDefaultChannel();
818
+ const missing = pin
819
+ ? `${pin.repoName} ${pinSpec(pin)}, the browser this camoufox release pairs with,`
820
+ : pinned
821
+ ? `${channel}/${pinned}`
822
+ : channel;
823
+ return new CamoufoxNotInstalled(`${missing} is not installed. Please run \`camoufox fetch\` to install.`);
824
+ }
825
+ /**
826
+ * The part of the Python twin's camoufox_path() that runs before it would
827
+ * download: returns the install to use, or null when a fetch is needed (only
828
+ * possible with `downloadIfMissing`; otherwise the Python errors are raised).
829
+ */
830
+ function resolveInstalledPath(downloadIfMissing) {
831
+ // Clean up incompatible old data directory
832
+ if (fs.existsSync(INSTALL_DIR) &&
833
+ fs.readdirSync(INSTALL_DIR).length > 0 &&
834
+ !fs.existsSync(COMPAT_FLAG)) {
835
+ rprint("Cleaning old data...", "yellow");
836
+ fs.rmSync(INSTALL_DIR, { recursive: true, force: true });
837
+ }
838
+ const active = getActivePath();
839
+ if (active) {
840
+ const installed = Version.fromPath(active);
841
+ const iface = installedInterface(active);
842
+ if (!interfaceSupported(iface)) {
843
+ throw new UnsupportedVersion(incompatibleMessage(installed, iface));
844
+ }
845
+ if (installed.isSupported())
846
+ return active;
847
+ }
848
+ if (!fs.existsSync(INSTALL_DIR) || fs.readdirSync(INSTALL_DIR).length === 0) {
849
+ if (!downloadIfMissing)
850
+ throw notInstalledError();
851
+ }
852
+ else if (rootInstallSupported()) {
853
+ return INSTALL_DIR;
854
+ }
855
+ else if (!downloadIfMissing) {
856
+ // Other builds are installed, but not the one this release pairs with.
857
+ if (effectivePin(loadConfig()))
858
+ throw notInstalledError();
859
+ throw new UnsupportedVersion("Camoufox executable is outdated.");
860
+ }
861
+ return null;
862
+ }
863
+ /**
864
+ * Full path to the active camoufox folder.
865
+ *
866
+ * This is the Python twin's camoufox_path(download_if_missing=False): it is
867
+ * called from synchronous path helpers, and a download is asynchronous in JS.
868
+ * `ensureCamoufoxInstalled()` is the download_if_missing=True half;
869
+ * `launchOptions()` awaits it before any path lookup, so first-run
870
+ * auto-download behaviour is preserved.
871
+ */
872
+ export function camoufoxPath() {
873
+ return resolveInstalledPath(false);
874
+ }
875
+ /**
876
+ * Resolve the active browser, downloading it first when nothing usable is
877
+ * installed. The async counterpart to the Python twin's camoufox_path().
878
+ */
879
+ export async function ensureCamoufoxInstalled() {
880
+ const found = resolveInstalledPath(true);
881
+ if (found !== null)
882
+ return found;
883
+ const fetcher = await pkgmanDeps.newFetcher();
884
+ await fetcher.install();
885
+ // Re-check rather than recurse.
886
+ //
887
+ // If the newest published build is still below the floor -- a library
888
+ // published ahead of its browser release, or a repos source that does not
889
+ // carry it -- install() is a no-op ("already installed") and recursing here
890
+ // spun ~1000 fetch attempts into a stack overflow, having hammered the
891
+ // GitHub API into a rate limit on the way. Say what is actually wrong.
892
+ const active = getActivePath();
893
+ if (active && Version.fromPath(active).isSupported()) {
894
+ return active;
895
+ }
896
+ if (fs.existsSync(INSTALL_DIR) && rootInstallSupported()) {
897
+ return INSTALL_DIR;
898
+ }
899
+ throw new UnsupportedVersion("No available Camoufox build satisfies this library's minimum " +
900
+ `(${CONSTRAINTS.MIN_VERSION}). The matching browser release may not be ` +
901
+ "published yet; wait for it, or install an older camoufox release.");
902
+ }
903
+ /**
904
+ * A file the build ships, found from its executable: beside it, or in
905
+ * Contents/Resources when the executable is a macOS app bundle's Contents/MacOS/.
906
+ */
907
+ export function buildFile(executablePath, name) {
908
+ const directory = path.dirname(executablePath);
909
+ return path.basename(directory) === "MacOS"
910
+ ? path.join(path.dirname(directory), "Resources", name)
911
+ : path.join(directory, name);
912
+ }
913
+ /** Get the path to a file in the camoufox directory. */
914
+ export function getPath(file) {
915
+ if (OS_NAME === "mac") {
916
+ return path.resolve(camoufoxPath(), "Camoufox.app", "Contents", "Resources", file);
917
+ }
918
+ return path.join(camoufoxPath(), file);
919
+ }
920
+ /**
921
+ * Get the path to the camoufox executable.
922
+ */
923
+ export function launchPath(browserPath) {
924
+ let execPath;
925
+ if (browserPath) {
926
+ execPath =
927
+ OS_NAME === "mac"
928
+ ? path.resolve(browserPath, "Camoufox.app", "Contents", "Resources", LAUNCH_FILE[OS_NAME])
929
+ : path.join(browserPath, LAUNCH_FILE[OS_NAME]);
930
+ }
931
+ else {
932
+ execPath = getPath(LAUNCH_FILE[OS_NAME]);
933
+ }
934
+ if (!fs.existsSync(execPath)) {
935
+ throw new CamoufoxNotInstalled(`Camoufox is not installed at ${browserPath ?? camoufoxPath()}. ` +
936
+ "Please run `camoufox fetch` to install.");
937
+ }
938
+ return execPath;
939
+ }
940
+ /**
941
+ * The executable of the installed build `specifier` names (the `browser`
942
+ * launch option). Like `camoufox set`, it overrides the pairing: it never
943
+ * downloads, and it warns when the build is not the paired one.
944
+ */
945
+ export function selectedLaunchPath(specifier) {
946
+ const installPath = findInstalledVersion(specifier);
947
+ if (installPath === null) {
948
+ throw new ValueError(`Browser version '${specifier}' not found. Run \`camoufox list\` to see installed versions.`);
949
+ }
950
+ const version = Version.fromPath(installPath);
951
+ const iface = installedInterface(installPath);
952
+ if (!interfaceSupported(iface)) {
953
+ throw new UnsupportedVersion(incompatibleMessage(version, iface));
954
+ }
955
+ warnIfUnpaired(path.basename(path.dirname(installPath)), version.version ?? "", version.build);
956
+ return launchPath(installPath);
957
+ }
958
+ const formatBytes = (v, _, type) => type === "total" || type === "value" ? prettyBytes(v) : String(v);
959
+ /**
960
+ * camoucore.download.webdl cannot resume (no `offset`, `restart`); this stays
961
+ * until it can.
962
+ *
963
+ * Download a file from the given URL. Streams into `buffer` when one is given,
964
+ * otherwise accumulates and returns the bytes.
965
+ *
966
+ * An HTTP error raises requests' "<status> Client Error: ... for url: ..."
967
+ * message, like the Python twin; see request() for network failures.
968
+ *
969
+ * `offset` resumes a download whose first `offset` bytes `buffer` already
970
+ * appends to. `restart` empties what `buffer` writes to: it is called when the
971
+ * server sends the whole file, not the rest of it.
972
+ */
973
+ export async function webdl(url, desc, bar = true, buffer = null, { progressCallback, offset = 0, restart, } = {}) {
974
+ const headers = githubHeaders(url);
975
+ if (offset)
976
+ headers.Range = `bytes=${offset}-`;
977
+ const response = await request(url, { headers });
978
+ raiseForStatus(response, url);
979
+ if (offset && response.status !== 206) {
980
+ restart?.();
981
+ offset = 0;
982
+ }
983
+ const totalSize = offset + Number.parseInt(response.headers.get("content-length") || "0", 10);
984
+ let progressBar = null;
985
+ if (!progressCallback && bar) {
986
+ progressBar = new cliProgress.SingleBar({
987
+ format: `${desc || "Downloading"} [{bar}] {percentage}% | ETA: {eta_formatted} | {value}/{total}`,
988
+ formatValue: formatBytes,
989
+ noTTYOutput: true,
990
+ }, cliProgress.Presets.shades_classic);
991
+ progressBar.start(totalSize, offset);
992
+ }
993
+ const chunks = [];
994
+ let downloaded = offset;
995
+ let lastUpdate = offset;
996
+ try {
997
+ if (!response.body) {
998
+ throw new Error(`Response from ${url} had no body`);
999
+ }
1000
+ for await (const chunk of response.body) {
1001
+ if (buffer) {
1002
+ // A stream that already failed (disk full) never drains: surface
1003
+ // its error instead of waiting on it. When it is merely slow,
1004
+ // wait for it, or the whole archive ends up queued in memory.
1005
+ if (buffer.errored)
1006
+ throw buffer.errored;
1007
+ if (!buffer.write(chunk))
1008
+ await once(buffer, "drain");
1009
+ }
1010
+ else {
1011
+ chunks.push(chunk);
1012
+ }
1013
+ downloaded += chunk.length;
1014
+ if (progressCallback) {
1015
+ if (downloaded - lastUpdate >= 65536 || downloaded === totalSize) {
1016
+ progressCallback(downloaded, totalSize);
1017
+ lastUpdate = downloaded;
1018
+ }
1019
+ }
1020
+ else if (progressBar) {
1021
+ progressBar.increment(chunk.length);
1022
+ }
1023
+ else if (totalSize) {
1024
+ const pct = (downloaded / totalSize) * 100;
1025
+ process.stdout.write(`\r${desc}: ${pct.toFixed(0)}%`);
1026
+ }
1027
+ }
1028
+ }
1029
+ finally {
1030
+ progressBar?.stop();
1031
+ }
1032
+ if (!progressCallback && !bar) {
1033
+ process.stdout.write(desc ? `\r${desc}: Complete\n` : "\n");
1034
+ }
1035
+ return Buffer.concat(chunks);
1036
+ }
1037
+ /**
1038
+ * chmod -R 755 on POSIX so the freshly-extracted binaries are executable.
1039
+ * (The zip does not carry usable permission bits on every platform.)
1040
+ */
1041
+ export function makeExecutable(dir) {
1042
+ if (OS_NAME === "win")
1043
+ return;
1044
+ try {
1045
+ execFileSync("chmod", ["-R", "755", dir]);
1046
+ }
1047
+ catch (error) {
1048
+ rprint(`Warning: could not chmod ${dir}: ${error}`, "yellow");
1049
+ }
1050
+ }
1051
+ /**
1052
+ * Format an asset timestamp as "Mon D", or "Mon D, YYYY" when the year differs.
1053
+ */
1054
+ export function formatAssetDate(iso, now) {
1055
+ if (!iso)
1056
+ return "";
1057
+ const dt = new Date(iso);
1058
+ if (Number.isNaN(dt.getTime()))
1059
+ return "";
1060
+ const currentYear = (now ?? new Date()).getFullYear();
1061
+ const month = dt.toLocaleString("en-US", { month: "short" });
1062
+ if (dt.getFullYear() === currentYear) {
1063
+ return `${month} ${dt.getDate()}`;
1064
+ }
1065
+ return `${month} ${dt.getDate()}, ${dt.getFullYear()}`;
1066
+ }