uwright 0.0.0-stage → 0.1.1

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/dist/watch.js ADDED
@@ -0,0 +1,412 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { readFile, writeFile } from 'node:fs/promises';
3
+ import { createServer } from 'node:http';
4
+ import path from 'node:path';
5
+ import { openai } from '@ai-sdk/openai';
6
+ import { generateText, Output } from 'ai';
7
+ import { z } from 'zod';
8
+ import { FlowError } from './model.js';
9
+ const commandSchema = z.discriminatedUnion('type', [
10
+ z.object({ type: z.literal('pause') }),
11
+ z.object({ type: z.literal('resume') }),
12
+ z.object({ type: z.literal('stop') }),
13
+ z.object({ type: z.literal('start') }),
14
+ z.object({ type: z.literal('rerun') }),
15
+ z.object({
16
+ type: z.literal('suggest'),
17
+ claim: z.string().min(1).max(4000),
18
+ clarification: z.string().min(1).max(4000),
19
+ }),
20
+ z.object({ type: z.literal('click'), x: z.number().min(0).max(1), y: z.number().min(0).max(1) }),
21
+ z.object({ type: z.literal('key'), key: z.string().min(1).max(40) }),
22
+ z.object({ type: z.literal('text'), text: z.string().max(4096) }),
23
+ z.object({ type: z.literal('scroll'), delta: z.number().min(-1200).max(1200) }),
24
+ z.object({ type: z.literal('save'), content: z.string().max(100000), revision: z.string() }),
25
+ ]);
26
+ const hash = (content) => createHash('sha256').update(content).digest('hex');
27
+ export class Watch {
28
+ source;
29
+ title;
30
+ model;
31
+ token = randomBytes(24).toString('hex');
32
+ controller = new AbortController();
33
+ get signal() {
34
+ return this.controller.signal;
35
+ }
36
+ clients = new Set();
37
+ reports = new Map();
38
+ page;
39
+ latest;
40
+ pauseRequested = false;
41
+ paused = false;
42
+ resumed;
43
+ viewerConnected;
44
+ connected = false;
45
+ startRequested = false;
46
+ started;
47
+ rerun;
48
+ origin = '';
49
+ state = { status: 'starting', current: '', items: [], plan: [], ready: false, message: '', logs: [] };
50
+ server = createServer((req, res) => {
51
+ void this.handle(req, res).catch(() => {
52
+ if (!res.headersSent)
53
+ res.writeHead(500);
54
+ res.end();
55
+ });
56
+ });
57
+ redact = (value) => value;
58
+ constructor(source, title, model) {
59
+ this.source = source;
60
+ this.title = title;
61
+ this.model = model;
62
+ }
63
+ setRedactor(redact) {
64
+ this.redact = redact;
65
+ }
66
+ setRerun(rerun) {
67
+ this.rerun = rerun;
68
+ }
69
+ async start() {
70
+ await new Promise((resolve, reject) => {
71
+ this.server.once('error', reject);
72
+ this.server.listen(0, '127.0.0.1', resolve);
73
+ });
74
+ const addr = this.server.address();
75
+ if (!addr || typeof addr === 'string')
76
+ throw new Error('Watch server failed to bind');
77
+ this.origin = `http://127.0.0.1:${addr.port}`;
78
+ return `${this.origin}/${this.token}/`;
79
+ }
80
+ async close() {
81
+ for (const client of this.clients)
82
+ client.end();
83
+ await new Promise((resolve, reject) => this.server.close((error) => (error ? reject(error) : resolve())));
84
+ }
85
+ async waitForViewer() {
86
+ if (!this.connected)
87
+ await new Promise((resolve) => {
88
+ this.viewerConnected = resolve;
89
+ });
90
+ }
91
+ async waitForStart() {
92
+ if (!this.startRequested && !this.signal.aborted)
93
+ await new Promise((resolve) => {
94
+ this.started = resolve;
95
+ });
96
+ if (this.signal.aborted)
97
+ throw new Error('Run stopped');
98
+ }
99
+ async attach(page) {
100
+ this.page = page;
101
+ await page.screencast.start({
102
+ size: page.viewportSize() ?? { width: 1280, height: 720 },
103
+ onFrame: (frame) => {
104
+ this.latest = frame.data;
105
+ const event = `event: frame\ndata: ${frame.data.toString('base64')}\n\n`;
106
+ for (const res of this.clients)
107
+ if (!res.writableNeedDrain)
108
+ res.write(event);
109
+ },
110
+ });
111
+ }
112
+ emit() {
113
+ const data = `data: ${JSON.stringify(this.state)}\n\n`;
114
+ for (const res of this.clients)
115
+ res.write(data);
116
+ }
117
+ plan(items, ready = true) {
118
+ this.state.plan = items.map((item) => ({
119
+ ...item,
120
+ kind: item.kind ?? (['expected outcome', 'postconditions'].includes(item.section) ? 'check' : 'step'),
121
+ status: 'pending',
122
+ actions: [],
123
+ }));
124
+ this.state.ready = ready;
125
+ this.emit();
126
+ }
127
+ async boundary(text, id, parentId, kind = 'step', section = 'steps') {
128
+ if (this.signal.aborted)
129
+ throw new Error('Run stopped');
130
+ this.state.current = text;
131
+ let item = this.state.plan.find((item) => item.id === id);
132
+ if (!item && id && parentId) {
133
+ item = { id, parentId, text, section, kind, status: 'pending', actions: [] };
134
+ this.state.plan.push(item);
135
+ }
136
+ if (item) {
137
+ item.status = 'running';
138
+ item.kind = kind;
139
+ }
140
+ if (this.pauseRequested) {
141
+ this.paused = true;
142
+ this.state.status = 'paused';
143
+ this.emit();
144
+ await new Promise((resolve) => {
145
+ this.resumed = resolve;
146
+ });
147
+ if (this.signal.aborted)
148
+ throw new Error('Run stopped');
149
+ }
150
+ this.state.status = 'running';
151
+ this.emit();
152
+ }
153
+ action(detail, id) {
154
+ this.state.message = detail;
155
+ const planned = this.state.plan.find((item) => item.id === id);
156
+ if (planned)
157
+ planned.actions.push(detail);
158
+ this.emit();
159
+ }
160
+ add(item, id) {
161
+ this.state.items.push(item);
162
+ const planned = this.state.plan.find((entry) => entry.id === id);
163
+ if (planned && item.status !== 'running') {
164
+ planned.status = item.status;
165
+ planned.detail = item.detail;
166
+ }
167
+ this.state.message = '';
168
+ this.emit();
169
+ }
170
+ log(message) {
171
+ this.state.logs.push(this.redact(message).trimEnd());
172
+ this.emit();
173
+ }
174
+ fail(error) {
175
+ const message = this.redact(error instanceof FlowError
176
+ ? `${error.code}: ${error.message}`
177
+ : `ERROR: ${error instanceof Error ? error.message : String(error)}`);
178
+ process.stderr.write(`${message}\n`);
179
+ this.state.message = message;
180
+ this.log(message);
181
+ this.done(this.signal.aborted ? 'stopped' : 'failed');
182
+ }
183
+ done(status, report) {
184
+ this.state.status = status;
185
+ this.state.current = '';
186
+ if (status !== 'passed')
187
+ for (const item of this.state.plan) {
188
+ if (item.status === 'running')
189
+ item.status = status === 'failed' ? 'failed' : 'skipped';
190
+ else if (item.status === 'pending')
191
+ item.status = 'skipped';
192
+ }
193
+ if (report) {
194
+ const id = path.basename(path.dirname(report));
195
+ this.reports.set(id, path.dirname(report));
196
+ this.state.report = `report/${id}/index.html`;
197
+ }
198
+ this.emit();
199
+ }
200
+ async handle(req, res) {
201
+ const url = new URL(req.url ?? '/', this.origin);
202
+ const base = `/${this.token}`;
203
+ if (req.method === 'GET' && url.pathname === base) {
204
+ res.writeHead(308, {
205
+ Location: `${base}/${url.search}`,
206
+ 'Cache-Control': 'no-store',
207
+ 'Referrer-Policy': 'no-referrer',
208
+ });
209
+ res.end();
210
+ return;
211
+ }
212
+ if (!url.pathname.startsWith(`${base}/`)) {
213
+ res.writeHead(404);
214
+ res.end();
215
+ return;
216
+ }
217
+ res.setHeader('Cache-Control', 'no-store');
218
+ if (req.method === 'GET' && url.pathname === `${base}/`) {
219
+ res.writeHead(200, {
220
+ 'Content-Type': 'text/html; charset=utf-8',
221
+ 'Referrer-Policy': 'no-referrer',
222
+ 'X-Content-Type-Options': 'nosniff',
223
+ });
224
+ res.end(await this.html());
225
+ return;
226
+ }
227
+ if (req.method === 'GET' && url.pathname === `${base}/events`) {
228
+ res.writeHead(200, { 'Content-Type': 'text/event-stream', Connection: 'keep-alive' });
229
+ this.clients.add(res);
230
+ res.write(`data: ${JSON.stringify(this.state)}\n\n`);
231
+ req.on('close', () => this.clients.delete(res));
232
+ if (this.latest)
233
+ res.write(`event: frame\ndata: ${this.latest.toString('base64')}\n\n`);
234
+ this.connected = true;
235
+ this.viewerConnected?.();
236
+ return;
237
+ }
238
+ if (req.method === 'GET' && url.pathname === `${base}/source`) {
239
+ const content = await readFile(this.source, 'utf8');
240
+ res.writeHead(200, { 'Content-Type': 'application/json' });
241
+ res.end(JSON.stringify({ content, revision: hash(content) }));
242
+ return;
243
+ }
244
+ if (req.method === 'GET' && url.pathname.startsWith(`${base}/report/`)) {
245
+ const [id, name, extra] = url.pathname.slice(`${base}/report/`.length).split('/');
246
+ const directory = id ? this.reports.get(id) : undefined;
247
+ if (!directory || extra || !name || (name !== 'index.html' && !/^screen-\d+\.png$/.test(name))) {
248
+ res.writeHead(404);
249
+ res.end();
250
+ return;
251
+ }
252
+ const content = await readFile(path.join(directory, name));
253
+ res.writeHead(200, {
254
+ 'Content-Type': name.endsWith('.png') ? 'image/png' : 'text/html; charset=utf-8',
255
+ 'X-Content-Type-Options': 'nosniff',
256
+ });
257
+ res.end(content);
258
+ return;
259
+ }
260
+ if (req.method !== 'POST' || url.pathname !== `${base}/command` || req.headers.origin !== this.origin) {
261
+ res.writeHead(403);
262
+ res.end();
263
+ return;
264
+ }
265
+ let body = '';
266
+ for await (const part of req) {
267
+ body += String(part);
268
+ if (body.length > 120000) {
269
+ res.writeHead(413);
270
+ res.end();
271
+ return;
272
+ }
273
+ }
274
+ const parsed = commandSchema.safeParse(JSON.parse(body));
275
+ if (!parsed.success) {
276
+ res.writeHead(400);
277
+ res.end();
278
+ return;
279
+ }
280
+ const cmd = parsed.data;
281
+ if (cmd.type === 'pause') {
282
+ this.pauseRequested = true;
283
+ this.state.status = 'pause requested';
284
+ this.emit();
285
+ }
286
+ else if (cmd.type === 'resume') {
287
+ this.pauseRequested = false;
288
+ this.paused = false;
289
+ this.resumed?.();
290
+ this.resumed = undefined;
291
+ this.state.status = 'running';
292
+ this.emit();
293
+ }
294
+ else if (cmd.type === 'start') {
295
+ if (this.startRequested || this.signal.aborted || this.state.status !== 'starting' || !this.state.ready) {
296
+ res.writeHead(409);
297
+ res.end('The test plan is not ready or the run has already started.');
298
+ return;
299
+ }
300
+ this.startRequested = true;
301
+ this.started?.();
302
+ this.started = undefined;
303
+ this.state.status = 'running';
304
+ this.emit();
305
+ }
306
+ else if (cmd.type === 'stop') {
307
+ this.controller.abort();
308
+ this.started?.();
309
+ this.started = undefined;
310
+ this.resumed?.();
311
+ this.resumed = undefined;
312
+ this.state.status = 'stopping';
313
+ this.emit();
314
+ }
315
+ else if (cmd.type === 'rerun') {
316
+ if (!this.rerun || !['passed', 'failed', 'stopped'].includes(this.state.status)) {
317
+ res.writeHead(409);
318
+ res.end('Wait for the current run to finish.');
319
+ return;
320
+ }
321
+ this.controller = new AbortController();
322
+ this.pauseRequested = false;
323
+ this.paused = false;
324
+ this.startRequested = true;
325
+ this.state = {
326
+ status: 'starting',
327
+ current: '',
328
+ items: [],
329
+ ready: false,
330
+ plan: this.state.plan
331
+ .filter((item) => !item.parentId)
332
+ .map((item) => ({
333
+ ...item,
334
+ status: 'pending',
335
+ kind: item.section === 'expected outcome' ? 'check' : 'step',
336
+ actions: [],
337
+ detail: undefined,
338
+ })),
339
+ message: 'Starting a new run from the saved Markdown.',
340
+ logs: [],
341
+ };
342
+ this.emit();
343
+ void this.rerun().catch((error) => this.fail(error));
344
+ }
345
+ else if (cmd.type === 'suggest') {
346
+ const recent = this.state.items.filter((item) => item.status === 'failed').slice(-1);
347
+ try {
348
+ const output = await generateText({
349
+ model: openai(this.model),
350
+ output: Output.object({ schema: z.object({ assertion: z.string() }) }),
351
+ providerOptions: { openai: { strictJsonSchema: false } },
352
+ prompt: this.redact(`Rewrite this test assertion to reflect the user's clarification. Return only the proposed assertion. Preserve its meaning and do not invent page details. If the clarification is unclear, say so in the assertion.
353
+
354
+ Original assertion: ${cmd.claim}
355
+ User clarification: ${cmd.clarification}
356
+ Recent failure: ${JSON.stringify(recent)}`),
357
+ });
358
+ res.writeHead(200, { 'Content-Type': 'application/json' });
359
+ res.end(JSON.stringify({ assertion: this.redact(output.output.assertion) }));
360
+ return;
361
+ }
362
+ catch (error) {
363
+ res.writeHead(502);
364
+ res.end(`Could not suggest wording: ${this.redact(error instanceof Error ? error.message : String(error))}`);
365
+ return;
366
+ }
367
+ }
368
+ else if (cmd.type === 'save') {
369
+ const current = await readFile(this.source, 'utf8');
370
+ if (hash(current) !== cmd.revision) {
371
+ res.writeHead(409);
372
+ res.end('File changed since it was opened. Reload before saving.');
373
+ return;
374
+ }
375
+ await writeFile(this.source, cmd.content);
376
+ this.state.message = 'Markdown saved. Changes apply on the next run.';
377
+ this.emit();
378
+ res.writeHead(200, { 'Content-Type': 'application/json' });
379
+ res.end(JSON.stringify({ revision: hash(cmd.content) }));
380
+ return;
381
+ }
382
+ else {
383
+ if (!this.paused || !this.page) {
384
+ res.writeHead(409);
385
+ res.end('Pause at a step boundary before controlling the page.');
386
+ return;
387
+ }
388
+ if (cmd.type === 'click') {
389
+ const size = this.page.viewportSize();
390
+ if (!size)
391
+ throw new Error('No viewport');
392
+ await this.page.mouse.click(cmd.x * size.width, cmd.y * size.height);
393
+ }
394
+ else if (cmd.type === 'key')
395
+ await this.page.keyboard.press(cmd.key);
396
+ else if (cmd.type === 'text')
397
+ await this.page.keyboard.insertText(cmd.text);
398
+ else if (cmd.type === 'scroll')
399
+ await this.page.mouse.wheel(0, cmd.delta);
400
+ this.state.message =
401
+ 'Page changed manually. Resume re-observes the UI; rerun from the start if prior steps are no longer valid.';
402
+ this.emit();
403
+ }
404
+ res.writeHead(200, { 'Content-Type': 'application/json' });
405
+ res.end('{}');
406
+ }
407
+ async html() {
408
+ const title = JSON.stringify(this.title).replace(/</g, '\\u003c');
409
+ const template = await readFile(new URL('./templates/watch.html', import.meta.url), 'utf8');
410
+ return template.replace('__UWRIGHT_TITLE_JSON__', title);
411
+ }
412
+ }
@@ -0,0 +1,103 @@
1
+ import { readdir, readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import matter from 'gray-matter';
4
+ import remarkParse from 'remark-parse';
5
+ import { unified } from 'unified';
6
+ import { parse as parseYaml } from 'yaml';
7
+ import { configSchema, FlowError, frontmatterSchema } from './model.js';
8
+ async function files(dir) {
9
+ try {
10
+ const entries = await readdir(dir, { withFileTypes: true });
11
+ return (await Promise.all(entries.map((e) => e.isDirectory() ? files(path.join(dir, e.name)) : Promise.resolve(e.isFile() ? [path.join(dir, e.name)] : [])))).flat();
12
+ }
13
+ catch (e) {
14
+ if (e.code === 'ENOENT')
15
+ return [];
16
+ throw e;
17
+ }
18
+ }
19
+ export async function parseDocument(file) {
20
+ const source = await readFile(file, 'utf8');
21
+ let parsed;
22
+ try {
23
+ parsed = matter(source);
24
+ }
25
+ catch (e) {
26
+ throw new FlowError('MARKDOWN_LINT_ERROR', `${file}:1: ${String(e)}`);
27
+ }
28
+ const fm = frontmatterSchema.safeParse(parsed.data);
29
+ if (!fm.success)
30
+ throw new FlowError('MARKDOWN_LINT_ERROR', `${file}:1: ${fm.error.message}`);
31
+ const tree = unified().use(remarkParse).parse(parsed.content);
32
+ const offset = source.slice(0, source.length - parsed.content.length).split('\n').length - 1;
33
+ const sections = {};
34
+ let section = '';
35
+ for (const node of tree.children) {
36
+ if (node.type === 'heading' && node.depth === 2) {
37
+ section = parsed.content
38
+ .slice(node.position.start.offset, node.position.end.offset)
39
+ .replace(/^##\s*/, '')
40
+ .trim()
41
+ .toLowerCase();
42
+ if (sections[section])
43
+ throw new FlowError('MARKDOWN_LINT_ERROR', `${file}:${node.position.start.line + offset}: duplicate section`);
44
+ sections[section] = [];
45
+ continue;
46
+ }
47
+ if (node.type === 'list' && section) {
48
+ for (const item of node.children) {
49
+ const start = item.position.start.offset;
50
+ const end = item.position.end.offset;
51
+ const text = parsed.content
52
+ .slice(start, end)
53
+ .replace(/^\s*(?:\d+[.)]|[-+*])\s+/, '')
54
+ .trim();
55
+ sections[section].push({ text, line: item.position.start.line + offset });
56
+ }
57
+ if (section === 'steps' && !node.ordered)
58
+ throw new FlowError('MARKDOWN_LINT_ERROR', `${file}:${node.position.start.line + offset}: Steps must be an ordered list`);
59
+ if (['expected outcome', 'postconditions'].includes(section) && node.ordered)
60
+ throw new FlowError('MARKDOWN_LINT_ERROR', `${file}:${node.position.start.line + offset}: outcomes must be an unordered list`);
61
+ }
62
+ }
63
+ return { path: file, source, frontmatter: fm.data, sections };
64
+ }
65
+ export async function loadWorkspace(root = process.cwd()) {
66
+ let raw;
67
+ try {
68
+ raw = parseYaml(await readFile(path.join(root, 'uwright.config.yaml'), 'utf8'));
69
+ }
70
+ catch (e) {
71
+ throw new FlowError('CONFIG_ERROR', `Cannot read uwright.config.yaml: ${String(e)}`);
72
+ }
73
+ const parsed = configSchema.safeParse(raw);
74
+ if (!parsed.success)
75
+ throw new FlowError('CONFIG_ERROR', parsed.error.message);
76
+ const all = await files(path.resolve(root, parsed.data.flowsDir));
77
+ const docs = await Promise.all(all
78
+ .filter((f) => f.endsWith('.flow.md') || f.endsWith('.skill.md') || path.basename(f) === 'CONTEXT.md')
79
+ .map(parseDocument));
80
+ const flows = docs.filter((d) => d.path.endsWith('.flow.md')), skills = docs.filter((d) => d.path.endsWith('.skill.md')), contexts = docs.filter((d) => path.basename(d.path) === 'CONTEXT.md');
81
+ const names = new Set();
82
+ for (const d of [...flows, ...skills]) {
83
+ const required = d.path.endsWith('.flow.md') ? 'expected outcome' : 'postconditions';
84
+ if (!d.frontmatter.name)
85
+ throw new FlowError('MARKDOWN_LINT_ERROR', `${d.path}:1: name is required`);
86
+ if (!d.sections.steps?.length || !d.sections[required]?.length)
87
+ throw new FlowError('MARKDOWN_LINT_ERROR', `${d.path}:1: nonempty Steps and ${required} sections are required`);
88
+ if (d.path.endsWith('.skill.md')) {
89
+ if (names.has(d.frontmatter.name))
90
+ throw new FlowError('MARKDOWN_LINT_ERROR', `${d.path}:1: duplicate skill ${d.frontmatter.name}`);
91
+ names.add(d.frontmatter.name);
92
+ }
93
+ }
94
+ return { root, config: parsed.data, flows, skills, contexts };
95
+ }
96
+ export function contextsFor(ws, doc) {
97
+ return ws.contexts
98
+ .filter((c) => {
99
+ const rel = path.relative(path.dirname(c.path), path.dirname(doc.path));
100
+ return !rel.startsWith('..') && !path.isAbsolute(rel);
101
+ })
102
+ .sort((a, b) => a.path.length - b.path.length);
103
+ }
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "uwright",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Markdown-first UI end-to-end testing",
5
+ "type": "module",
6
+ "bin": {
7
+ "uwright": "dist/cli.js"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "!dist/telemetry.js"
12
+ ],
13
+ "engines": {
14
+ "node": "^22.22.3 || >=24.8.0"
15
+ },
16
+ "scripts": {
17
+ "build": "tsc && node scripts/copy-html-templates.mjs",
18
+ "typecheck": "tsc --noEmit",
19
+ "test": "vitest run",
20
+ "format": "biome format --write src tests && node scripts/enforce-function-spacing.mjs",
21
+ "lint": "biome lint src tests",
22
+ "check": "biome check src tests"
23
+ },
24
+ "dependencies": {
25
+ "@ai-sdk/openai": "^4.0.126",
26
+ "@e2e-dev/core": "0.25.0",
27
+ "@e2e-dev/web": "0.17.0",
28
+ "@modelcontextprotocol/sdk": "^1.0.0",
29
+ "ai": "^7.0.185",
30
+ "gray-matter": "^4.0.3",
31
+ "playwright": "1.65.1",
32
+ "remark-parse": "^11.0.0",
33
+ "unified": "^11.0.0",
34
+ "yaml": "^2.0.0",
35
+ "zod": "^4.0.0"
36
+ },
37
+ "devDependencies": {
38
+ "@ai-sdk/otel": "^1.0.186",
39
+ "@biomejs/biome": "2.3.8",
40
+ "@opentelemetry/api": "^1.9.1",
41
+ "@softprobe/tracing": "^0.2.9",
42
+ "@softprobe/vercel-ai-sdk": "^0.2.9",
43
+ "@types/node": "^24.0.0",
44
+ "tsx": "^4.0.0",
45
+ "typescript": "^5.0.0",
46
+ "vitest": "^4.0.0"
47
+ },
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "git+https://github.com/softprobe/uwright.git"
51
+ },
52
+ "homepage": "https://github.com/softprobe/uwright#readme",
53
+ "bugs": {
54
+ "url": "https://github.com/softprobe/uwright/issues"
55
+ },
56
+ "publishConfig": {
57
+ "access": "public"
58
+ }
59
+ }