@webhands/core 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 (76) hide show
  1. package/dist/cookies-export.d.ts +56 -0
  2. package/dist/cookies-export.d.ts.map +1 -0
  3. package/dist/cookies-export.js +69 -0
  4. package/dist/cookies-export.js.map +1 -0
  5. package/dist/errors.d.ts +126 -0
  6. package/dist/errors.d.ts.map +1 -0
  7. package/dist/errors.js +135 -0
  8. package/dist/errors.js.map +1 -0
  9. package/dist/index.d.ts +16 -0
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +15 -0
  12. package/dist/index.js.map +1 -0
  13. package/dist/playwright-attach-transport.d.ts +28 -0
  14. package/dist/playwright-attach-transport.d.ts.map +1 -0
  15. package/dist/playwright-attach-transport.js +175 -0
  16. package/dist/playwright-attach-transport.js.map +1 -0
  17. package/dist/playwright-launch-transport.d.ts +90 -0
  18. package/dist/playwright-launch-transport.d.ts.map +1 -0
  19. package/dist/playwright-launch-transport.js +305 -0
  20. package/dist/playwright-launch-transport.js.map +1 -0
  21. package/dist/profile-location.d.ts +61 -0
  22. package/dist/profile-location.d.ts.map +1 -0
  23. package/dist/profile-location.js +61 -0
  24. package/dist/profile-location.js.map +1 -0
  25. package/dist/remote-session.d.ts +22 -0
  26. package/dist/remote-session.d.ts.map +1 -0
  27. package/dist/remote-session.js +57 -0
  28. package/dist/remote-session.js.map +1 -0
  29. package/dist/seam.d.ts +212 -0
  30. package/dist/seam.d.ts.map +1 -0
  31. package/dist/seam.js +25 -0
  32. package/dist/seam.js.map +1 -0
  33. package/dist/session-endpoint.d.ts +53 -0
  34. package/dist/session-endpoint.d.ts.map +1 -0
  35. package/dist/session-endpoint.js +75 -0
  36. package/dist/session-endpoint.js.map +1 -0
  37. package/dist/session-rpc.d.ts +82 -0
  38. package/dist/session-rpc.d.ts.map +1 -0
  39. package/dist/session-rpc.js +107 -0
  40. package/dist/session-rpc.js.map +1 -0
  41. package/dist/session-server.d.ts +79 -0
  42. package/dist/session-server.d.ts.map +1 -0
  43. package/dist/session-server.js +141 -0
  44. package/dist/session-server.js.map +1 -0
  45. package/dist/setup-profile.d.ts +84 -0
  46. package/dist/setup-profile.d.ts.map +1 -0
  47. package/dist/setup-profile.js +52 -0
  48. package/dist/setup-profile.js.map +1 -0
  49. package/dist/stub-transport.d.ts +26 -0
  50. package/dist/stub-transport.d.ts.map +1 -0
  51. package/dist/stub-transport.js +76 -0
  52. package/dist/stub-transport.js.map +1 -0
  53. package/dist/test-fixtures/fixture-pages.d.ts +12 -0
  54. package/dist/test-fixtures/fixture-pages.d.ts.map +1 -0
  55. package/dist/test-fixtures/fixture-pages.js +204 -0
  56. package/dist/test-fixtures/fixture-pages.js.map +1 -0
  57. package/dist/test-fixtures/fixture-server.d.ts +19 -0
  58. package/dist/test-fixtures/fixture-server.d.ts.map +1 -0
  59. package/dist/test-fixtures/fixture-server.js +41 -0
  60. package/dist/test-fixtures/fixture-server.js.map +1 -0
  61. package/package.json +34 -0
  62. package/src/cookies-export.ts +91 -0
  63. package/src/errors.ts +185 -0
  64. package/src/index.ts +89 -0
  65. package/src/playwright-attach-transport.ts +214 -0
  66. package/src/playwright-launch-transport.ts +363 -0
  67. package/src/profile-location.ts +92 -0
  68. package/src/remote-session.ts +66 -0
  69. package/src/seam.ts +222 -0
  70. package/src/session-endpoint.ts +104 -0
  71. package/src/session-rpc.ts +143 -0
  72. package/src/session-server.ts +231 -0
  73. package/src/setup-profile.ts +134 -0
  74. package/src/stub-transport.ts +100 -0
  75. package/src/test-fixtures/fixture-pages.ts +210 -0
  76. package/src/test-fixtures/fixture-server.ts +54 -0
