testsurfer 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,157 @@
1
- # Temporary Holding Version
1
+ # testsurfer
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ End-to-end testing for the web, driven by [vibesurfer](https://github.com/frane/vibesurfer).
4
+
5
+ testsurfer is lightweight. It drives the browser engine already on your machine through vibesurfer, a small native binary. Nothing bundles Chromium or Firefox or WebKit; you add one small dependency and get a real WebKit engine with fast cold starts and cheap CI.
6
+
7
+ Tests address the page through its accessibility tree. You assert on roles and labels instead of CSS selectors, so tests survive DOM and styling churn. And because the engine is a plain OS webview, no automation protocol is attached to the page: no WebDriver, no CDP, and `navigator.webdriver` is `undefined`.
8
+
9
+ ```ts
10
+ import { test, expect } from 'testsurfer';
11
+
12
+ test('login', async ({ page }) => {
13
+ await page.goto('https://example.com/login');
14
+ await page.getByRole('textbox', { name: 'Email' }).fill('a@b.com');
15
+ await page.getByRole('button', { name: 'Sign in' }).click();
16
+ await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
17
+ });
18
+ ```
19
+
20
+ Install it and run with node's built-in test runner:
21
+
22
+ ```sh
23
+ npm install -D testsurfer
24
+ node --test tests/
25
+ ```
26
+
27
+ Node 22.18 or newer runs the `.ts` test files directly.
28
+
29
+ ## How it works
30
+
31
+ vibesurfer is a daemon that owns one real WebKit engine and speaks a line protocol over a Unix socket. testsurfer is a TypeScript client for that protocol. It opens a session, resolves your locators against the live accessibility tree, and handles the daemon's optimistic-concurrency tokens internally. You never see a token, a ref, or a retry.
32
+
33
+ The daemon is fetched automatically. If `vs` is not on your PATH, testsurfer runs `npx vibesurfer@0.2.13` (pinned, checksum-verified) to download and start it. Set `TESTSURFER_VS` to point at a specific binary. testsurfer reads the daemon's protocol version and feature flags at launch and uses what it offers, so a newer `vs` on your PATH works too.
34
+
35
+ ## API
36
+
37
+ Locators resolve lazily at action time, against a fresh view:
38
+
39
+ - `page.getByRole(role, { name, exact, level })` matches ARIA roles (`button`, `textbox`, `heading`, `link`, ...). Name matching is whole-string and case-insensitive by default; `exact: true` makes it case-sensitive. RegExp names are supported.
40
+ - `page.getByText(text, { exact })` matches visible text, substring and case-insensitive by default.
41
+ - `page.getByLabel(text, { exact })` matches form fields by their `<label>` (for, wrapping, or `aria-labelledby`) or `aria-label`.
42
+ - `.first()` and `.nth(i)` pick one match when several qualify. Otherwise a locator that matches more than one element fails the action, like Playwright's strict mode.
43
+
44
+ Actions auto-wait for their element and retry when the page changes underneath them: `click()`, `fill(value)`, `type(text)` (trusted native keystrokes, for rich-text editors), `press(key)`, `hover()`, `focus()`, `check()`, `uncheck()`, `dragTo(locator)`. Reads: `textContent()`, `inputValue()`, `isChecked()`, `isVisible()`, `boundingBox()`, `count()`, `ariaSnapshot()`.
45
+
46
+ Clicks and keystrokes dispatch as native OS input. The cadence is configurable per browser: the default `inputMode: 'robotic'` is instant, which is what tests want; `'human'` moves the cursor along a humanized path with realistic timing for flows that score input behavior.
47
+
48
+ Assertions poll until they pass or time out:
49
+
50
+ - `expect(locator).toBeVisible()` / `.toBeHidden()`
51
+ - `expect(locator).toHaveText(value)` / `.toContainText(value)` (string or RegExp)
52
+ - `expect(locator).toHaveValue(value)` / `.toBeChecked()`
53
+ - `expect(locator).toHaveCount(n)`
54
+ - `expect(locator).toMatchAriaSnapshot(template)` / `expect(page).toMatchAriaSnapshot(template)`
55
+ - `expect(page).toHaveTitle(value)` / `.toHaveURL(value)`
56
+ - every matcher takes `{ timeout }` and negates with `.not`
57
+
58
+ ## Tree snapshots
59
+
60
+ `toMatchAriaSnapshot` compares part of the page against a template of roles and names:
61
+
62
+ ```ts
63
+ await expect(page.getByRole('main')).toMatchAriaSnapshot(`
64
+ - heading "Settings" [level=1]
65
+ - textbox "Work email"
66
+ - checkbox "Send me news" [checked]
67
+ - list:
68
+ - listitem "Alpha"
69
+ - listitem /bravo/i
70
+ `);
71
+ ```
72
+
73
+ Template siblings must appear in that order, and a child can sit at any depth under its parent, so wrapper elements do not break a template. Nodes the template does not mention are ignored. A name in quotes matches the whole name; `/regex/flags` is tested as written; no name matches any. `[level=N]` and `[checked]` constrain headings and checkboxes. A form field is printed under its `<label>` text when it has one; in a template, either that text or the field's current value names it. `await locator.ariaSnapshot()` (or `page.ariaSnapshot()`) prints the current tree in this format, ready to paste in and trim.
74
+
75
+ ## The page
76
+
77
+ - `page.goto(url)` navigates; relative URLs resolve against the `baseURL` option.
78
+ - `page.url()`, `page.title()`, and `page.evaluate(expr | fn)` read the page. `evaluate` returns the JSON-serialized result.
79
+ - `page.screenshot({ path, fullPage })` saves a PNG and returns its path.
80
+ - `page.mouse.move(x, y)`, `page.mouse.click(x, y)` and `page.mouse.drag(x1, y1, x2, y2)` send trusted pointer input at viewport coordinates, for canvas, maps, sliders and other surfaces with no accessibility tree. A drag also fires the HTML5 drag events, so native `draggable` lists see the drop.
81
+
82
+ ## Logging in once
83
+
84
+ `page.saveAuth(name)` stores the page's cookies, local and session storage, and IndexedDB, encrypted by the daemon. `page.loadAuth(name)` restores them in a later run; `page.clearAuth(name)` deletes them. Storage is per origin, so load on a page of the same site, then navigate:
85
+
86
+ ```ts
87
+ // once, after logging in through the UI
88
+ await page.saveAuth('staging-admin');
89
+
90
+ // every run after that
91
+ configure({ auth: { name: 'staging-admin', url: 'https://staging.example.com/' } });
92
+ ```
93
+
94
+ With the `auth` option, every test's `page` starts logged in.
95
+
96
+ ## Runner
97
+
98
+ The `test` export wraps node:test. Each test gets a fresh `page`; one browser session is shared across the file. `test.describe(name, fn)` groups tests, `test.beforeEach(fn)` and `test.afterEach(fn)` receive the same `{ page }`, and `test.only` / `test.skip` work as in node:test.
99
+
100
+ `configure(options)` sets the shared browser up before the first test runs:
101
+
102
+ - `baseURL`: resolve relative `goto` URLs against it.
103
+ - `auth: { name, url }`: start every page logged in (see above).
104
+ - `screenshot: 'only-on-failure'` with `outputDir` (default `test-results`): save a PNG when a test fails and add its path to the error.
105
+ - `timeouts: { action, expect, navigation }`, in milliseconds.
106
+ - `inputMode`: `robotic` (default, instant), `careful`, or `human` (a humanized cursor path for flows that score input behavior).
107
+
108
+ ```ts
109
+ import { test, expect, configure } from 'testsurfer';
110
+
111
+ configure({ baseURL: 'http://localhost:3000', screenshot: 'only-on-failure' });
112
+
113
+ test.describe('todos', () => {
114
+ test.beforeEach(async ({ page }) => {
115
+ await page.goto('/');
116
+ });
117
+
118
+ test('adds one', async ({ page }) => {
119
+ await page.getByLabel('New todo').fill('Buy milk');
120
+ await page.getByLabel('New todo').press('Enter');
121
+ await expect(page.getByRole('listitem')).toHaveCount(1);
122
+ });
123
+ });
124
+ ```
125
+
126
+ Runner integration is optional. Under vitest or any other runner, use `Browser.launch()` directly:
127
+
128
+ ```ts
129
+ import { Browser, expect } from 'testsurfer';
130
+
131
+ const browser = await Browser.launch();
132
+ const page = browser.newPage();
133
+ await page.goto('https://example.com');
134
+ await expect(page.getByRole('heading', { name: 'Example Domain' })).toBeVisible();
135
+ await browser.close();
136
+ ```
137
+
138
+ ## Status
139
+
140
+ Version 0.1 pins vibesurfer 0.2.13 and speaks its frozen wire protocol (v1). Older daemons work for everything except `level`, `checked` and `<label>` lookups, which need the tree attributes 0.2.12 added. Known issue: on some macOS 27 machines each WebKit navigation stalls for about ten seconds inside the engine, which makes suites much slower than the benchmark below; it is tracked in the vibesurfer repo.
141
+
142
+ ## Benchmark
143
+
144
+ [`bench/`](bench) runs identical flows through testsurfer and Playwright (WebKit and Chromium) against the same app and reports the numbers, favorable and not. On a GitHub macOS runner with vibesurfer 0.2.13: testsurfer launches in 4ms against Playwright's 0.6-2s, and runs the four-flow suite in 1437ms against 845ms for Playwright-WebKit and 494ms for Playwright-Chromium. A working install is ~6MB against ~300MB+ per Playwright browser. The full table, methodology and history are in the bench README; the `bench` workflow reproduces them.
145
+
146
+ ## Example
147
+
148
+ [`examples/todo`](examples/todo) is a small todo app with a complete e2e suite: locators by role and label, polling assertions, and the `{ page }` fixture. It installs testsurfer as a package dependency, so it also exercises the published module shape.
149
+
150
+ ## Development
151
+
152
+ ```sh
153
+ npm install
154
+ npm run test:unit # protocol and locator tests, no daemon needed
155
+ npm run test:e2e # drives a real page through a local daemon
156
+ npm run build
157
+ ```
package/dist/aria.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Accessibility-tree snapshots: render a subtree as indented text and
3
+ * match a hand-written template against it.
4
+ *
5
+ * Template format, one node per line, children indented under a
6
+ * trailing colon:
7
+ *
8
+ * - heading "Todos" [level=1]
9
+ * - list:
10
+ * - listitem "Buy milk"
11
+ * - listitem /walk/i
12
+ * - checkbox "Done" [checked]
13
+ * - button "Add"
14
+ *
15
+ * A role is an ARIA role name (or a wire role code). The name is a
16
+ * quoted string, matched whole after whitespace is collapsed, or a
17
+ * /regex/flags; leaving it out matches any name. `[level=N]` and
18
+ * `[checked]` constrain attributes.
19
+ *
20
+ * Matching is structural but forgiving: template siblings must appear
21
+ * in document order, and a template child may sit at any depth under
22
+ * its parent, so wrapper elements in the page do not break a template.
23
+ * Nodes the template does not mention are ignored.
24
+ */
25
+ import type { Snapshot } from './tree.ts';
26
+ export interface TemplateNode {
27
+ role: string;
28
+ name?: string | RegExp;
29
+ attrs: Record<string, string>;
30
+ children: TemplateNode[];
31
+ line: number;
32
+ }
33
+ /** Role name for a wire code, falling back to the code itself. */
34
+ export declare function roleName(code: string): string;
35
+ /** Parse a template. Throws with the line number on malformed input. */
36
+ export declare function parseTemplate(text: string): TemplateNode[];
37
+ /** True when the template matches somewhere within the subtrees rooted at `scope`. */
38
+ export declare function matchesTemplate(snap: Snapshot, scope: number[], template: TemplateNode[]): boolean;
39
+ /**
40
+ * Render subtrees as template text. Unnamed generic wrappers are
41
+ * dropped and their children lifted, so the output reads like the page
42
+ * and pastes straight back in as a template.
43
+ */
44
+ export declare function renderSnapshot(snap: Snapshot, scope: number[]): string;
package/dist/aria.js ADDED
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Accessibility-tree snapshots: render a subtree as indented text and
3
+ * match a hand-written template against it.
4
+ *
5
+ * Template format, one node per line, children indented under a
6
+ * trailing colon:
7
+ *
8
+ * - heading "Todos" [level=1]
9
+ * - list:
10
+ * - listitem "Buy milk"
11
+ * - listitem /walk/i
12
+ * - checkbox "Done" [checked]
13
+ * - button "Add"
14
+ *
15
+ * A role is an ARIA role name (or a wire role code). The name is a
16
+ * quoted string, matched whole after whitespace is collapsed, or a
17
+ * /regex/flags; leaving it out matches any name. `[level=N]` and
18
+ * `[checked]` constrain attributes.
19
+ *
20
+ * Matching is structural but forgiving: template siblings must appear
21
+ * in document order, and a template child may sit at any depth under
22
+ * its parent, so wrapper elements in the page do not break a template.
23
+ * Nodes the template does not mention are ignored.
24
+ */
25
+ import { ROLE_TO_CODES } from "./roles.js";
26
+ const CODE_TO_ROLE = {};
27
+ for (const [role, codes] of Object.entries(ROLE_TO_CODES)) {
28
+ for (const code of codes)
29
+ CODE_TO_ROLE[code] ??= role;
30
+ }
31
+ CODE_TO_ROLE['lbl'] ??= 'label';
32
+ CODE_TO_ROLE['hdr'] = 'banner';
33
+ const normalize = (s) => s.replace(/\s+/g, ' ').trim();
34
+ /** Role name for a wire code, falling back to the code itself. */
35
+ export function roleName(code) {
36
+ return CODE_TO_ROLE[code] ?? code;
37
+ }
38
+ function roleMatches(want, code) {
39
+ if (want === code)
40
+ return true;
41
+ const codes = ROLE_TO_CODES[want];
42
+ if (codes?.includes(code))
43
+ return true;
44
+ // `banner` (page header) shares the wire code with columnheader.
45
+ return want === 'banner' && code === 'hdr';
46
+ }
47
+ /** Parse a template. Throws with the line number on malformed input. */
48
+ export function parseTemplate(text) {
49
+ const roots = [];
50
+ const stack = [];
51
+ const lines = text.split('\n');
52
+ lines.forEach((raw, i) => {
53
+ if (raw.trim() === '')
54
+ return;
55
+ const indent = raw.length - raw.trimStart().length;
56
+ const m = /^-\s+([A-Za-z]+)(.*)$/.exec(raw.trim());
57
+ if (!m)
58
+ throw new Error(`aria template line ${i + 1}: expected "- role ...", got ${JSON.stringify(raw.trim())}`);
59
+ const role = m[1];
60
+ let rest = m[2].trim();
61
+ if (rest.endsWith(':'))
62
+ rest = rest.slice(0, -1).trim();
63
+ const node = { role, attrs: {}, children: [], line: i + 1 };
64
+ const str = /^"((?:[^"\\]|\\.)*)"/.exec(rest);
65
+ const re = /^\/((?:[^/\\]|\\.)+)\/([a-z]*)/.exec(rest);
66
+ if (str) {
67
+ node.name = str[1].replace(/\\(.)/g, '$1');
68
+ rest = rest.slice(str[0].length).trim();
69
+ }
70
+ else if (re) {
71
+ node.name = new RegExp(re[1], re[2]);
72
+ rest = rest.slice(re[0].length).trim();
73
+ }
74
+ for (const a of rest.matchAll(/\[([a-z]+)(?:=([^\]]*))?\]/g)) {
75
+ node.attrs[a[1]] = a[2] ?? '';
76
+ }
77
+ while (stack.length > 0 && stack[stack.length - 1].indent >= indent)
78
+ stack.pop();
79
+ const parent = stack[stack.length - 1];
80
+ if (parent)
81
+ parent.node.children.push(node);
82
+ else
83
+ roots.push(node);
84
+ stack.push({ indent, node });
85
+ });
86
+ return roots;
87
+ }
88
+ /** The text a node is known by: its label, or for a form field its <label> text when present. */
89
+ function names(node) {
90
+ const out = [normalize(node.label)];
91
+ const lbl = node.attrs['lbl'];
92
+ if (lbl)
93
+ out.push(normalize(lbl));
94
+ return out;
95
+ }
96
+ function nodeMatches(t, n) {
97
+ if (!roleMatches(t.role, n.role))
98
+ return false;
99
+ if (t.name !== undefined) {
100
+ const want = t.name;
101
+ const ok = names(n).some((s) => (want instanceof RegExp ? want.test(s) : s === normalize(want)));
102
+ if (!ok)
103
+ return false;
104
+ }
105
+ for (const [k, v] of Object.entries(t.attrs)) {
106
+ if (k === 'checked') {
107
+ const checked = n.attrs['checked'] === '1';
108
+ if (checked !== (v === '' || v === 'true'))
109
+ return false;
110
+ }
111
+ else if (n.attrs[k] !== v) {
112
+ return false;
113
+ }
114
+ }
115
+ return true;
116
+ }
117
+ /** Descendants of `refs` in document order, each with the index just past its subtree. */
118
+ function flatten(snap, refs) {
119
+ const out = [];
120
+ const visit = (ref) => {
121
+ const node = snap.nodes.get(ref);
122
+ if (!node)
123
+ return;
124
+ const slot = { node, end: 0 };
125
+ out.push(slot);
126
+ for (const c of node.children)
127
+ visit(c);
128
+ slot.end = out.length;
129
+ };
130
+ for (const r of refs)
131
+ visit(r);
132
+ return out;
133
+ }
134
+ /**
135
+ * Match template siblings, in order, against a document-ordered node
136
+ * list. Each template node takes the first viable node; a later sibling
137
+ * must start after the previous one's subtree. Backtracks when a
138
+ * greedy pick starves a later sibling.
139
+ */
140
+ function matchSeq(flat, from, to, tmpl) {
141
+ if (tmpl.length === 0)
142
+ return true;
143
+ const [head, ...tail] = tmpl;
144
+ for (let i = from; i < to; i++) {
145
+ const slot = flat[i];
146
+ if (!nodeMatches(head, slot.node))
147
+ continue;
148
+ if (!matchSeq(flat, i + 1, slot.end, head.children))
149
+ continue;
150
+ if (matchSeq(flat, slot.end, to, tail))
151
+ return true;
152
+ }
153
+ return false;
154
+ }
155
+ /** True when the template matches somewhere within the subtrees rooted at `scope`. */
156
+ export function matchesTemplate(snap, scope, template) {
157
+ const flat = flatten(snap, scope);
158
+ return matchSeq(flat, 0, flat.length, template);
159
+ }
160
+ /**
161
+ * Render subtrees as template text. Unnamed generic wrappers are
162
+ * dropped and their children lifted, so the output reads like the page
163
+ * and pastes straight back in as a template.
164
+ */
165
+ export function renderSnapshot(snap, scope) {
166
+ const lines = [];
167
+ const visit = (ref, depth) => {
168
+ const node = snap.nodes.get(ref);
169
+ if (!node)
170
+ return;
171
+ const label = normalize(node.label);
172
+ const wrapper = (node.role === 'el' || node.role === 'doc') && label === '';
173
+ if (wrapper || node.role === 'doc') {
174
+ for (const c of node.children)
175
+ visit(c, depth);
176
+ return;
177
+ }
178
+ let line = `${' '.repeat(depth)}- ${roleName(node.role)}`;
179
+ // A form field's label is its value; show the <label> text instead when there is one.
180
+ const lbl = node.attrs['lbl'];
181
+ const shown = lbl ? normalize(lbl) : label;
182
+ if (shown)
183
+ line += ` ${JSON.stringify(shown)}`;
184
+ if (node.attrs['level'])
185
+ line += ` [level=${node.attrs['level']}]`;
186
+ if (node.attrs['checked'] === '1')
187
+ line += ' [checked]';
188
+ const at = lines.push(line) - 1;
189
+ for (const c of node.children)
190
+ visit(c, depth + 1);
191
+ if (lines.length > at + 1)
192
+ lines[at] += ':';
193
+ };
194
+ for (const r of scope)
195
+ visit(r, 0);
196
+ return lines.join('\n');
197
+ }
198
+ //# sourceMappingURL=aria.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aria.js","sourceRoot":"","sources":["../src/aria.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAW3C,MAAM,YAAY,GAA2B,EAAE,CAAC;AAChD,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE,CAAC;IAC1D,KAAK,MAAM,IAAI,IAAI,KAAK;QAAE,YAAY,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC;AACxD,CAAC;AACD,YAAY,CAAC,KAAK,CAAC,KAAK,OAAO,CAAC;AAChC,YAAY,CAAC,KAAK,CAAC,GAAG,QAAQ,CAAC;AAE/B,MAAM,SAAS,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;AAE/D,kEAAkE;AAClE,MAAM,UAAU,QAAQ,CAAC,IAAY;IACnC,OAAO,YAAY,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC;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C,CAAC,CAAC;IACnC,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Browser: one vibesurfer session. Owns the wire client, opens pages,
3
+ * and closes the session on shutdown.
4
+ */
5
+ import { type ClientOptions } from './client.ts';
6
+ import { Page, type ClickVia, type InputMode, type ProtocolOptions, type Timeouts } from './page.ts';
7
+ export interface LaunchOptions extends ClientOptions {
8
+ timeouts?: Partial<Timeouts>;
9
+ /** vs policy name passed to session-open. */
10
+ policy?: string;
11
+ /**
12
+ * Cursor and keyboard cadence for trusted input. Defaults to
13
+ * `robotic` (instant, right for tests). Set `human` when a flow sits
14
+ * behind bot detection that scores cursor motion.
15
+ */
16
+ inputMode?: InputMode;
17
+ /** How click() reaches visible targets. See ClickVia; negotiated from the daemon by default. */
18
+ clickVia?: ClickVia;
19
+ /** Wire-semantics options for newer daemons. See ProtocolOptions. */
20
+ protocol?: ProtocolOptions;
21
+ /** Resolve relative goto() URLs against this, e.g. `http://localhost:3000`. */
22
+ baseURL?: string;
23
+ }
24
+ export declare class Browser {
25
+ private readonly client;
26
+ readonly sessionId: string;
27
+ private readonly timeouts;
28
+ private readonly inputMode;
29
+ private readonly clickVia;
30
+ private readonly protocol;
31
+ private readonly baseURL;
32
+ private constructor();
33
+ /**
34
+ * Connect to the daemon (spawning it if needed) and open a session.
35
+ * Wire capabilities are negotiated from the vs_status daemon line
36
+ * (`daemon version=... proto=N flags=a,b`): protocol-v1 daemons get
37
+ * inline act deltas, act-mode clicks, and nav-in-place goto
38
+ * automatically. Explicit options always win over negotiation.
39
+ */
40
+ static launch(options?: LaunchOptions): Promise<Browser>;
41
+ /** A new page in this session. Call page.goto(url) to load a URL. */
42
+ newPage(): Page;
43
+ /** Close the session and drop the connection. */
44
+ close(): Promise<void>;
45
+ }