@namzu/browser 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 (74) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/LICENSE.md +110 -0
  3. package/README.md +149 -0
  4. package/dist/classifier.d.ts +70 -0
  5. package/dist/classifier.d.ts.map +1 -0
  6. package/dist/classifier.js +147 -0
  7. package/dist/classifier.js.map +1 -0
  8. package/dist/detect.d.ts +126 -0
  9. package/dist/detect.d.ts.map +1 -0
  10. package/dist/detect.js +282 -0
  11. package/dist/detect.js.map +1 -0
  12. package/dist/errors.d.ts +64 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/errors.js +99 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/host.d.ts +167 -0
  17. package/dist/host.d.ts.map +1 -0
  18. package/dist/host.js +1024 -0
  19. package/dist/host.js.map +1 -0
  20. package/dist/index.d.ts +17 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +10 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/page-scripts.d.ts +51 -0
  25. package/dist/page-scripts.d.ts.map +1 -0
  26. package/dist/page-scripts.js +123 -0
  27. package/dist/page-scripts.js.map +1 -0
  28. package/dist/policy.d.ts +61 -0
  29. package/dist/policy.d.ts.map +1 -0
  30. package/dist/policy.js +150 -0
  31. package/dist/policy.js.map +1 -0
  32. package/dist/profiles.d.ts +107 -0
  33. package/dist/profiles.d.ts.map +1 -0
  34. package/dist/profiles.js +312 -0
  35. package/dist/profiles.js.map +1 -0
  36. package/dist/relay.d.ts +27 -0
  37. package/dist/relay.d.ts.map +1 -0
  38. package/dist/relay.js +69 -0
  39. package/dist/relay.js.map +1 -0
  40. package/dist/snapshot.d.ts +101 -0
  41. package/dist/snapshot.d.ts.map +1 -0
  42. package/dist/snapshot.js +265 -0
  43. package/dist/snapshot.js.map +1 -0
  44. package/dist/windows-bridge-script.d.ts +29 -0
  45. package/dist/windows-bridge-script.d.ts.map +1 -0
  46. package/dist/windows-bridge-script.js +161 -0
  47. package/dist/windows-bridge-script.js.map +1 -0
  48. package/dist/windows-bridge.d.ts +120 -0
  49. package/dist/windows-bridge.d.ts.map +1 -0
  50. package/dist/windows-bridge.js +267 -0
  51. package/dist/windows-bridge.js.map +1 -0
  52. package/dist/windows-engine.d.ts +55 -0
  53. package/dist/windows-engine.d.ts.map +1 -0
  54. package/dist/windows-engine.js +154 -0
  55. package/dist/windows-engine.js.map +1 -0
  56. package/dist/wsl.d.ts +52 -0
  57. package/dist/wsl.d.ts.map +1 -0
  58. package/dist/wsl.js +134 -0
  59. package/dist/wsl.js.map +1 -0
  60. package/package.json +74 -0
  61. package/src/classifier.ts +191 -0
  62. package/src/detect.ts +432 -0
  63. package/src/errors.ts +121 -0
  64. package/src/host.ts +1217 -0
  65. package/src/index.ts +79 -0
  66. package/src/page-scripts.ts +154 -0
  67. package/src/policy.ts +190 -0
  68. package/src/profiles.ts +373 -0
  69. package/src/relay.ts +101 -0
  70. package/src/snapshot.ts +317 -0
  71. package/src/windows-bridge-script.ts +160 -0
  72. package/src/windows-bridge.ts +358 -0
  73. package/src/windows-engine.ts +208 -0
  74. package/src/wsl.ts +155 -0
