@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
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Browser profiles and the leases on them, under `NAMZU_HOME/browser`:
3
+ *
4
+ * ```text
5
+ * browser/
6
+ * profiles/<name>.json the descriptor
7
+ * profiles/<name>/ the browser's user data directory (0700)
8
+ * leases/<name>/<pid>-<session>.json
9
+ * ```
10
+ *
11
+ * A profile of the Windows engine (WSL driving the Windows browser) keeps its
12
+ * user data on the Windows side, under
13
+ * `%LOCALAPPDATA%\namzu\browser\profiles\<name>`; only the descriptor is
14
+ * here, and its `userDataDir` is that Windows path.
15
+ *
16
+ * A profile is where a site's sign-in lives: the operator signs in once in
17
+ * a visible window, and every later run reuses the cookies. Every directory
18
+ * here is created 0700, because what is inside is as good as a password.
19
+ */
20
+ /** Profile names: lowercase words joined by single hyphens. */
21
+ export declare const BROWSER_PROFILE_NAME: RegExp;
22
+ export declare const DEFAULT_BROWSER_PROFILE = "default";
23
+ export interface BrowserProfileDescriptor {
24
+ readonly v: 1;
25
+ readonly name: string;
26
+ /** The engine whose browser owns the user data directory. */
27
+ readonly engine: 'local' | 'windows-cdp';
28
+ /** The browser's user data directory, in the engine's own path syntax. */
29
+ readonly userDataDir: string;
30
+ /** `chrome`, `msedge` or `chromium`. */
31
+ readonly browser: string;
32
+ readonly createdAt: string;
33
+ readonly lastLoginAt?: string;
34
+ }
35
+ export declare class BrowserProfileError extends Error {
36
+ readonly name = "BrowserProfileError";
37
+ }
38
+ export declare class BrowserProfileStore {
39
+ readonly home: string;
40
+ readonly root: string;
41
+ /** `home` is `NAMZU_HOME`. */
42
+ constructor(home: string);
43
+ /** Where a local engine keeps this profile's user data. */
44
+ localUserDataDir(name: string): string;
45
+ get(name: string): BrowserProfileDescriptor | undefined;
46
+ list(): BrowserProfileDescriptor[];
47
+ /**
48
+ * The profile's descriptor, created with a 0700 local user data directory
49
+ * when it does not exist yet.
50
+ */
51
+ ensureLocal(name: string, browser: string, now?: Date): BrowserProfileDescriptor;
52
+ /**
53
+ * The descriptor of a Windows-engine profile whose user data directory the
54
+ * bridge reported, created when it does not exist yet.
55
+ */
56
+ ensureWindows(name: string, browser: string, userDataDir: string, now?: Date): BrowserProfileDescriptor;
57
+ /** Record a completed sign-in. */
58
+ markLogin(name: string, now?: Date): BrowserProfileDescriptor;
59
+ /**
60
+ * Delete the descriptor and the profile's user data: a local profile's
61
+ * directory, or a Windows-engine profile's through the drive mount
62
+ * (`mountRoot`, `/mnt/` by default), and only when that directory is a
63
+ * namzu profile directory (`…\namzu\browser\profiles\<name>`). Refused
64
+ * while any live process holds a lease on it.
65
+ */
66
+ remove(name: string, leases?: BrowserLeaseStore, options?: {
67
+ mountRoot?: string;
68
+ }): boolean;
69
+ }
70
+ export interface BrowserLeaseRecord {
71
+ readonly v: 1;
72
+ readonly profile: string;
73
+ readonly pid: number;
74
+ readonly session: string;
75
+ readonly acquiredAt: string;
76
+ }
77
+ /** A held lease. `release` returns whether it was the last live one on the profile. */
78
+ export interface BrowserLease {
79
+ readonly profile: string;
80
+ readonly id: string;
81
+ release(): {
82
+ last: boolean;
83
+ };
84
+ }
85
+ /** Is `pid` a live process? A process we may not signal is alive. */
86
+ export declare function processAlive(pid: number): boolean;
87
+ export declare class BrowserLeaseStore {
88
+ readonly home: string;
89
+ private readonly alive;
90
+ readonly root: string;
91
+ constructor(home: string, alive?: (pid: number) => boolean);
92
+ private dir;
93
+ /** Live leases on `profile`, as `<pid>-<session>`. Stale ones are removed on the way. */
94
+ holders(profile: string): string[];
95
+ /**
96
+ * Take a lease for this process and `session`. With `exclusive`, any live
97
+ * lease by another holder — another process, or another session of this
98
+ * one — is a {@link ProfileBusyError}: a local profile directory can be
99
+ * open in one browser at a time.
100
+ */
101
+ acquire(profile: string, session: string, options?: {
102
+ exclusive?: boolean;
103
+ pid?: number;
104
+ now?: Date;
105
+ }): BrowserLease;
106
+ }
107
+ //# sourceMappingURL=profiles.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"profiles.d.ts","sourceRoot":"","sources":["../src/profiles.ts"],"names":[],"mappings":"AAeA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,+DAA+D;AAC/D,eAAO,MAAM,oBAAoB,QAA+B,CAAA;AAEhE,eAAO,MAAM,uBAAuB,YAAY,CAAA;AAEhD,MAAM,WAAW,wBAAwB;IACxC,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAA;IACb,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,6DAA6D;IAC7D,QAAQ,CAAC,MAAM,EAAE,OAAO,GAAG,aAAa,CAAA;IACxC,0EAA0E;IAC1E,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;IAC5B,wCAAwC;IACxC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,SAAS,E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M,WAAW,YAAY;IAC5B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;IACnB,OAAO,IAAI;QAAE,IAAI,EAAE,OAAO,CAAA;KAAE,CAAA;CAC5B;AAED,qEAAqE;AACrE,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAQjD;AAID,qBAAa,iBAAiB;IAI5B,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB,OAAO,CAAC,QAAQ,CAAC,KAAK;IAJvB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;gBAGX,IAAI,EAAE,MAAM,EACJ,KAAK,GAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAsB;IAKhE,OAAO,CAAC,GAAG;IAKX,yFAAyF;IACzF,OAAO,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE;IAkBlC;;;;;OAKG;IACH,OAAO,CACN,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,OAAO,GAAE;QAAE,SAAS,CAAC,EAAE,OAAO,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,IAAI,CAAA;KAAO,GAC7D,YAAY;CAyCf"}
@@ -0,0 +1,312 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { chmodSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { ProfileBusyError } from './errors.js';
5
+ import { DEFAULT_WSL_MOUNT_ROOT, windowsPathToWsl } from './wsl.js';
6
+ /**
7
+ * Browser profiles and the leases on them, under `NAMZU_HOME/browser`:
8
+ *
9
+ * ```text
10
+ * browser/
11
+ * profiles/<name>.json the descriptor
12
+ * profiles/<name>/ the browser's user data directory (0700)
13
+ * leases/<name>/<pid>-<session>.json
14
+ * ```
15
+ *
16
+ * A profile of the Windows engine (WSL driving the Windows browser) keeps its
17
+ * user data on the Windows side, under
18
+ * `%LOCALAPPDATA%\namzu\browser\profiles\<name>`; only the descriptor is
19
+ * here, and its `userDataDir` is that Windows path.
20
+ *
21
+ * A profile is where a site's sign-in lives: the operator signs in once in
22
+ * a visible window, and every later run reuses the cookies. Every directory
23
+ * here is created 0700, because what is inside is as good as a password.
24
+ */
25
+ /** Profile names: lowercase words joined by single hyphens. */
26
+ export const BROWSER_PROFILE_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
27
+ export const DEFAULT_BROWSER_PROFILE = 'default';
28
+ export class BrowserProfileError extends Error {
29
+ name = 'BrowserProfileError';
30
+ }
31
+ function assertName(name) {
32
+ if (name.length > 64 || !BROWSER_PROFILE_NAME.test(name)) {
33
+ throw new BrowserProfileError(`"${name}" is not a profile name: use lowercase letters, digits and single hyphens, at most 64 characters.`);
34
+ }
35
+ }
36
+ function ensurePrivateDir(path) {
37
+ mkdirSync(path, { recursive: true, mode: 0o700 });
38
+ const stat = lstatSync(path);
39
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
40
+ throw new BrowserProfileError(`${path} is not a real directory.`);
41
+ }
42
+ if (process.platform !== 'win32' && (stat.mode & 0o077) !== 0)
43
+ chmodSync(path, 0o700);
44
+ }
45
+ function writeJsonAtomic(path, value) {
46
+ const temp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
47
+ writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
48
+ renameSync(temp, path);
49
+ }
50
+ function isDescriptor(value, name) {
51
+ if (typeof value !== 'object' || value === null)
52
+ return false;
53
+ const v = value;
54
+ return (v.v === 1 &&
55
+ v.name === name &&
56
+ (v.engine === 'local' || v.engine === 'windows-cdp') &&
57
+ typeof v.userDataDir === 'string' &&
58
+ typeof v.browser === 'string' &&
59
+ typeof v.createdAt === 'string');
60
+ }
61
+ export class BrowserProfileStore {
62
+ home;
63
+ root;
64
+ /** `home` is `NAMZU_HOME`. */
65
+ constructor(home) {
66
+ this.home = home;
67
+ this.root = join(home, 'browser', 'profiles');
68
+ }
69
+ /** Where a local engine keeps this profile's user data. */
70
+ localUserDataDir(name) {
71
+ assertName(name);
72
+ return join(this.root, name);
73
+ }
74
+ get(name) {
75
+ assertName(name);
76
+ let text;
77
+ try {
78
+ text = readFileSync(join(this.root, `${name}.json`), 'utf8');
79
+ }
80
+ catch {
81
+ return undefined;
82
+ }
83
+ let parsed;
84
+ try {
85
+ parsed = JSON.parse(text);
86
+ }
87
+ catch {
88
+ throw new BrowserProfileError(`The descriptor of browser profile "${name}" is not JSON.`);
89
+ }
90
+ if (!isDescriptor(parsed, name)) {
91
+ throw new BrowserProfileError(`The descriptor of browser profile "${name}" is not readable.`);
92
+ }
93
+ return parsed;
94
+ }
95
+ list() {
96
+ let entries;
97
+ try {
98
+ entries = readdirSync(this.root);
99
+ }
100
+ catch {
101
+ return [];
102
+ }
103
+ const out = [];
104
+ for (const entry of entries.sort()) {
105
+ if (!entry.endsWith('.json'))
106
+ continue;
107
+ const name = entry.slice(0, -'.json'.length);
108
+ if (!BROWSER_PROFILE_NAME.test(name))
109
+ continue;
110
+ try {
111
+ const descriptor = this.get(name);
112
+ if (descriptor)
113
+ out.push(descriptor);
114
+ }
115
+ catch {
116
+ // An unreadable descriptor is skipped in a listing; `get` reports it.
117
+ }
118
+ }
119
+ return out;
120
+ }
121
+ /**
122
+ * The profile's descriptor, created with a 0700 local user data directory
123
+ * when it does not exist yet.
124
+ */
125
+ ensureLocal(name, browser, now = new Date()) {
126
+ const existing = this.get(name);
127
+ if (existing) {
128
+ if (existing.engine !== 'local') {
129
+ throw new BrowserProfileError(`Browser profile "${name}" belongs to the ${existing.engine} engine, not this local browser. Use another profile name.`);
130
+ }
131
+ ensurePrivateDir(existing.userDataDir);
132
+ return existing;
133
+ }
134
+ ensurePrivateDir(join(this.home, 'browser'));
135
+ ensurePrivateDir(this.root);
136
+ const userDataDir = this.localUserDataDir(name);
137
+ ensurePrivateDir(userDataDir);
138
+ const descriptor = {
139
+ v: 1,
140
+ name,
141
+ engine: 'local',
142
+ userDataDir,
143
+ browser,
144
+ createdAt: now.toISOString(),
145
+ };
146
+ writeJsonAtomic(join(this.root, `${name}.json`), descriptor);
147
+ return descriptor;
148
+ }
149
+ /**
150
+ * The descriptor of a Windows-engine profile whose user data directory the
151
+ * bridge reported, created when it does not exist yet.
152
+ */
153
+ ensureWindows(name, browser, userDataDir, now = new Date()) {
154
+ const existing = this.get(name);
155
+ if (existing) {
156
+ if (existing.engine !== 'windows-cdp') {
157
+ throw new BrowserProfileError(`Browser profile "${name}" belongs to the ${existing.engine} engine, not the Windows browser. Use another profile name.`);
158
+ }
159
+ if (existing.userDataDir === userDataDir)
160
+ return existing;
161
+ const moved = { ...existing, userDataDir };
162
+ writeJsonAtomic(join(this.root, `${name}.json`), moved);
163
+ return moved;
164
+ }
165
+ ensurePrivateDir(join(this.home, 'browser'));
166
+ ensurePrivateDir(this.root);
167
+ const descriptor = {
168
+ v: 1,
169
+ name,
170
+ engine: 'windows-cdp',
171
+ userDataDir,
172
+ browser,
173
+ createdAt: now.toISOString(),
174
+ };
175
+ writeJsonAtomic(join(this.root, `${name}.json`), descriptor);
176
+ return descriptor;
177
+ }
178
+ /** Record a completed sign-in. */
179
+ markLogin(name, now = new Date()) {
180
+ const existing = this.get(name);
181
+ if (!existing)
182
+ throw new BrowserProfileError(`There is no browser profile "${name}".`);
183
+ const next = { ...existing, lastLoginAt: now.toISOString() };
184
+ writeJsonAtomic(join(this.root, `${name}.json`), next);
185
+ return next;
186
+ }
187
+ /**
188
+ * Delete the descriptor and the profile's user data: a local profile's
189
+ * directory, or a Windows-engine profile's through the drive mount
190
+ * (`mountRoot`, `/mnt/` by default), and only when that directory is a
191
+ * namzu profile directory (`…\namzu\browser\profiles\<name>`). Refused
192
+ * while any live process holds a lease on it.
193
+ */
194
+ remove(name, leases = new BrowserLeaseStore(this.home), options = {}) {
195
+ const existing = this.get(name);
196
+ if (!existing)
197
+ return false;
198
+ const holders = leases.holders(name);
199
+ if (holders.length > 0)
200
+ throw new ProfileBusyError(name, holders);
201
+ if (existing.engine === 'local') {
202
+ rmSync(existing.userDataDir, { recursive: true, force: true });
203
+ }
204
+ else {
205
+ const suffix = `\\namzu\\browser\\profiles\\${name}`;
206
+ const local = existing.userDataDir.toLowerCase().endsWith(suffix)
207
+ ? windowsPathToWsl(existing.userDataDir, options.mountRoot ?? DEFAULT_WSL_MOUNT_ROOT)
208
+ : undefined;
209
+ if (local)
210
+ rmSync(local, { recursive: true, force: true });
211
+ }
212
+ rmSync(join(this.root, `${name}.json`), { force: true });
213
+ return true;
214
+ }
215
+ }
216
+ /** Is `pid` a live process? A process we may not signal is alive. */
217
+ export function processAlive(pid) {
218
+ if (!Number.isInteger(pid) || pid <= 0)
219
+ return false;
220
+ try {
221
+ process.kill(pid, 0);
222
+ return true;
223
+ }
224
+ catch (error) {
225
+ return error.code === 'EPERM';
226
+ }
227
+ }
228
+ const SESSION_ID = /^[A-Za-z0-9_-]{1,64}$/;
229
+ export class BrowserLeaseStore {
230
+ home;
231
+ alive;
232
+ root;
233
+ constructor(home, alive = processAlive) {
234
+ this.home = home;
235
+ this.alive = alive;
236
+ this.root = join(home, 'browser', 'leases');
237
+ }
238
+ dir(profile) {
239
+ assertName(profile);
240
+ return join(this.root, profile);
241
+ }
242
+ /** Live leases on `profile`, as `<pid>-<session>`. Stale ones are removed on the way. */
243
+ holders(profile) {
244
+ const dir = this.dir(profile);
245
+ let entries;
246
+ try {
247
+ entries = readdirSync(dir);
248
+ }
249
+ catch {
250
+ return [];
251
+ }
252
+ const live = [];
253
+ for (const entry of entries.sort()) {
254
+ const match = /^(\d+)-([A-Za-z0-9_-]+)\.json$/.exec(entry);
255
+ if (!match)
256
+ continue;
257
+ if (this.alive(Number(match[1])))
258
+ live.push(`${match[1]}-${match[2]}`);
259
+ else
260
+ rmSync(join(dir, entry), { force: true });
261
+ }
262
+ return live;
263
+ }
264
+ /**
265
+ * Take a lease for this process and `session`. With `exclusive`, any live
266
+ * lease by another holder — another process, or another session of this
267
+ * one — is a {@link ProfileBusyError}: a local profile directory can be
268
+ * open in one browser at a time.
269
+ */
270
+ acquire(profile, session, options = {}) {
271
+ if (!SESSION_ID.test(session)) {
272
+ throw new BrowserProfileError(`"${session}" is not a usable session id for a lease.`);
273
+ }
274
+ const pid = options.pid ?? process.pid;
275
+ const id = `${pid}-${session}`;
276
+ const dir = this.dir(profile);
277
+ ensurePrivateDir(join(this.home, 'browser'));
278
+ ensurePrivateDir(this.root);
279
+ ensurePrivateDir(dir);
280
+ const record = {
281
+ v: 1,
282
+ profile,
283
+ pid,
284
+ session,
285
+ acquiredAt: (options.now ?? new Date()).toISOString(),
286
+ };
287
+ const path = join(dir, `${id}.json`);
288
+ writeJsonAtomic(path, record);
289
+ // Written first, checked second: two processes racing both see each
290
+ // other and both refuse, rather than both seeing nothing.
291
+ if (options.exclusive) {
292
+ const others = this.holders(profile).filter((holder) => holder !== id);
293
+ if (others.length > 0) {
294
+ rmSync(path, { force: true });
295
+ throw new ProfileBusyError(profile, others);
296
+ }
297
+ }
298
+ let released = false;
299
+ return {
300
+ profile,
301
+ id,
302
+ release: () => {
303
+ if (!released) {
304
+ released = true;
305
+ rmSync(path, { force: true });
306
+ }
307
+ return { last: this.holders(profile).length === 0 };
308
+ },
309
+ };
310
+ }
311
+ }
312
+ //# sourceMappingURL=profiles.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"profiles.js","sourceRoot":"","sources":["../src/profiles.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,EACN,SAAS,EACT,SAAS,EACT,SAAS,EACT,YAAY,EACZ,WAAW,EACX,UAAU,EACV,MAAM,EACN,aAAa,GACb,MAAM,SAAS,CAAA;AAChB,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAA;AAC9C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C,eAAe,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;QAC7B,oEAAoE;QACpE,0DAA0D;QAC1D,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;YACvB,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,KAAK,EAAE,CAAC,CAAA;YACtE,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACvB,MAAM,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAA;gBAC7B,MAAM,IAAI,gBAAgB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;YAC5C,CAAC;QACF,CAAC;QACD,IAAI,QAAQ,GAAG,KAAK,CAAA;QACpB,OAAO;YACN,OAAO;YACP,EAAE;YACF,OAAO,EAAE,GAAG,EAAE;gBACb,IAAI,CAAC,QAAQ,EAAE,CAAC;oBACf,QAAQ,GAAG,IAAI,CAAA;oBACf,MAAM,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAA;gBAC9B,CAAC;gBACD,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAA;YACpD,CAAC;SACD,CAAA;IACF,CAAC;CACD"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * A WebSocket endpoint on WSL's `127.0.0.1` that Playwright's
3
+ * `connectOverCDP` can use, relaying every message to and from the bridge.
4
+ *
5
+ * The listening port is visible to every process in the distro, so the
6
+ * endpoint lives at a path of 32 random bytes (hex), a request anywhere else
7
+ * is answered 404 before any WebSocket is made, a request carrying an
8
+ * `Origin` header (every browser page's WebSocket does) is refused, and only
9
+ * one client is served at a time.
10
+ */
11
+ /** The bridge side of a relay. */
12
+ export interface CdpRelayPeer {
13
+ /** Send one CDP message to the browser. */
14
+ send(message: Buffer | string): boolean;
15
+ /** Called with every CDP message from the browser. Replaces any earlier listener. */
16
+ onMessage(listener: (message: Buffer) => void): void;
17
+ }
18
+ export interface CdpRelay {
19
+ /** `ws://127.0.0.1:<port>/<token>`. */
20
+ readonly url: string;
21
+ /** Stop listening and drop the client. */
22
+ close(): Promise<void>;
23
+ }
24
+ export declare function startCdpRelay(peer: CdpRelayPeer, options?: {
25
+ token?: string;
26
+ }): Promise<CdpRelay>;
27
+ //# sourceMappingURL=relay.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relay.d.ts","sourceRoot":"","sources":["../src/relay.ts"],"names":[],"mappings":"AAMA;;;;;;;;;GASG;AAEH,kCAAkC;AAClC,MAAM,WAAW,YAAY;IAC5B,2CAA2C;IAC3C,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAA;IACvC,qFAAqF;IACrF,SAAS,CAAC,QAAQ,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI,CAAA;CACpD;AAED,MAAM,WAAW,QAAQ;IACxB,uCAAuC;IACvC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,0CAA0C;IAC1C,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;CACtB;AAgBD,wBAAsB,aAAa,CAClC,IAAI,EAAE,YAAY,EAClB,OAAO,GAAE;IAAE,KAAK,CAAC,EAAE,MAAM,CAAA;CAAO,GAC9B,OAAO,CAAC,QAAQ,CAAC,CAmDnB"}
package/dist/relay.js ADDED
@@ -0,0 +1,69 @@
1
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
2
+ import { createServer } from 'node:http';
3
+ import { WebSocketServer } from 'ws';
4
+ /** Largest message relayed: a full-page screenshot of a very long page, base64. */
5
+ const MAX_MESSAGE_BYTES = 512 * 1024 * 1024;
6
+ function reject(socket, status, text) {
7
+ socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
8
+ socket.destroy();
9
+ }
10
+ function samePath(actual, expected) {
11
+ const a = Buffer.from(actual);
12
+ const b = Buffer.from(expected);
13
+ return a.length === b.length && timingSafeEqual(a, b);
14
+ }
15
+ export async function startCdpRelay(peer, options = {}) {
16
+ const token = options.token ?? randomBytes(32).toString('hex');
17
+ const path = `/${token}`;
18
+ const server = createServer((_request, response) => {
19
+ response.writeHead(404, { Connection: 'close' }).end();
20
+ });
21
+ const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE_BYTES });
22
+ let client;
23
+ peer.onMessage((message) => {
24
+ if (client && client.readyState === client.OPEN)
25
+ client.send(message, { binary: false });
26
+ });
27
+ server.on('upgrade', (request, socket, head) => {
28
+ if (!samePath(request.url ?? '', path))
29
+ return reject(socket, 404, 'Not Found');
30
+ if (request.headers.origin !== undefined)
31
+ return reject(socket, 403, 'Forbidden');
32
+ if (client)
33
+ return reject(socket, 409, 'Conflict');
34
+ wss.handleUpgrade(request, socket, head, (ws) => {
35
+ client = ws;
36
+ ws.on('message', (data) => {
37
+ const buffer = Array.isArray(data)
38
+ ? Buffer.concat(data)
39
+ : Buffer.isBuffer(data)
40
+ ? data
41
+ : Buffer.from(data);
42
+ peer.send(buffer);
43
+ });
44
+ ws.on('close', () => {
45
+ if (client === ws)
46
+ client = undefined;
47
+ });
48
+ ws.on('error', () => ws.terminate());
49
+ });
50
+ });
51
+ await new Promise((resolve, rejectListen) => {
52
+ server.once('error', rejectListen);
53
+ server.listen(0, '127.0.0.1', () => {
54
+ server.off('error', rejectListen);
55
+ resolve();
56
+ });
57
+ });
58
+ const { port } = server.address();
59
+ return {
60
+ url: `ws://127.0.0.1:${port}${path}`,
61
+ close: async () => {
62
+ client?.terminate();
63
+ client = undefined;
64
+ wss.close();
65
+ await new Promise((resolve) => server.close(() => resolve()));
66
+ },
67
+ };
68
+ }
69
+ //# sourceMappingURL=relay.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relay.js","sourceRoot":"","sources":["../src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CAAC,CAAA;YAClB,CAAC,CAAC,CAAA;YACF,EAAE,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE;gBACnB,IAAI,MAAM,KAAK,EAAE;oBAAE,MAAM,GAAG,SAAS,CAAA;YACtC,CAAC,CAAC,CAAA;YACF,EAAE,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,CAAA;QACrC,CAAC,CAAC,CAAA;IACH,CAAC,CAAC,CAAA;IAEF,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE;QACjD,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,YAAY,CAAC,CAAA;QAClC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE;YAClC,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,YAAY,CAAC,CAAA;YACjC,OAAO,EAAE,CAAA;QACV,CAAC,CAAC,CAAA;IACH,CAAC,CAAC,CAAA;IACF,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC,OAAO,EAAiB,CAAA;IAChD,OAAO;QACN,GAAG,EAAE,kBAAkB,IAAI,GAAG,IAAI,EAAE;QACpC,KAAK,EAAE,KAAK,IAAI,EAAE;YACjB,MAAM,EAAE,SAAS,EAAE,CAAA;YACnB,MAAM,GAAG,SAAS,CAAA;YAClB,GAAG,CAAC,KAAK,EAAE,CAAA;YACX,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAA;QACpE,CAAC;KACD,CAAA;AACF,CAAC"}
@@ -0,0 +1,101 @@
1
+ import type { BrowserRefDescription } from '@namzu/sdk';
2
+ import type { Locator, Page } from 'playwright-core';
3
+ import { type InvisibleBoxes, type Rect } from './page-scripts.js';
4
+ /**
5
+ * The accessibility snapshot, and the one place that knows how Playwright
6
+ * produces refs and resolves them.
7
+ *
8
+ * Two Playwright surfaces are used, and they are not equally stable:
9
+ *
10
+ * - `page.ariaSnapshotJSON({ mode: 'ai', boxes: true })` is public API in the
11
+ * pinned version: the accessibility tree with a `ref` on every element
12
+ * that can be targeted, stable across snapshots for an element that stays.
13
+ * - `page.locator('aria-ref=eN')` resolves a ref. That selector engine is
14
+ * NOT documented; it is what Playwright's own agent tooling uses. It is
15
+ * why `playwright-core` is pinned exactly, and the contract test in
16
+ * `__tests__/e2e` fails if an upgrade changes it. The fallback, should it
17
+ * go, is CDP `Accessibility.getFullAXTree` with `DOM.resolveNode` on each
18
+ * node's `backendDOMNodeId` — behind this module's same three functions.
19
+ *
20
+ * Observed in 1.63.0 and relied on here: a snapshot of a single element
21
+ * REPLACES the page's ref table (refs outside it stop resolving), so a
22
+ * region is always cut out of a whole-page snapshot on this side; and a
23
+ * snapshot hangs while a JavaScript dialog is open, so the host never takes
24
+ * one then.
25
+ */
26
+ /** The `playwright-core` version this module was verified against. */
27
+ export declare const PLAYWRIGHT_CORE_VERSION = "1.63.0";
28
+ /** One node of `ariaSnapshotJSON({ mode: 'ai' })`. Fields beyond these are ignored. */
29
+ export interface AriaNode {
30
+ readonly role: string;
31
+ readonly name?: string;
32
+ readonly ref?: string;
33
+ readonly box?: Rect;
34
+ readonly text?: string;
35
+ readonly url?: string;
36
+ readonly placeholder?: string;
37
+ readonly ariaHidden?: boolean;
38
+ readonly checked?: boolean | 'mixed';
39
+ readonly disabled?: boolean;
40
+ readonly expanded?: boolean;
41
+ readonly invalid?: boolean | string;
42
+ readonly level?: number;
43
+ readonly pressed?: boolean | 'mixed';
44
+ readonly selected?: boolean;
45
+ readonly children?: readonly (string | AriaNode)[];
46
+ }
47
+ /** What a rendered snapshot knows: its lines, and every ref it showed. */
48
+ export interface RenderedSnapshot {
49
+ readonly text: string;
50
+ readonly refs: ReadonlyMap<string, BrowserRefDescription>;
51
+ }
52
+ /** What a credential field's value is shown as. */
53
+ export declare const REDACTED = "[value hidden: password or one-time code]";
54
+ /**
55
+ * Render nodes as the snapshot text the model reads, one element per line:
56
+ *
57
+ * ```text
58
+ * - link "Pricing" [ref=e7]:
59
+ * - /url: /pricing
60
+ * - textbox "Email" [ref=e9]
61
+ * ```
62
+ *
63
+ * Dropped: `aria-hidden` subtrees, and the own text of nodes nobody can see
64
+ * (their visible children are kept, one level up). With `rootRef`, only that
65
+ * element's subtree; `undefined` when the ref is not in the tree.
66
+ */
67
+ export declare function renderAriaTree(nodes: readonly (string | AriaNode)[], hidden?: InvisibleBoxes, rootRef?: string, redact?: ReadonlySet<string>): RenderedSnapshot | undefined;
68
+ /**
69
+ * Take a whole-page snapshot. `ariaSnapshotJSON` returns one root node or a
70
+ * list; either way the result is a list.
71
+ */
72
+ export declare function captureAriaTree(page: Page, timeoutMs: number): Promise<{
73
+ nodes: (string | AriaNode)[];
74
+ hidden: InvisibleBoxes;
75
+ redact: Set<string>;
76
+ }>;
77
+ /** The element a ref names, in whichever frame it lives. */
78
+ export declare function locateRef(page: Page, ref: string): Locator;
79
+ /** Longest snapshot text kept for paging, in characters. Past it: cut, with a note. */
80
+ export declare const SNAPSHOT_TOTAL_MAX_CHARS = 400000;
81
+ export interface SnapshotPage {
82
+ readonly text: string;
83
+ readonly nextCursor?: string;
84
+ }
85
+ /**
86
+ * Pages of one snapshot, cut at line boundaries. A cursor names the snapshot
87
+ * and the offset, so a cursor from an older snapshot is refused rather than
88
+ * silently reading the new page from the middle.
89
+ */
90
+ export declare class SnapshotPager {
91
+ private readonly pageChars;
92
+ private id;
93
+ private text;
94
+ constructor(pageChars: number);
95
+ /** Start a new snapshot and return its first page. */
96
+ start(text: string): SnapshotPage;
97
+ /** The page a cursor names, or `undefined` when the cursor is not from the latest snapshot. */
98
+ resume(cursor: string): SnapshotPage | undefined;
99
+ private pageAt;
100
+ }
101
+ //# sourceMappingURL=snapshot.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"snapshot.d.ts","source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