@@ -0,0 +1,214 @@
1
+ import {
2
+ chromium,
3
+ type Browser,
4
+ type BrowserContext,
5
+ type Page as PwPage,
6
+ } from 'playwright';
7
+ import {AttachNoContextError, AttachNotChromiumError} from './errors.js';
8
+ import {
9
+ clickLocator,
10
+ resolveLocator,
11
+ waitFor,
12
+ } from './playwright-launch-transport.js';
13
+ import type {
14
+ Cookie,
15
+ OpenTarget,
16
+ Page,
17
+ Session,
18
+ Snapshot,
19
+ SnapshotOptions,
20
+ Transport,
21
+ WaitCondition,
22
+ } from './seam.js';
23
+
24
+ /**
25
+ * The `attach` concrete transport: connect (`chromium.connectOverCDP`) to a
26
+ * browser the USER already started with remote debugging enabled, and reuse the
27
+ * user's EXISTING authenticated context — `browser.contexts()[0]`, never
28
+ * `newContext()` — so the controller drives the live, logged-in tabs on the
29
+ * user's real fingerprint and IP (PRD "Solution, attach"; ADR-0002).
30
+ *
31
+ * CDP-attach is Chromium-only (ADR-0003: Firefox attaches via a different
32
+ * mechanism). That constraint is SURFACED as a typed `core` error
33
+ * ({@link AttachNotChromiumError}) rather than leaking any CDP/Chromium-only
34
+ * type into the seam: the Playwright/CDP types are confined to this module and
35
+ * the seam stays transport-neutral (ADR-0003).
36
+ *
37
+ * It handles ONLY `mode: 'attach'`. `mode: 'launch'` is a SEPARATE transport
38
+ * ({@link PlaywrightLaunchTransport}); calling `open` with `mode: 'launch'`
39
+ * here throws, because mixing the two open mechanisms in one transport is what
40
+ * ADR-0003's seam exists to avoid.
41
+ *
42
+ * There is NO browser-relaunch helper: a settled PRD decision is that the user
43
+ * starts their own browser with `--remote-debugging-port` and supplies the
44
+ * resulting endpoint (PRD "needsAnswers" #5). This transport only connects to a
45
+ * running one.
46
+ */
47
+ export class PlaywrightAttachTransport implements Transport {
48
+ async open(target: OpenTarget): Promise<Session> {
49
+ if (target.mode !== 'attach') {
50
+ throw new Error(
51
+ `PlaywrightAttachTransport only handles 'attach'; ` +
52
+ `'${target.mode}' is owned by the launch transport.`,
53
+ );
54
+ }
55
+
56
+ // `endpoint` is the opaque, transport-resolved remote-debugging endpoint
57
+ // (e.g. `http://127.0.0.1:9222`). The seam keeps it a plain string so no
58
+ // CDP type leaks (ADR-0003); this transport interprets it as a CDP URL.
59
+ const browser = await chromium.connectOverCDP(target.endpoint);
60
+
61
+ try {
62
+ // CDP-attach is Chromium-only. If the reached engine is not Chromium,
63
+ // refuse with a typed condition instead of driving an unsupported
64
+ // browser (Firefox attaches differently — ADR-0003).
65
+ const engine = browser.browserType().name();
66
+ if (engine !== 'chromium') {
67
+ throw new AttachNotChromiumError(engine);
68
+ }
69
+
70
+ // Reuse the EXISTING authenticated context, never `newContext()`
71
+ // (ADR-0002): a fresh context would discard the user's live login.
72
+ const context = browser.contexts()[0];
73
+ if (context === undefined) {
74
+ throw new AttachNoContextError(target.endpoint);
75
+ }
76
+
77
+ // Drive the context's existing active page; open one only if the
78
+ // browser exposes a context with no page yet (single active session in
79
+ // v1, PRD Out of Scope).
80
+ const pwPage = context.pages()[0] ?? (await context.newPage());
81
+ return makeAttachedSession(browser, pwPage);
82
+ } catch (cause) {
83
+ // On any open-time refusal, disconnect from the user's browser without
84
+ // closing it (a CDP connection close detaches; it does not kill the
85
+ // browser the user started).
86
+ await browser.close().catch(() => {});
87
+ throw cause;
88
+ }
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Wrap a CDP-attached browser into the seam's {@link Session}.
94
+ *
95
+ * `close()` DISCONNECTS the controller from the user's browser; it must not
96
+ * kill the browser the user started (`Browser.close()` on a `connectOverCDP`
97
+ * connection detaches rather than terminating the remote process). We resolve
98
+ * cookies through the reused context so they reflect the live, authenticated
99
+ * session.
100
+ */
101
+ function makeAttachedSession(browser: Browser, pwPage: PwPage): Session {
102
+ const context: BrowserContext = pwPage.context();
103
+ let closed = false;
104
+ const ensureOpen = () => {
105
+ if (closed) {
106
+ throw new Error('session is closed');
107
+ }
108
+ };
109
+
110
+ const page: Page = {
111
+ async navigate(url: string): Promise<void> {
112
+ ensureOpen();
113
+ // "Settled" = the `load` event; XHR/JS-rendered content that appears
114
+ // after load is the `wait` verb's job. Same rationale (and the
115
+ // no-`networkidle` reasoning) as the launch transport's `navigate`.
116
+ await pwPage.goto(url, {waitUntil: 'load'});
117
+ },
118
+ async snapshot(options?: SnapshotOptions): Promise<Snapshot> {
119
+ ensureOpen();
120
+ const url = pwPage.url();
121
+ if (options?.full === true) {
122
+ const content = await pwPage.evaluate(
123
+ () => document.documentElement.outerHTML,
124
+ );
125
+ return {url, view: 'full', content};
126
+ }
127
+ // Default: the token-cheap accessibility tree + visible text with stable
128
+ // `[ref=...]` refs (see the launch transport and `Snapshot` for the
129
+ // rationale; the string crosses the seam as opaque, transport-neutral
130
+ // text, ADR-0003).
131
+ const content = await pwPage.ariaSnapshot({mode: 'ai'});
132
+ return {url, view: 'accessibility', content};
133
+ },
134
+ // `resolveLocator`/`clickLocator`/`waitFor` are imported from the launch
135
+ // transport so both transports resolve locators and run the verbs through
136
+ // ONE path (no parallel addressing scheme; the forward-note).
137
+ async click(t): Promise<void> {
138
+ ensureOpen();
139
+ // Shared `clickLocator`: normal actionability-checked click with the
140
+ // hidden-element dispatch fallback (PRD story 8), identical to launch.
141
+ await clickLocator(pwPage, t);
142
+ },
143
+ async type(t, text): Promise<void> {
144
+ ensureOpen();
145
+ await resolveLocator(pwPage, t).fill(text);
146
+ },
147
+ async eval(expression: string): Promise<unknown> {
148
+ ensureOpen();
149
+ return pwPage.evaluate(expression);
150
+ },
151
+ async wait(condition: WaitCondition): Promise<void> {
152
+ ensureOpen();
153
+ // Identical to the launch transport (shared `waitFor`): selector /
154
+ // navigation / timeout, so the verb behaves the same on both.
155
+ await waitFor(pwPage, condition);
156
+ },
157
+ async cookies(): Promise<readonly Cookie[]> {
158
+ ensureOpen();
159
+ const raw = await context.cookies();
160
+ return raw.map(toSeamCookie);
161
+ },
162
+ async setCookies(cookies): Promise<void> {
163
+ ensureOpen();
164
+ await context.addCookies(cookies.map(fromSeamCookie));
165
+ },
166
+ };
167
+
168
+ return {
169
+ page,
170
+ async close(): Promise<void> {
171
+ if (closed) return;
172
+ closed = true;
173
+ // Detach from the user's browser; do NOT terminate it.
174
+ await browser.close();
175
+ },
176
+ };
177
+ }
178
+
179
+ /** Map a Playwright cookie to the transport-neutral seam {@link Cookie}. */
180
+ function toSeamCookie(c: {
181
+ name: string;
182
+ value: string;
183
+ domain?: string;
184
+ path?: string;
185
+ expires?: number;
186
+ httpOnly?: boolean;
187
+ secure?: boolean;
188
+ sameSite?: 'Strict' | 'Lax' | 'None';
189
+ }): Cookie {
190
+ return {
191
+ name: c.name,
192
+ value: c.value,
193
+ domain: c.domain,
194
+ path: c.path,
195
+ expires: c.expires,
196
+ httpOnly: c.httpOnly,
197
+ secure: c.secure,
198
+ sameSite: c.sameSite,
199
+ };
200
+ }
201
+
202
+ /** Map a seam {@link Cookie} to a Playwright cookie shape. */
203
+ function fromSeamCookie(c: Cookie) {
204
+ return {
205
+ name: c.name,
206
+ value: c.value,
207
+ domain: c.domain,
208
+ path: c.path,
209
+ expires: c.expires,
210
+ httpOnly: c.httpOnly,
211
+ secure: c.secure,
212
+ sameSite: c.sameSite,
213
+ };
214
+ }
@@ -0,0 +1,363 @@
1
+ import {stat} from 'node:fs/promises';
2
+ import {
3
+ chromium,
4
+ errors as pwErrors,
5
+ type BrowserContext,
6
+ type Page as PwPage,
7
+ } from 'playwright';
8
+ import {MissingBrowserBinaryError, MissingProfileError} from './errors.js';
9
+ import {
10
+ resolveProfileLocation,
11
+ type ProfileLocationOptions,
12
+ } from './profile-location.js';
13
+ import type {
14
+ Cookie,
15
+ OpenTarget,
16
+ Page,
17
+ Session,
18
+ Snapshot,
19
+ SnapshotOptions,
20
+ Transport,
21
+ WaitCondition,
22
+ } from './seam.js';
23
+
24
+ /**
25
+ * The v1 concrete transport: a Playwright browser the controller LAUNCHES
26
+ * against a dedicated, persistent profile directory it owns (PRD "Solution,
27
+ * launch"; ADR-0002). It implements the `core` {@link Transport}/`Driver` seam
28
+ * with NO Playwright/CDP types in its public surface (ADR-0003): the
29
+ * Playwright types are confined to this module.
30
+ *
31
+ * It handles ONLY `mode: 'launch'`. The `attach` mode (`connectOverCDP`) is a
32
+ * SEPARATE transport (task `attach-transport-cdp-chromium`); calling `open`
33
+ * with `mode: 'attach'` here throws, because mixing the two launch mechanisms
34
+ * in one transport is what ADR-0003's seam exists to avoid.
35
+ *
36
+ * Profile location is resolved from the constructor options (or the
37
+ * `WEBHANDS_HOME` env var, or `~/.webhands`). See
38
+ * {@link resolveProfileLocation}. Because that is a SHARED location, tests pass
39
+ * a temp `root` (or set the env var) and assert the real home is untouched.
40
+ */
41
+ export class PlaywrightLaunchTransport implements Transport {
42
+ readonly #location: ProfileLocationOptions;
43
+
44
+ /**
45
+ * @param location overrides for where profiles live (a `root` dir and/or an
46
+ * `env`). Omit in production to use `~/.webhands`; pass a temp
47
+ * `root` in tests to isolate the shared profile location.
48
+ */
49
+ constructor(location: ProfileLocationOptions = {}) {
50
+ this.#location = location;
51
+ }
52
+
53
+ async open(target: OpenTarget): Promise<Session> {
54
+ if (target.mode !== 'launch') {
55
+ throw new Error(
56
+ `PlaywrightLaunchTransport only handles 'launch'; ` +
57
+ `'${target.mode}' is owned by the attach transport.`,
58
+ );
59
+ }
60
+
61
+ const loc = resolveProfileLocation(target.profile, this.#location);
62
+
63
+ // A profile is "set up" iff its dedicated dir exists on disk. Creating it
64
+ // is the headed `setup-profile` flow's job (a later task); `launch`
65
+ // against a missing profile is the typed MissingProfileError so the CLI
66
+ // can tell the user to run `setup-profile` first (PRD story 17). We never
67
+ // create the dir here, so a `launch` typo cannot silently spawn a blank
68
+ // profile.
69
+ if (!(await isExistingDirectory(loc.profileDir))) {
70
+ throw new MissingProfileError(loc.profile, loc.profileDir);
71
+ }
72
+
73
+ const headless = target.headed !== true;
74
+
75
+ let context: BrowserContext;
76
+ try {
77
+ context = await chromium.launchPersistentContext(loc.profileDir, {
78
+ headless,
79
+ });
80
+ } catch (cause) {
81
+ if (isMissingBrowserBinary(cause)) {
82
+ throw new MissingBrowserBinaryError('chromium', undefined, {cause});
83
+ }
84
+ throw cause;
85
+ }
86
+
87
+ // launchPersistentContext always opens with exactly one page; reuse it as
88
+ // the single active page (PRD: single active session in v1). Create one if
89
+ // the build ever changes that invariant.
90
+ const pwPage = context.pages()[0] ?? (await context.newPage());
91
+ return makeSession(context, pwPage);
92
+ }
93
+ }
94
+
95
+ /** True iff `path` exists and is a directory. */
96
+ async function isExistingDirectory(path: string): Promise<boolean> {
97
+ try {
98
+ const s = await stat(path);
99
+ return s.isDirectory();
100
+ } catch {
101
+ return false;
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Recognise Playwright's "browser executable doesn't exist" failure. Playwright
107
+ * does not export a typed error for this, so we detect on the message (it
108
+ * instructs the user to run `playwright install`). We confine that brittle
109
+ * string match to this one spot and re-raise as a stable typed error.
110
+ */
111
+ function isMissingBrowserBinary(cause: unknown): boolean {
112
+ const message = cause instanceof Error ? cause.message : String(cause ?? '');
113
+ return (
114
+ /Executable doesn't exist/i.test(message) ||
115
+ /please run the following command to download new browsers/i.test(
116
+ message,
117
+ ) ||
118
+ /playwright install/i.test(message)
119
+ );
120
+ }
121
+
122
+ /** Wrap a live Playwright persistent context into the seam's {@link Session}. */
123
+ function makeSession(context: BrowserContext, pwPage: PwPage): Session {
124
+ let closed = false;
125
+ const ensureOpen = () => {
126
+ if (closed) {
127
+ throw new Error('session is closed');
128
+ }
129
+ };
130
+
131
+ const page: Page = {
132
+ async navigate(url: string): Promise<void> {
133
+ ensureOpen();
134
+ // "Settled" for `goto` = the `load` event: the document and its
135
+ // subresources have loaded (PRD story 6, "navigate ... and wait for it
136
+ // to settle"). We deliberately do NOT wait for `networkidle`:
137
+ // Playwright discourages it, and it hangs forever on pages with
138
+ // long-poll / streaming / analytics beacons (exactly the logged-in apps
139
+ // this tool targets). Content rendered AFTER load (XHR-injected prices,
140
+ // hydrated lists) is the job of the explicit `wait` verb (story 10), not
141
+ // of `goto`.
142
+ await pwPage.goto(url, {waitUntil: 'load'});
143
+ },
144
+ async snapshot(options?: SnapshotOptions): Promise<Snapshot> {
145
+ ensureOpen();
146
+ const url = pwPage.url();
147
+ if (options?.full === true) {
148
+ // `--full`: the raw DOM. `documentElement.outerHTML` is the serialized
149
+ // live DOM (post-script render), which is what an agent that wants the
150
+ // real HTML expects — not the original network response.
151
+ const content = await pwPage.evaluate(
152
+ () => document.documentElement.outerHTML,
153
+ );
154
+ return {url, view: 'full', content};
155
+ }
156
+ // Default: the token-cheap accessibility tree + visible text with stable
157
+ // `[ref=...]` element refs. Playwright's `ariaSnapshot({mode: 'ai'})`
158
+ // emits exactly that — a YAML aria tree (roles + accessible names +
159
+ // text) where each node carries a stable `[ref=eN]` reference, assigned
160
+ // deterministically by traversal order so re-snapshotting an unchanged
161
+ // page yields the same refs. The string crosses the seam as opaque,
162
+ // transport-neutral text (no Playwright type leaks, ADR-0003).
163
+ const content = await pwPage.ariaSnapshot({mode: 'ai'});
164
+ return {url, view: 'accessibility', content};
165
+ },
166
+ async click(t): Promise<void> {
167
+ ensureOpen();
168
+ await clickLocator(pwPage, t);
169
+ },
170
+ async type(t, text): Promise<void> {
171
+ ensureOpen();
172
+ await resolveLocator(pwPage, t).fill(text);
173
+ },
174
+ async eval(expression: string): Promise<unknown> {
175
+ ensureOpen();
176
+ // The `eval` escape hatch (PRD story 9): run the raw JS EXPRESSION in the
177
+ // page and return its serializable result. Playwright's `evaluate`
178
+ // already IS the seam's serialization contract (see {@link Page.eval}):
179
+ // it passes a string as an expression, awaits a returned Promise, and
180
+ // structurally clones the result out of the page by VALUE. That clone is
181
+ // richer than JSON: it preserves NaN/Infinity/BigInt and circular
182
+ // structures (back-refs become a `[Circular]` marker), yields `undefined`
183
+ // for functions/symbols, and returns an opaque preview string for a live
184
+ // host object (a DOM node never crosses the process boundary). A page-side
185
+ // throw rejects. We pass it straight through rather than re-encode it:
186
+ // wrapping the value in a transport-specific envelope would invent a
187
+ // dialect the seam deliberately avoids. The thrown error is a plain
188
+ // `Error`, so no Playwright/CDP type leaks across the seam (ADR-0003).
189
+ return pwPage.evaluate(expression);
190
+ },
191
+ async wait(condition: WaitCondition): Promise<void> {
192
+ ensureOpen();
193
+ await waitFor(pwPage, condition);
194
+ },
195
+ async cookies(): Promise<readonly Cookie[]> {
196
+ ensureOpen();
197
+ const raw = await context.cookies();
198
+ return raw.map(toSeamCookie);
199
+ },
200
+ async setCookies(cookies): Promise<void> {
201
+ ensureOpen();
202
+ await context.addCookies(cookies.map(fromSeamCookie));
203
+ },
204
+ };
205
+
206
+ return {
207
+ page,
208
+ async close(): Promise<void> {
209
+ if (closed) return;
210
+ closed = true;
211
+ await context.close();
212
+ },
213
+ };
214
+ }
215
+
216
+ /**
217
+ * Run the `wait` verb's three forms (PRD story 10) against a Playwright page.
218
+ *
219
+ * - `timeout` — pace by a fixed delay (`waitForTimeout`), so an agent can act
220
+ * like a human and let XHR-rendered content land.
221
+ * - `locator` — block until the addressed element appears (`Locator.waitFor()`),
222
+ * the form for content rendered AFTER `goto` settled on `load`.
223
+ * - `navigation` — block until the NEXT navigation settles to `load`. We use
224
+ * `waitForNavigation()` even though Playwright marks it `@deprecated` ("racy,
225
+ * use waitForURL"): that deprecation targets in-process TEST code that can arm
226
+ * the wait BEFORE the action and pass a target URL. Neither holds here. Across
227
+ * this seam verbs are DISCRETE sequential calls (`click` then `wait`), so we
228
+ * CANNOT arm before the trigger; and the realistic trigger is an async,
229
+ * JS-driven transition (a redirect / SPA route change that fires AFTER the
230
+ * agent's action, the "let XHR-rendered content load" case of story 10), so
231
+ * "wait for the NEXT navigation" is exactly right — whereas `waitForLoadState`
232
+ * would see the already-loaded current page and return before the pending
233
+ * transition. `waitForURL` is unusable because the verb has no target URL by
234
+ * design (the agent waits for "a navigation", not a known address). (See the
235
+ * task's ## Decisions note.)
236
+ *
237
+ * Shared by both Playwright transports so the verb behaviour stays identical
238
+ * (the forward-note's "do NOT write a parallel second implementation").
239
+ */
240
+ export async function waitFor(
241
+ page: PwPage,
242
+ condition: WaitCondition,
243
+ ): Promise<void> {
244
+ switch (condition.kind) {
245
+ case 'timeout':
246
+ await page.waitForTimeout(condition.ms);
247
+ return;
248
+ case 'locator':
249
+ await resolveLocator(page, condition.target).waitFor();
250
+ return;
251
+ case 'navigation':
252
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
253
+ await page.waitForNavigation();
254
+ return;
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Resolve a raw Playwright locator EXPRESSION (ADR-0004) against the page. The
260
+ * verb surface passes locator expressions like `getByRole('button', …)`; we
261
+ * evaluate them in a small sandbox where `page`/`p` is the page, so the full
262
+ * Playwright locator grammar is available without leaking the type across the
263
+ * seam.
264
+ *
265
+ * Exported (with {@link clickLocator}/{@link waitFor}) so the attach transport
266
+ * resolves locators IDENTICALLY — one resolution path, no parallel addressing
267
+ * scheme (the forward-note's "do NOT write a parallel second implementation").
268
+ */
269
+ export function resolveLocator(page: PwPage, expression: string) {
270
+ // eslint-disable-next-line no-new-func
271
+ const factory = new Function('page', 'p', `return (${expression});`) as (
272
+ page: PwPage,
273
+ p: PwPage,
274
+ ) => ReturnType<PwPage['locator']>;
275
+ return factory(page, page);
276
+ }
277
+
278
+ /**
279
+ * How long a normal, actionability-checked `click` may wait before we treat the
280
+ * element as un-clickable and fall back to a dispatched click. Short on purpose:
281
+ * a hidden custom input never becomes actionable, so the regular click would
282
+ * otherwise burn Playwright's full default timeout (30s) before the escape path
283
+ * runs. The visible-element happy path clicks immediately and never hits this;
284
+ * this bound is the latency cost paid ONLY on the hidden/non-actionable path,
285
+ * and is long enough to tolerate a slow-but-eventually-actionable element
286
+ * (animations, late layout) before deciding to dispatch.
287
+ */
288
+ const NORMAL_CLICK_TIMEOUT_MS = 1_000;
289
+
290
+ /**
291
+ * Run the `click` verb against a Playwright page (PRD story 8), shared by both
292
+ * Playwright transports so the verb behaves identically (mirrors {@link waitFor};
293
+ * the forward-note's "do NOT write a parallel second implementation").
294
+ *
295
+ * First try a normal `Locator.click()`, which AUTO-WAITS for the element to be
296
+ * visible and actionable — the right behaviour for a real button. A hidden
297
+ * custom input (the case the prd calls out) NEVER becomes actionable, so that
298
+ * click times out; on a Playwright `TimeoutError` we fall back to
299
+ * `dispatchEvent('click')`, which fires a click WITHOUT the actionability
300
+ * checks. The fallback is deliberately the documented Playwright escape (a
301
+ * sibling to the `eval` hatch, ADR-0004), not a reimplemented click: we keep
302
+ * the locator a raw resolved expression and only change HOW the resolved
303
+ * locator is clicked.
304
+ *
305
+ * Only a timeout triggers the fallback. The fallback `dispatchEvent` is itself
306
+ * bounded by the same short timeout, so a locator that resolves NO element (a
307
+ * bad locator) surfaces its timeout quickly instead of hanging the dispatch on
308
+ * Playwright's 30s default — the dispatch escape is for elements that EXIST but
309
+ * are not actionable (hidden custom inputs), not for absent ones.
310
+ */
311
+ export async function clickLocator(
312
+ page: PwPage,
313
+ expression: string,
314
+ ): Promise<void> {
315
+ const target = resolveLocator(page, expression);
316
+ try {
317
+ await target.click({timeout: NORMAL_CLICK_TIMEOUT_MS});
318
+ } catch (cause) {
319
+ if (!(cause instanceof pwErrors.TimeoutError)) {
320
+ throw cause;
321
+ }
322
+ // The element never became actionable (e.g. a hidden custom input). Fire
323
+ // the click without actionability checks, the prd's explicit escape path.
324
+ await target.dispatchEvent('click', {timeout: NORMAL_CLICK_TIMEOUT_MS});
325
+ }
326
+ }
327
+
328
+ /** Map a Playwright cookie to the transport-neutral seam {@link Cookie}. */
329
+ function toSeamCookie(c: {
330
+ name: string;
331
+ value: string;
332
+ domain?: string;
333
+ path?: string;
334
+ expires?: number;
335
+ httpOnly?: boolean;
336
+ secure?: boolean;
337
+ sameSite?: 'Strict' | 'Lax' | 'None';
338
+ }): Cookie {
339
+ return {
340
+ name: c.name,
341
+ value: c.value,
342
+ domain: c.domain,
343
+ path: c.path,
344
+ expires: c.expires,
345
+ httpOnly: c.httpOnly,
346
+ secure: c.secure,
347
+ sameSite: c.sameSite,
348
+ };
349
+ }
350
+
351
+ /** Map a seam {@link Cookie} to a Playwright cookie shape. */
352
+ function fromSeamCookie(c: Cookie) {
353
+ return {
354
+ name: c.name,
355
+ value: c.value,
356
+ domain: c.domain,
357
+ path: c.path,
358
+ expires: c.expires,
359
+ httpOnly: c.httpOnly,
360
+ secure: c.secure,
361
+ sameSite: c.sameSite,
362
+ };
363
+ }
@@ -0,0 +1,92 @@
1
+ import {homedir} from 'node:os';
2
+ import {join} from 'node:path';
3
+
4
+ /**
5
+ * Where the controller's dedicated profiles (and other config state) live.
6
+ *
7
+ * This is a SHARED/GLOBAL, per-user location: by default
8
+ * `~/.webhands`. Profiles are dedicated browser user-data dirs
9
+ * under `<root>/profiles/<name>` (PRD "Profile management"; ADR-0002: never the
10
+ * OS default Chrome profile). The endpoint file from ADR-0005 also lives under
11
+ * this root, owned by a later task.
12
+ *
13
+ * Because writing here touches a real, shared location, TESTS MUST override the
14
+ * root to a scratch dir and assert the real one is untouched. The override is
15
+ * the {@link CONTROLLER_HOME_ENV} environment variable (or an explicit
16
+ * `root` passed to {@link resolveProfileLocation}); nothing else points a
17
+ * launch at the real home.
18
+ */
19
+
20
+ /** The directory name appended to the user's home for the default root. */
21
+ export const DEFAULT_HOME_DIRNAME = '.webhands';
22
+
23
+ /**
24
+ * Environment variable that overrides the controller home root. Set this (to a
25
+ * temp dir) in tests, or to relocate state in production. When set to a
26
+ * non-empty value it fully replaces the `~/.webhands` default.
27
+ */
28
+ export const CONTROLLER_HOME_ENV = 'WEBHANDS_HOME';
29
+
30
+ /** The subdirectory under the home root that holds dedicated profiles. */
31
+ export const PROFILES_DIRNAME = 'profiles';
32
+
33
+ /** Inputs that influence where a profile resolves (all optional, for tests). */
34
+ export interface ProfileLocationOptions {
35
+ /**
36
+ * Explicit home root, highest precedence. When omitted, falls back to the
37
+ * {@link CONTROLLER_HOME_ENV} env var, then `~/.webhands`.
38
+ */
39
+ readonly root?: string;
40
+ /** Environment to read the override from. Defaults to `process.env`. */
41
+ readonly env?: NodeJS.ProcessEnv;
42
+ }
43
+
44
+ /** A resolved set of controller paths for a given profile name. */
45
+ export interface ProfileLocation {
46
+ /** The controller home root (e.g. `~/.webhands`). */
47
+ readonly homeRoot: string;
48
+ /** The directory holding all dedicated profiles (`<homeRoot>/profiles`). */
49
+ readonly profilesRoot: string;
50
+ /** The dedicated user-data dir for this profile (`<profilesRoot>/<name>`). */
51
+ readonly profileDir: string;
52
+ /** The profile name that was resolved. */
53
+ readonly profile: string;
54
+ }
55
+
56
+ /**
57
+ * Resolve the controller home root. Precedence:
58
+ * 1. an explicit `options.root`,
59
+ * 2. the {@link CONTROLLER_HOME_ENV} env var (if non-empty),
60
+ * 3. `~/.webhands`.
61
+ */
62
+ export function resolveHomeRoot(options: ProfileLocationOptions = {}): string {
63
+ if (options.root !== undefined && options.root !== '') {
64
+ return options.root;
65
+ }
66
+ const env = options.env ?? process.env;
67
+ const fromEnv = env[CONTROLLER_HOME_ENV];
68
+ if (fromEnv !== undefined && fromEnv !== '') {
69
+ return fromEnv;
70
+ }
71
+ return join(homedir(), DEFAULT_HOME_DIRNAME);
72
+ }
73
+
74
+ /**
75
+ * Resolve every path for a named profile. Does NOT touch the filesystem (no
76
+ * dir is created or checked here) so it is pure and safe to call freely; the
77
+ * transport decides what to do when the dir is absent (raise
78
+ * `MissingProfileError`) or present.
79
+ */
80
+ export function resolveProfileLocation(
81
+ profile: string,
82
+ options: ProfileLocationOptions = {},
83
+ ): ProfileLocation {
84
+ const homeRoot = resolveHomeRoot(options);
85
+ const profilesRoot = join(homeRoot, PROFILES_DIRNAME);
86
+ return {
87
+ homeRoot,
88
+ profilesRoot,
89
+ profileDir: join(profilesRoot, profile),
90
+ profile,
91
+ };
92
+ }