package/src/detect.ts ADDED
@@ -0,0 +1,432 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
3
+ import {
4
+ DEFAULT_WSL_MOUNT_ROOT,
5
+ WSL_RUN_DIR,
6
+ type WslNetworkingMode,
7
+ findWslInteropSocket,
8
+ parseNetworkingModeOutput,
9
+ parseWslConfigNetworkingMode,
10
+ parseWslMountRoot,
11
+ wslPathToWindows,
12
+ } from './wsl.js'
13
+
14
+ /**
15
+ * Which browser runs, where, and whether its window is shown — decided from
16
+ * the environment before anything is launched.
17
+ *
18
+ * | Where namzu runs | Plan |
19
+ * | --- | --- |
20
+ * | WSL2 with interop and a Windows Chrome or Edge | `windows-cdp` — the Windows browser, driven over CDP |
21
+ * | WSL2 without either | `local` Chromium inside WSL (a warning says why); headed through WSLg when there is a display |
22
+ * | Linux with a display | `local`: Google Chrome if installed, else Playwright's Chromium |
23
+ * | Linux without a display | `local`, headless only |
24
+ * | macOS | `local`: Google Chrome if installed, else Playwright's Chromium |
25
+ * | Windows | `local`: Chrome, else Edge, else Playwright's Chromium |
26
+ *
27
+ * The `windows-cdp` engine starts the Windows browser through `powershell.exe`
28
+ * and talks CDP to it through that process's standard streams (see
29
+ * `windows-bridge.ts`), because WSL's NAT networking cannot reach Windows'
30
+ * `127.0.0.1`. Under mirrored networking it connects directly and keeps the
31
+ * bridge only to start and stop the browser.
32
+ */
33
+
34
+ /** `auto` follows the table; `windows` and `local` force one engine. */
35
+ export type BrowserEngineSetting = 'auto' | 'windows' | 'local'
36
+
37
+ /** `auto`: a window when there is a display and a person at it (`interactive`). */
38
+ export type BrowserHeadlessSetting = 'auto' | 'always' | 'never'
39
+
40
+ /** `interactive`: a person is at the terminal. `unattended`: a scheduled run. */
41
+ export type BrowserRunMode = 'interactive' | 'unattended'
42
+
43
+ export type BrowserHostPlatform = 'linux' | 'wsl' | 'darwin' | 'win32'
44
+
45
+ /** The file-system questions detection asks; injected so tests need no real machine. */
46
+ export interface BrowserEnvironmentProbes {
47
+ exists(path: string): boolean
48
+ /** The file's text, or `undefined` if it cannot be read. */
49
+ readFile(path: string): string | undefined
50
+ /** Entry names, or `[]` if the directory cannot be read. */
51
+ listDir(path: string): readonly string[]
52
+ /** Modification time in ms, or `undefined`. Absent: every file is equally old. */
53
+ modifiedMs?(path: string): number | undefined
54
+ /**
55
+ * Standard output of a short-lived program, or `undefined` if it failed.
56
+ * Absent: nothing is run (`wslinfo` is skipped and `.wslconfig` decides).
57
+ */
58
+ run?(file: string, args: readonly string[]): string | undefined
59
+ }
60
+
61
+ export interface DetectBrowserEnvironmentOptions {
62
+ readonly engine?: BrowserEngineSetting
63
+ readonly headless?: BrowserHeadlessSetting
64
+ readonly mode?: BrowserRunMode
65
+ /** Under WSL: which Windows browser to drive. Default Chrome, else Edge. */
66
+ readonly windowsBrowser?: 'chrome' | 'msedge'
67
+ }
68
+
69
+ /** A browser this process launches itself, with Playwright. */
70
+ export interface LocalBrowserPlan {
71
+ readonly engine: 'local'
72
+ readonly platform: BrowserHostPlatform
73
+ /** `chromium` is Playwright's own build, from its browser cache. */
74
+ readonly browser: 'chrome' | 'msedge' | 'chromium'
75
+ /** The Playwright channel for an installed browser; absent for Playwright's Chromium. */
76
+ readonly channel?: 'chrome' | 'msedge'
77
+ readonly headless: boolean
78
+ /** A display is available for a visible window. */
79
+ readonly display: boolean
80
+ readonly warnings: readonly string[]
81
+ /** Present when this plan cannot run at all. */
82
+ readonly unavailableReason?: string
83
+ }
84
+
85
+ /** The Windows browser, driven from WSL over CDP. */
86
+ export interface WindowsCdpBrowserPlan {
87
+ readonly engine: 'windows-cdp'
88
+ readonly platform: 'wsl'
89
+ readonly browser: 'chrome' | 'msedge'
90
+ /** The browser as WSL sees it (`/mnt/c/Program Files/…/chrome.exe`). */
91
+ readonly executable: string
92
+ /** The browser as Windows sees it (`C:\Program Files\…\chrome.exe`). */
93
+ readonly windowsExecutable: string
94
+ /** `powershell.exe`, absolute, as WSL sees it. */
95
+ readonly powershell: string
96
+ /** Where the Windows drives are mounted, with a trailing slash (`/mnt/`). */
97
+ readonly mountRoot: string
98
+ /** `mirrored` lets WSL reach Windows' `127.0.0.1` directly; anything else goes through the bridge. */
99
+ readonly networkingMode: WslNetworkingMode
100
+ /**
101
+ * The interop socket to hand a Windows program as `WSL_INTEROP`, when this
102
+ * process has none of its own (a systemd service). Absent when the
103
+ * environment's `WSL_INTEROP` works.
104
+ */
105
+ readonly interopSocket?: string
106
+ readonly headless: boolean
107
+ readonly display: true
108
+ readonly warnings: readonly string[]
109
+ readonly unavailableReason?: string
110
+ /** What to run instead when this engine is unavailable and was not forced. */
111
+ readonly fallback?: LocalBrowserPlan
112
+ }
113
+
114
+ export type BrowserEnginePlan = LocalBrowserPlan | WindowsCdpBrowserPlan
115
+
116
+ /** Probes over the real file system. */
117
+ export const nodeBrowserProbes: BrowserEnvironmentProbes = {
118
+ exists: (path) => {
119
+ try {
120
+ return existsSync(path)
121
+ } catch {
122
+ return false
123
+ }
124
+ },
125
+ readFile: (path) => {
126
+ try {
127
+ return readFileSync(path, 'utf8')
128
+ } catch {
129
+ return undefined
130
+ }
131
+ },
132
+ listDir: (path) => {
133
+ try {
134
+ return readdirSync(path)
135
+ } catch {
136
+ return []
137
+ }
138
+ },
139
+ modifiedMs: (path) => {
140
+ try {
141
+ return statSync(path).mtimeMs
142
+ } catch {
143
+ return undefined
144
+ }
145
+ },
146
+ run: (file, args) => {
147
+ try {
148
+ return execFileSync(file, [...args], {
149
+ encoding: 'utf8',
150
+ timeout: 3_000,
151
+ stdio: ['ignore', 'pipe', 'ignore'],
152
+ })
153
+ } catch {
154
+ return undefined
155
+ }
156
+ },
157
+ }
158
+
159
+ const WSL_POWERSHELL_TAIL = 'c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe'
160
+
161
+ /** Where the Windows browsers install, relative to the mount root. */
162
+ const WSL_WINDOWS_BROWSERS: readonly { browser: 'chrome' | 'msedge'; tail: string }[] = [
163
+ { browser: 'chrome', tail: 'c/Program Files/Google/Chrome/Application/chrome.exe' },
164
+ { browser: 'chrome', tail: 'c/Program Files (x86)/Google/Chrome/Application/chrome.exe' },
165
+ { browser: 'msedge', tail: 'c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe' },
166
+ { browser: 'msedge', tail: 'c/Program Files/Microsoft/Edge/Application/msedge.exe' },
167
+ ]
168
+
169
+ const WSLINFO = '/usr/bin/wslinfo'
170
+
171
+ /** Profile folders under `C:\Users` that are not a person's. */
172
+ const NOT_A_USER = new Set(['all users', 'default', 'default user', 'public', 'desktop.ini'])
173
+
174
+ /**
175
+ * The VM's networking mode: `wslinfo --networking-mode` when WSL has it;
176
+ * otherwise the one `.wslconfig` under `C:\Users` (when exactly one user has
177
+ * one); otherwise `unknown`, which is treated as NAT.
178
+ */
179
+ export function wslNetworkingMode(
180
+ probes: BrowserEnvironmentProbes,
181
+ mountRoot: string = DEFAULT_WSL_MOUNT_ROOT,
182
+ ): WslNetworkingMode {
183
+ if (probes.run && probes.exists(WSLINFO)) {
184
+ const mode = parseNetworkingModeOutput(probes.run(WSLINFO, ['--networking-mode']))
185
+ if (mode !== 'unknown') return mode
186
+ }
187
+ const users = `${mountRoot}c/Users`
188
+ const configs = probes
189
+ .listDir(users)
190
+ .filter((name) => !NOT_A_USER.has(name.toLowerCase()))
191
+ .map((name) => `${users}/${name}/.wslconfig`)
192
+ .filter((path) => probes.exists(path))
193
+ if (configs.length !== 1) return 'unknown'
194
+ return parseWslConfigNetworkingMode(probes.readFile(configs[0] as string))
195
+ }
196
+
197
+ /**
198
+ * The interop socket to give a Windows program: the environment's
199
+ * `WSL_INTEROP` when it exists, else one under `/run/WSL`.
200
+ */
201
+ export function wslInteropSocket(
202
+ env: NodeJS.ProcessEnv,
203
+ probes: BrowserEnvironmentProbes,
204
+ ): string | undefined {
205
+ if (env.WSL_INTEROP && probes.exists(env.WSL_INTEROP)) return env.WSL_INTEROP
206
+ const sockets = probes
207
+ .listDir(WSL_RUN_DIR)
208
+ .filter((name) => /^\d+_interop$/.test(name))
209
+ .map((name) => {
210
+ const path = `${WSL_RUN_DIR}/${name}`
211
+ return { path, mtimeMs: probes.modifiedMs?.(path) ?? 0 }
212
+ })
213
+ return findWslInteropSocket(sockets)
214
+ }
215
+
216
+ const LINUX_CHROME = ['/opt/google/chrome/chrome']
217
+ const DARWIN_CHROME = ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome']
218
+
219
+ function windowsBrowserPaths(
220
+ env: NodeJS.ProcessEnv,
221
+ browser: 'chrome' | 'msedge',
222
+ ): readonly string[] {
223
+ const roots = [env.PROGRAMFILES, env['PROGRAMFILES(X86)'], env.LOCALAPPDATA].filter(
224
+ (root): root is string => typeof root === 'string' && root.length > 0,
225
+ )
226
+ const tail =
227
+ browser === 'chrome'
228
+ ? '\\Google\\Chrome\\Application\\chrome.exe'
229
+ : '\\Microsoft\\Edge\\Application\\msedge.exe'
230
+ return roots.map((root) => `${root.replace(/[\\/]+$/, '')}${tail}`)
231
+ }
232
+
233
+ /** Is this Linux kernel WSL's? The environment variables are absent under a systemd service. */
234
+ export function isWsl(env: NodeJS.ProcessEnv, probes: BrowserEnvironmentProbes): boolean {
235
+ if (env.WSL_DISTRO_NAME || env.WSL_INTEROP) return true
236
+ const release = probes.readFile('/proc/sys/kernel/osrelease') ?? ''
237
+ return /microsoft|wsl/i.test(release)
238
+ }
239
+
240
+ /**
241
+ * Can this WSL process start Windows programs? The binfmt handler must be
242
+ * registered, and a socket must be reachable: `WSL_INTEROP`, or one under
243
+ * `/run/WSL` (all a systemd user service has).
244
+ */
245
+ export function wslInteropAvailable(
246
+ env: NodeJS.ProcessEnv,
247
+ probes: BrowserEnvironmentProbes,
248
+ ): boolean {
249
+ const registered =
250
+ probes.exists('/proc/sys/fs/binfmt_misc/WSLInterop') ||
251
+ probes.exists('/proc/sys/fs/binfmt_misc/WSLInterop-late')
252
+ if (!registered) return false
253
+ if (env.WSL_INTEROP && probes.exists(env.WSL_INTEROP)) return true
254
+ return probes.listDir('/run/WSL').some((name) => name.endsWith('_interop'))
255
+ }
256
+
257
+ function hasDisplay(env: NodeJS.ProcessEnv): boolean {
258
+ return Boolean(env.DISPLAY || env.WAYLAND_DISPLAY)
259
+ }
260
+
261
+ function headlessFor(
262
+ setting: BrowserHeadlessSetting,
263
+ mode: BrowserRunMode,
264
+ display: boolean,
265
+ ): { headless: boolean; unavailableReason?: string } {
266
+ if (setting === 'always') return { headless: true }
267
+ if (setting === 'never') {
268
+ return display
269
+ ? { headless: false }
270
+ : {
271
+ headless: false,
272
+ unavailableReason:
273
+ 'A visible browser window was asked for (headless: never), but there is no display: neither DISPLAY nor WAYLAND_DISPLAY is set. Run under a desktop session, with ssh -X, or with xvfb-run.',
274
+ }
275
+ }
276
+ return { headless: !(display && mode === 'interactive') }
277
+ }
278
+
279
+ function localPlan(
280
+ platform: BrowserHostPlatform,
281
+ env: NodeJS.ProcessEnv,
282
+ probes: BrowserEnvironmentProbes,
283
+ options: Required<Omit<DetectBrowserEnvironmentOptions, 'windowsBrowser'>>,
284
+ warnings: string[],
285
+ ): LocalBrowserPlan {
286
+ const display = platform === 'darwin' || platform === 'win32' ? true : hasDisplay(env)
287
+ let browser: LocalBrowserPlan['browser'] = 'chromium'
288
+ if (platform === 'linux' || platform === 'wsl') {
289
+ if (LINUX_CHROME.some((p) => probes.exists(p))) browser = 'chrome'
290
+ } else if (platform === 'darwin') {
291
+ if (DARWIN_CHROME.some((p) => probes.exists(p))) browser = 'chrome'
292
+ } else if (windowsBrowserPaths(env, 'chrome').some((p) => probes.exists(p))) {
293
+ browser = 'chrome'
294
+ } else if (windowsBrowserPaths(env, 'msedge').some((p) => probes.exists(p))) {
295
+ browser = 'msedge'
296
+ }
297
+ if (!display) {
298
+ warnings.push(
299
+ 'No display (DISPLAY and WAYLAND_DISPLAY are unset): the browser runs headless, and signing in to a profile needs a machine with a display.',
300
+ )
301
+ }
302
+ const { headless, unavailableReason } = headlessFor(options.headless, options.mode, display)
303
+ return {
304
+ engine: 'local',
305
+ platform,
306
+ browser,
307
+ ...(browser === 'chromium' ? {} : { channel: browser }),
308
+ headless,
309
+ display,
310
+ warnings,
311
+ ...(unavailableReason !== undefined ? { unavailableReason } : {}),
312
+ }
313
+ }
314
+
315
+ /**
316
+ * The engine plan for this environment. Pure over its arguments: the
317
+ * environment, the platform, and the probes answer every question.
318
+ */
319
+ export function detectBrowserEnvironment(
320
+ env: NodeJS.ProcessEnv,
321
+ platform: NodeJS.Platform,
322
+ probes: BrowserEnvironmentProbes = nodeBrowserProbes,
323
+ options: DetectBrowserEnvironmentOptions = {},
324
+ ): BrowserEnginePlan {
325
+ const settings: Required<Omit<DetectBrowserEnvironmentOptions, 'windowsBrowser'>> = {
326
+ engine: options.engine ?? 'auto',
327
+ headless: options.headless ?? 'auto',
328
+ mode: options.mode ?? 'interactive',
329
+ }
330
+
331
+ if (platform === 'darwin' || platform === 'win32') {
332
+ const plan = localPlan(platform, env, probes, settings, [])
333
+ if (settings.engine === 'windows') {
334
+ return {
335
+ ...plan,
336
+ unavailableReason:
337
+ 'engine "windows" drives a Windows browser from WSL; this is not WSL. Use engine "auto" or "local".',
338
+ }
339
+ }
340
+ return plan
341
+ }
342
+ if (platform !== 'linux') {
343
+ return {
344
+ engine: 'local',
345
+ platform: 'linux',
346
+ browser: 'chromium',
347
+ headless: true,
348
+ display: false,
349
+ warnings: [],
350
+ unavailableReason: `The browser is not supported on ${platform}.`,
351
+ }
352
+ }
353
+
354
+ if (!isWsl(env, probes)) {
355
+ const plan = localPlan('linux', env, probes, settings, [])
356
+ if (settings.engine === 'windows') {
357
+ return {
358
+ ...plan,
359
+ unavailableReason:
360
+ 'engine "windows" drives a Windows browser from WSL; this is not WSL. Use engine "auto" or "local".',
361
+ }
362
+ }
363
+ return plan
364
+ }
365
+
366
+ // WSL.
367
+ if (settings.engine === 'local') return localPlan('wsl', env, probes, settings, [])
368
+ const mountRoot = parseWslMountRoot(probes.readFile('/etc/wsl.conf'))
369
+ const interop = wslInteropAvailable(env, probes)
370
+ const powershellPath = `${mountRoot}${WSL_POWERSHELL_TAIL}`
371
+ const powershell = probes.exists(powershellPath) ? powershellPath : undefined
372
+ const installed = WSL_WINDOWS_BROWSERS.map((b) => ({
373
+ browser: b.browser,
374
+ path: `${mountRoot}${b.tail}`,
375
+ })).filter((b) => probes.exists(b.path))
376
+ const preferred = options.windowsBrowser
377
+ const windowsBrowser =
378
+ (preferred ? installed.find((b) => b.browser === preferred) : undefined) ?? installed[0]
379
+ const warnings: string[] = []
380
+ if (preferred && windowsBrowser && windowsBrowser.browser !== preferred) {
381
+ warnings.push(
382
+ `${preferred === 'chrome' ? 'Google Chrome' : 'Microsoft Edge'} is not installed on Windows; using ${windowsBrowser.browser === 'chrome' ? 'Google Chrome' : 'Microsoft Edge'}.`,
383
+ )
384
+ }
385
+ if (!interop || !powershell || !windowsBrowser) {
386
+ const why = !interop
387
+ ? 'WSL interop is off, so Windows programs cannot be started'
388
+ : !powershell
389
+ ? `powershell.exe was not found at ${powershellPath}`
390
+ : 'no Windows Chrome or Edge was found under C:\\Program Files'
391
+ if (settings.engine === 'windows') {
392
+ return {
393
+ ...localPlan('wsl', env, probes, settings, []),
394
+ unavailableReason: `engine "windows" was asked for, but ${why}.`,
395
+ }
396
+ }
397
+ return localPlan('wsl', env, probes, settings, [
398
+ `Using Chromium inside WSL: ${why}. Sites see a Linux browser, and a visible window needs WSLg.`,
399
+ ])
400
+ }
401
+ // The Windows browser has the Windows desktop for a display, whatever
402
+ // WSLg says; headless follows the setting and the mode alone.
403
+ const { headless } = headlessFor(settings.headless, settings.mode, true)
404
+ const socket = wslInteropSocket(env, probes)
405
+ const windowsExecutable = wslPathToWindows(windowsBrowser.path, mountRoot) as string
406
+ return {
407
+ engine: 'windows-cdp',
408
+ platform: 'wsl',
409
+ browser: windowsBrowser.browser,
410
+ executable: windowsBrowser.path,
411
+ windowsExecutable,
412
+ powershell,
413
+ mountRoot,
414
+ networkingMode: wslNetworkingMode(probes, mountRoot),
415
+ ...(socket !== undefined && socket !== env.WSL_INTEROP ? { interopSocket: socket } : {}),
416
+ headless,
417
+ display: true,
418
+ warnings,
419
+ }
420
+ }
421
+
422
+ /**
423
+ * The plan to actually run: the plan itself, or its fallback when it is
424
+ * unavailable and has one. Still possibly unavailable — check
425
+ * `unavailableReason`.
426
+ */
427
+ export function runnableBrowserPlan(plan: BrowserEnginePlan): BrowserEnginePlan {
428
+ if (plan.unavailableReason !== undefined && plan.engine === 'windows-cdp' && plan.fallback) {
429
+ return plan.fallback
430
+ }
431
+ return plan
432
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,121 @@
1
+ import type {
2
+ BrowserActionName,
3
+ BrowserHumanRequired,
4
+ BrowserHumanRequiredReason,
5
+ BrowserOriginMismatch,
6
+ BrowserOutcomeUnknown,
7
+ BrowserSiteDenied,
8
+ BrowserStaleRef,
9
+ } from '@namzu/sdk'
10
+
11
+ /**
12
+ * The browser cannot run here: the engine is not installed, there is no
13
+ * display for a visible window, the engine this environment needs is not in
14
+ * this build. `reason` is a sentence for a person and ends with what to do.
15
+ */
16
+ export class BrowserUnavailableError extends Error {
17
+ override readonly name = 'BrowserUnavailableError'
18
+ readonly code = 'browser_unavailable' as const
19
+
20
+ constructor(readonly reason: string) {
21
+ super(reason)
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Another browser holds the profile. A local profile directory can be opened
27
+ * by one browser process at a time; `holders` names the processes that hold
28
+ * it, as `<pid>-<session>`.
29
+ */
30
+ export class ProfileBusyError extends Error {
31
+ override readonly name = 'ProfileBusyError'
32
+ readonly code = 'browser_profile_busy' as const
33
+
34
+ constructor(
35
+ readonly profile: string,
36
+ readonly holders: readonly string[],
37
+ ) {
38
+ super(
39
+ holders.length > 0
40
+ ? `The browser profile "${profile}" is in use by another namzu process (${holders.join(', ')}). Close that session, or use another profile.`
41
+ : `The browser profile "${profile}" is in use by another browser. Close it, or use another profile.`,
42
+ )
43
+ }
44
+ }
45
+
46
+ // ---------------------------------------------------------------------------
47
+ // The SDK's structural refusals, as classes. The tools recognise them by
48
+ // shape (`browserHostErrorOf`), so these only need to carry the fields.
49
+ // ---------------------------------------------------------------------------
50
+
51
+ export class BrowserOriginMismatchError extends Error implements BrowserOriginMismatch {
52
+ override readonly name = 'BrowserOriginMismatchError'
53
+ readonly code = 'browser_origin_mismatch' as const
54
+
55
+ constructor(
56
+ readonly expected: string,
57
+ readonly actual: string,
58
+ ) {
59
+ super(`The page is at ${actual || 'an unknown origin'}, not ${expected}. Nothing was done.`)
60
+ }
61
+ }
62
+
63
+ export class BrowserStaleRefError extends Error implements BrowserStaleRef {
64
+ override readonly name = 'BrowserStaleRefError'
65
+ readonly code = 'browser_stale_ref' as const
66
+
67
+ constructor(readonly ref: string) {
68
+ super(`Element ${ref} is not on the page any more. Nothing was done.`)
69
+ }
70
+ }
71
+
72
+ export class BrowserHumanRequiredError extends Error implements BrowserHumanRequired {
73
+ override readonly name = 'BrowserHumanRequiredError'
74
+ readonly code = 'browser_human_required' as const
75
+ readonly profile?: string
76
+ readonly loginCommand?: string
77
+
78
+ constructor(
79
+ readonly reason: BrowserHumanRequiredReason,
80
+ readonly origin: string,
81
+ options: { profile?: string; loginCommand?: string } = {},
82
+ ) {
83
+ super(`${origin || 'The page'} needs a person (${reason}).`)
84
+ if (options.profile !== undefined) this.profile = options.profile
85
+ if (options.loginCommand !== undefined) this.loginCommand = options.loginCommand
86
+ }
87
+ }
88
+
89
+ export class BrowserSiteDeniedError extends Error implements BrowserSiteDenied {
90
+ override readonly name = 'BrowserSiteDeniedError'
91
+ readonly code = 'browser_site_denied' as const
92
+
93
+ constructor(
94
+ readonly origin: string,
95
+ detail?: string,
96
+ ) {
97
+ super(detail ?? `${origin || 'This site'} is not allowed by the site rules.`)
98
+ }
99
+ }
100
+
101
+ export class BrowserOutcomeUnknownError extends Error implements BrowserOutcomeUnknown {
102
+ override readonly name = 'BrowserOutcomeUnknownError'
103
+ readonly code = 'browser_outcome_unknown' as const
104
+ readonly outcome = 'unknown' as const
105
+ readonly retrySafety = 'unsafe' as const
106
+
107
+ constructor(
108
+ readonly action: BrowserActionName,
109
+ cause: unknown,
110
+ ) {
111
+ super(
112
+ `browser_act "${action}" started and did not finish cleanly (${firstLine(cause)}). The page may already have changed; take a snapshot before deciding what to do, and do not repeat the action blindly.`,
113
+ )
114
+ }
115
+ }
116
+
117
+ function firstLine(cause: unknown): string {
118
+ const text = cause instanceof Error ? cause.message : String(cause)
119
+ const line = text.split('\n')[0] ?? ''
120
+ return line.length > 200 ? `${line.slice(0, 199)}…` : line
121
+ }