@quiesco/ui 0.0.0-stage → 0.3.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 +21 -0
- package/README.md +20 -2
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/messages.d.ts +74 -0
- package/dist/messages.d.ts.map +1 -0
- package/dist/messages.js +2 -0
- package/dist/messages.js.map +1 -0
- package/dist/server.d.ts +25 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +289 -0
- package/dist/server.js.map +1 -0
- package/dist/spawn.d.ts +13 -0
- package/dist/spawn.d.ts.map +1 -0
- package/dist/spawn.js +42 -0
- package/dist/spawn.js.map +1 -0
- package/dist/targets.d.ts +24 -0
- package/dist/targets.d.ts.map +1 -0
- package/dist/targets.js +37 -0
- package/dist/targets.js.map +1 -0
- package/dist/web/assets/dm-sans-latin-ext-wght-normal-BOFOeGcA.woff2 +0 -0
- package/dist/web/assets/dm-sans-latin-wght-normal-Xz1IZZA0.woff2 +0 -0
- package/dist/web/assets/index-Blhnqd4m.css +1 -0
- package/dist/web/assets/index-BmpF4iJ3.js +16 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-ext-wght-normal-EocZY2iu.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
- package/dist/web/assets/space-grotesk-latin-ext-wght-normal-D9tNdqV9.woff2 +0 -0
- package/dist/web/assets/space-grotesk-latin-wght-normal-BhU9QXUp.woff2 +0 -0
- package/dist/web/assets/space-grotesk-vietnamese-wght-normal-D0rl6rjA.woff2 +0 -0
- package/dist/web/index.html +15 -0
- package/package.json +63 -3
- package/src/index.ts +11 -0
- package/src/messages.ts +44 -0
- package/src/server.ts +311 -0
- package/src/spawn.ts +52 -0
- package/src/targets.ts +47 -0
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en" data-theme="dark">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<meta name="color-scheme" content="dark light">
|
|
7
|
+
<title>Quiesco</title>
|
|
8
|
+
<link rel="icon" href="data:,">
|
|
9
|
+
<script type="module" crossorigin src="./assets/index-BmpF4iJ3.js"></script>
|
|
10
|
+
<link rel="stylesheet" crossorigin href="./assets/index-Blhnqd4m.css">
|
|
11
|
+
</head>
|
|
12
|
+
<body>
|
|
13
|
+
<div id="root"></div>
|
|
14
|
+
</body>
|
|
15
|
+
</html>
|
package/package.json
CHANGED
|
@@ -1,6 +1,66 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quiesco/ui",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Quiesco test UI: run tests from the browser and watch them live (quiesco ui).",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "h2nology",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"quiesco",
|
|
9
|
+
"e2e",
|
|
10
|
+
"testing",
|
|
11
|
+
"expo",
|
|
12
|
+
"react-native",
|
|
13
|
+
"ui"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://github.com/h2nology/quiesco/tree/main/packages/ui#readme",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/h2nology/quiesco.git",
|
|
19
|
+
"directory": "packages/ui"
|
|
20
|
+
},
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/h2nology/quiesco/issues"
|
|
23
|
+
},
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=24"
|
|
26
|
+
},
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public"
|
|
29
|
+
},
|
|
30
|
+
"type": "module",
|
|
31
|
+
"main": "./dist/index.js",
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"exports": {
|
|
34
|
+
".": {
|
|
35
|
+
"types": "./dist/index.d.ts",
|
|
36
|
+
"default": "./dist/index.js"
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist",
|
|
41
|
+
"src"
|
|
42
|
+
],
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"@quiesco/core": "0.3.0",
|
|
45
|
+
"@quiesco/protocol": "0.3.0",
|
|
46
|
+
"ws": "8.22.1"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@fontsource-variable/dm-sans": "5.3.0",
|
|
50
|
+
"@fontsource-variable/jetbrains-mono": "5.3.0",
|
|
51
|
+
"@fontsource-variable/space-grotesk": "5.3.0",
|
|
52
|
+
"@types/react": "19.3.0",
|
|
53
|
+
"@types/react-dom": "19.3.0",
|
|
54
|
+
"@types/ws": "8.18.2",
|
|
55
|
+
"@vitejs/plugin-react": "6.1.2",
|
|
56
|
+
"playwright": "1.65.0",
|
|
57
|
+
"react": "19.3.0",
|
|
58
|
+
"react-dom": "19.3.0",
|
|
59
|
+
"vite": "8.3.6"
|
|
60
|
+
},
|
|
61
|
+
"scripts": {
|
|
62
|
+
"build": "tsc -b && pnpm run build:web",
|
|
63
|
+
"build:web": "tsc -p web/tsconfig.json && vite build --config web/vite.config.ts",
|
|
64
|
+
"test": "vitest run"
|
|
65
|
+
}
|
|
6
66
|
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @quiesco/ui: the test UI behind `quiesco ui` — run tests from the browser and watch them live.
|
|
3
|
+
* The CLI loads it; it is not meant to be used directly.
|
|
4
|
+
*/
|
|
5
|
+
export { startUiServer } from './server.js';
|
|
6
|
+
export type { UiServer, UiServerOptions } from './server.js';
|
|
7
|
+
export { spawnRun } from './spawn.js';
|
|
8
|
+
export type { RunHandle, SpawnRunOptions } from './spawn.js';
|
|
9
|
+
export { targetArgs } from './targets.js';
|
|
10
|
+
export type { RunTarget } from './targets.js';
|
|
11
|
+
export type { ClientMessage, NoticeCode, RunningInfo, ServerMessage, UiInfo } from './messages.js';
|
package/src/messages.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Messages between the `quiesco ui` server and the browser, over a WebSocket at `/ws` (JSON, one
|
|
3
|
+
* message per frame). Types only: the web app imports them too.
|
|
4
|
+
*/
|
|
5
|
+
import type { RunStateSnapshot } from '@quiesco/core/run-state';
|
|
6
|
+
import type { RunEvent, RunnerName, TestList } from '@quiesco/protocol';
|
|
7
|
+
|
|
8
|
+
import type { RunTarget } from './targets.js';
|
|
9
|
+
|
|
10
|
+
export type { RunTarget };
|
|
11
|
+
|
|
12
|
+
export interface UiInfo {
|
|
13
|
+
/** The project directory's name. */
|
|
14
|
+
project: string;
|
|
15
|
+
runner: RunnerName;
|
|
16
|
+
platform: string;
|
|
17
|
+
/** Version of @quiesco/ui. */
|
|
18
|
+
version: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type ServerMessage =
|
|
22
|
+
/** First message on a connection, with everything needed to draw the page. */
|
|
23
|
+
| { type: 'welcome'; info: UiInfo; list: TestList | null; listing: boolean; state: RunStateSnapshot; running: RunningInfo | null; output: string }
|
|
24
|
+
/** Listing the tests started (`listing: true`) or finished (with the list). */
|
|
25
|
+
| { type: 'list'; list: TestList | null; listing: boolean }
|
|
26
|
+
/** A run event from the runner (apply it to the RunState). */
|
|
27
|
+
| { type: 'event'; event: RunEvent }
|
|
28
|
+
/** A run started (`running` set) or ended (`running: null`, the final state). */
|
|
29
|
+
| { type: 'run'; running: RunningInfo | null; exitCode?: number; state?: RunStateSnapshot }
|
|
30
|
+
/** The runner's own output (stdout / stderr). */
|
|
31
|
+
| { type: 'output'; stream: 'stdout' | 'stderr'; text: string }
|
|
32
|
+
/** `code` lets the page show the notice in its language; `message` is the English text. */
|
|
33
|
+
| { type: 'notice'; level: 'info' | 'error'; code?: NoticeCode; message: string };
|
|
34
|
+
|
|
35
|
+
export type NoticeCode = 'busy' | 'unknown-tests';
|
|
36
|
+
|
|
37
|
+
export interface RunningInfo {
|
|
38
|
+
target: RunTarget;
|
|
39
|
+
/** The runner arguments chosen for the target. */
|
|
40
|
+
args: string[];
|
|
41
|
+
startedAt: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export type ClientMessage = { type: 'run'; target: RunTarget } | { type: 'cancel' } | { type: 'list' };
|
package/src/server.ts
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `quiesco ui` server (P5): serves the web app, lists the tests, runs what the browser asks for
|
|
3
|
+
* (one run at a time: one device), and streams the run events to every open page.
|
|
4
|
+
*
|
|
5
|
+
* Local only: it listens on 127.0.0.1, refuses other Host / Origin headers (DNS rebinding) and requires
|
|
6
|
+
* the token from the URL it prints (kept in a cookie after the first page load). Files are served only
|
|
7
|
+
* from the artifacts directory (evidence) and the listed test files (source view).
|
|
8
|
+
*/
|
|
9
|
+
import { randomBytes } from 'node:crypto';
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import http from 'node:http';
|
|
12
|
+
import { createRequire } from 'node:module';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
|
|
15
|
+
import { RunEventServer, RunState } from '@quiesco/core';
|
|
16
|
+
import type { RunEvent, RunnerName, TestList, TestRef } from '@quiesco/protocol';
|
|
17
|
+
import { WebSocketServer } from 'ws';
|
|
18
|
+
import type { WebSocket } from 'ws';
|
|
19
|
+
|
|
20
|
+
import type { ClientMessage, NoticeCode, RunningInfo, ServerMessage, UiInfo } from './messages.js';
|
|
21
|
+
import type { RunHandle } from './spawn.js';
|
|
22
|
+
import { targetArgs } from './targets.js';
|
|
23
|
+
import type { RunTarget } from './targets.js';
|
|
24
|
+
|
|
25
|
+
export interface UiServerOptions {
|
|
26
|
+
cwd: string;
|
|
27
|
+
runner: RunnerName;
|
|
28
|
+
platform: string;
|
|
29
|
+
/** Start the runner with `args` added (the target) and `env` added (QUIESCO_EVENTS). */
|
|
30
|
+
startRun(args: string[], env: Record<string, string>, onOutput: (stream: 'stdout' | 'stderr', text: string) => void): RunHandle;
|
|
31
|
+
listTests(): Promise<TestList>;
|
|
32
|
+
/** Absolute path of the artifacts directory (evidence files). */
|
|
33
|
+
artifactsDir: string;
|
|
34
|
+
/** The built web app; null serves a minimal page (tests of the server). */
|
|
35
|
+
staticDir: string | null;
|
|
36
|
+
port?: number;
|
|
37
|
+
host?: string;
|
|
38
|
+
token?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface UiServer {
|
|
42
|
+
readonly url: string;
|
|
43
|
+
readonly port: number;
|
|
44
|
+
readonly token: string;
|
|
45
|
+
close(): Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const OUTPUT_KEEP = 200_000;
|
|
49
|
+
const COOKIE = 'quiesco_ui';
|
|
50
|
+
const MIME: Record<string, string> = {
|
|
51
|
+
'.html': 'text/html; charset=utf-8',
|
|
52
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
53
|
+
'.css': 'text/css; charset=utf-8',
|
|
54
|
+
'.svg': 'image/svg+xml',
|
|
55
|
+
'.woff2': 'font/woff2',
|
|
56
|
+
'.png': 'image/png',
|
|
57
|
+
'.jpg': 'image/jpeg',
|
|
58
|
+
'.jpeg': 'image/jpeg',
|
|
59
|
+
'.webp': 'image/webp',
|
|
60
|
+
'.mp4': 'video/mp4',
|
|
61
|
+
'.webm': 'video/webm',
|
|
62
|
+
'.json': 'application/json; charset=utf-8',
|
|
63
|
+
'.ico': 'image/x-icon',
|
|
64
|
+
};
|
|
65
|
+
/** Evidence and source files: media as such, everything else as plain text (never HTML: no script). */
|
|
66
|
+
function fileType(file: string): string {
|
|
67
|
+
const ext = path.extname(file).toLowerCase();
|
|
68
|
+
return ['.png', '.jpg', '.jpeg', '.webp', '.mp4', '.webm', '.json'].includes(ext) ? (MIME[ext] as string) : 'text/plain; charset=utf-8';
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function version(): string {
|
|
72
|
+
return (createRequire(import.meta.url)('../package.json') as { version: string }).version;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** `child` is `root` or inside it, after resolving symlinks. */
|
|
76
|
+
function inside(root: string, child: string): boolean {
|
|
77
|
+
try {
|
|
78
|
+
const r = fs.realpathSync(root);
|
|
79
|
+
const c = fs.realpathSync(child);
|
|
80
|
+
return c === r || c.startsWith(r + path.sep);
|
|
81
|
+
} catch {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function startUiServer(options: UiServerOptions): Promise<UiServer> {
|
|
87
|
+
const host = options.host ?? '127.0.0.1';
|
|
88
|
+
const token = options.token ?? randomBytes(16).toString('hex');
|
|
89
|
+
const info: UiInfo = { project: path.basename(options.cwd), runner: options.runner, platform: options.platform, version: version() };
|
|
90
|
+
const state = new RunState();
|
|
91
|
+
const clients = new Set<WebSocket>();
|
|
92
|
+
let list: TestList | null = null;
|
|
93
|
+
let listing = false;
|
|
94
|
+
let relistQueued = false;
|
|
95
|
+
let running: RunningInfo | null = null;
|
|
96
|
+
let handle: RunHandle | null = null;
|
|
97
|
+
let output = '';
|
|
98
|
+
let port = 0;
|
|
99
|
+
|
|
100
|
+
const send = (ws: WebSocket, m: ServerMessage) => {
|
|
101
|
+
if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(m));
|
|
102
|
+
};
|
|
103
|
+
const broadcast = (m: ServerMessage) => {
|
|
104
|
+
const data = JSON.stringify(m);
|
|
105
|
+
for (const ws of clients) if (ws.readyState === ws.OPEN) ws.send(data);
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Running chosen tests: Vitest and Jest report the other tests of their files as skipped (filtered
|
|
110
|
+
* out). Those reports are dropped, so a test keeps its last real result, and the total is the
|
|
111
|
+
* number of chosen tests.
|
|
112
|
+
*/
|
|
113
|
+
let chosen: ReadonlySet<string> | null = null;
|
|
114
|
+
const filtered = (event: RunEvent): RunEvent | null => {
|
|
115
|
+
if (chosen === null) return event;
|
|
116
|
+
if (event.type === 'run:start' || event.type === 'total:update') return { ...event, total: chosen.size, totalIsEstimate: false };
|
|
117
|
+
if ((event.type === 'test:start' || event.type === 'test:end') && !chosen.has(event.test.id)) {
|
|
118
|
+
if (event.type === 'test:start' || event.status === 'skipped') return null;
|
|
119
|
+
}
|
|
120
|
+
return event;
|
|
121
|
+
};
|
|
122
|
+
const events = new RunEventServer({
|
|
123
|
+
onEvent: (raw) => {
|
|
124
|
+
const event = filtered(raw);
|
|
125
|
+
if (event === null) return;
|
|
126
|
+
state.apply(event);
|
|
127
|
+
broadcast({ type: 'event', event });
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
await events.listen();
|
|
131
|
+
|
|
132
|
+
const knownTests = (): Map<string, TestRef> => {
|
|
133
|
+
const m = new Map<string, TestRef>();
|
|
134
|
+
for (const t of list?.tests ?? []) m.set(t.id, t);
|
|
135
|
+
for (const t of state.tests.values()) m.set(t.test.id, { ...m.get(t.test.id), ...t.test });
|
|
136
|
+
return m;
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
const relist = async (): Promise<void> => {
|
|
140
|
+
if (listing || running !== null) {
|
|
141
|
+
relistQueued = true;
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
listing = true;
|
|
145
|
+
broadcast({ type: 'list', list, listing: true });
|
|
146
|
+
try {
|
|
147
|
+
list = await options.listTests();
|
|
148
|
+
} catch (e) {
|
|
149
|
+
list = { runner: options.runner, files: [], tests: [], errors: [{ message: (e as Error).message }] };
|
|
150
|
+
}
|
|
151
|
+
listing = false;
|
|
152
|
+
broadcast({ type: 'list', list, listing: false });
|
|
153
|
+
watchFiles();
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const run = (target: RunTarget): { code: NoticeCode; message: string } | null => {
|
|
157
|
+
if (running !== null) return { code: 'busy', message: 'A run is already in progress (one device: one run at a time).' };
|
|
158
|
+
let args: string[];
|
|
159
|
+
try {
|
|
160
|
+
args = targetArgs(options.runner, target, knownTests());
|
|
161
|
+
} catch (e) {
|
|
162
|
+
return { code: 'unknown-tests', message: (e as Error).message };
|
|
163
|
+
}
|
|
164
|
+
output = '';
|
|
165
|
+
chosen = target.kind === 'tests' ? new Set(target.ids) : null;
|
|
166
|
+
running = { target, args, startedAt: Date.now() };
|
|
167
|
+
broadcast({ type: 'run', running });
|
|
168
|
+
const h = options.startRun(args, events.env(), (stream, text) => {
|
|
169
|
+
output = (output + text).slice(-OUTPUT_KEEP);
|
|
170
|
+
broadcast({ type: 'output', stream, text });
|
|
171
|
+
});
|
|
172
|
+
handle = h;
|
|
173
|
+
void h.exited.then(async (code) => {
|
|
174
|
+
await events.drain();
|
|
175
|
+
state.runnerExited(code);
|
|
176
|
+
running = null;
|
|
177
|
+
handle = null;
|
|
178
|
+
broadcast({ type: 'run', running: null, exitCode: code, state: state.snapshot() });
|
|
179
|
+
if (relistQueued) {
|
|
180
|
+
relistQueued = false;
|
|
181
|
+
void relist();
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
return null;
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
// Test files changed: list again (debounced).
|
|
188
|
+
let watchers: fs.FSWatcher[] = [];
|
|
189
|
+
let relistTimer: NodeJS.Timeout | null = null;
|
|
190
|
+
function watchFiles(): void {
|
|
191
|
+
for (const w of watchers) w.close();
|
|
192
|
+
watchers = [];
|
|
193
|
+
const dirs = new Set((list?.files ?? []).map((f) => path.dirname(path.resolve(options.cwd, f))));
|
|
194
|
+
for (const dir of dirs) {
|
|
195
|
+
try {
|
|
196
|
+
const w = fs.watch(dir, () => {
|
|
197
|
+
if (relistTimer !== null) clearTimeout(relistTimer);
|
|
198
|
+
relistTimer = setTimeout(() => void relist(), 400);
|
|
199
|
+
});
|
|
200
|
+
w.unref();
|
|
201
|
+
watchers.push(w);
|
|
202
|
+
} catch {
|
|
203
|
+
// A directory that went away: the next listing drops it.
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const allowedHost = (h: string | undefined) => h !== undefined && [`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`].includes(h);
|
|
209
|
+
const cookieToken = (req: http.IncomingMessage) => /(?:^|;\s*)quiesco_ui=([0-9a-f]+)/.exec(req.headers.cookie ?? '')?.[1];
|
|
210
|
+
|
|
211
|
+
const httpServer = http.createServer((req, res) => {
|
|
212
|
+
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? host}`);
|
|
213
|
+
const headers = { 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer', 'Cache-Control': 'no-store' };
|
|
214
|
+
if (!allowedHost(req.headers.host)) {
|
|
215
|
+
res.writeHead(403, headers).end('Forbidden host');
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const queryToken = url.searchParams.get('token');
|
|
219
|
+
const authorized = queryToken === token || cookieToken(req) === token;
|
|
220
|
+
if (!authorized) {
|
|
221
|
+
res.writeHead(401, { ...headers, 'Content-Type': 'text/plain; charset=utf-8' }).end('Open the URL quiesco ui printed (it carries the token).');
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
const setCookie = queryToken === token ? { 'Set-Cookie': `${COOKIE}=${token}; HttpOnly; SameSite=Strict; Path=/` } : {};
|
|
225
|
+
|
|
226
|
+
if (url.pathname === '/api/file' || url.pathname === '/api/source') {
|
|
227
|
+
const p = url.searchParams.get('path') ?? '';
|
|
228
|
+
const file = path.resolve(options.cwd, p);
|
|
229
|
+
const ok =
|
|
230
|
+
url.pathname === '/api/file'
|
|
231
|
+
? inside(options.artifactsDir, file)
|
|
232
|
+
: (list?.files ?? []).some((f) => path.resolve(options.cwd, f) === file) && inside(options.cwd, file);
|
|
233
|
+
if (!ok || !fs.existsSync(file) || !fs.statSync(file).isFile()) {
|
|
234
|
+
res.writeHead(404, headers).end('Not found');
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
res.writeHead(200, { ...headers, 'Content-Type': fileType(file), 'Content-Security-Policy': "default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'" });
|
|
238
|
+
fs.createReadStream(file).pipe(res);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const csp = `default-src 'self'; connect-src 'self' ws://${req.headers.host}; img-src 'self' data: blob:; media-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; frame-ancestors 'none'`;
|
|
243
|
+
if (options.staticDir === null) {
|
|
244
|
+
res.writeHead(200, { ...headers, ...setCookie, 'Content-Type': 'text/html; charset=utf-8', 'Content-Security-Policy': csp }).end('<!doctype html><title>Quiesco</title><p>Quiesco UI</p>');
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
const rel = decodeURIComponent(url.pathname).replace(/^\/+/, '');
|
|
248
|
+
let file = path.join(options.staticDir, rel === '' ? 'index.html' : rel);
|
|
249
|
+
if (!inside(options.staticDir, file) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) file = path.join(options.staticDir, 'index.html');
|
|
250
|
+
const type = MIME[path.extname(file).toLowerCase()] ?? 'application/octet-stream';
|
|
251
|
+
res.writeHead(200, { ...headers, ...setCookie, 'Content-Type': type, 'Content-Security-Policy': csp });
|
|
252
|
+
fs.createReadStream(file).pipe(res);
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload: 64 * 1024 });
|
|
256
|
+
httpServer.on('upgrade', (req, socket, head) => {
|
|
257
|
+
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? host}`);
|
|
258
|
+
const origin = req.headers.origin;
|
|
259
|
+
const originOk = origin === undefined || [`http://127.0.0.1:${port}`, `http://localhost:${port}`, `http://[::1]:${port}`].includes(origin);
|
|
260
|
+
const tokenOk = url.searchParams.get('token') === token || cookieToken(req) === token;
|
|
261
|
+
if (url.pathname !== '/ws' || !allowedHost(req.headers.host) || !originOk || !tokenOk) {
|
|
262
|
+
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
|
|
263
|
+
socket.destroy();
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
267
|
+
clients.add(ws);
|
|
268
|
+
ws.on('close', () => clients.delete(ws));
|
|
269
|
+
ws.on('message', (data) => {
|
|
270
|
+
let m: ClientMessage;
|
|
271
|
+
try {
|
|
272
|
+
m = JSON.parse(String(data)) as ClientMessage;
|
|
273
|
+
} catch {
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
if (m.type === 'run') {
|
|
277
|
+
const problem = run(m.target);
|
|
278
|
+
if (problem !== null) send(ws, { type: 'notice', level: 'error', ...problem });
|
|
279
|
+
} else if (m.type === 'cancel') {
|
|
280
|
+
handle?.stop();
|
|
281
|
+
} else if (m.type === 'list') {
|
|
282
|
+
void relist();
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
send(ws, { type: 'welcome', info, list, listing, state: state.snapshot(), running, output });
|
|
286
|
+
});
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
await new Promise<void>((resolve, reject) => {
|
|
290
|
+
httpServer.once('error', reject);
|
|
291
|
+
httpServer.listen(options.port ?? 0, host, () => resolve());
|
|
292
|
+
});
|
|
293
|
+
port = (httpServer.address() as { port: number }).port;
|
|
294
|
+
void relist();
|
|
295
|
+
|
|
296
|
+
return {
|
|
297
|
+
url: `http://${host === '127.0.0.1' ? '127.0.0.1' : host}:${port}/?token=${token}`,
|
|
298
|
+
port,
|
|
299
|
+
token,
|
|
300
|
+
async close() {
|
|
301
|
+
handle?.stop(2000);
|
|
302
|
+
if (handle !== null) await handle.exited;
|
|
303
|
+
for (const w of watchers) w.close();
|
|
304
|
+
if (relistTimer !== null) clearTimeout(relistTimer);
|
|
305
|
+
for (const ws of clients) ws.terminate();
|
|
306
|
+
wss.close();
|
|
307
|
+
await new Promise<void>((resolve) => httpServer.close(() => resolve()));
|
|
308
|
+
await events.close();
|
|
309
|
+
},
|
|
310
|
+
};
|
|
311
|
+
}
|
package/src/spawn.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Start a test run as a child process: its output to a callback, stoppable as a whole (the runner runs
|
|
3
|
+
* under npx, so stopping must reach the runner and its workers, not only npx).
|
|
4
|
+
*/
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
|
|
7
|
+
export interface RunHandle {
|
|
8
|
+
/** Resolves with the exit code (130 when stopped with SIGINT). */
|
|
9
|
+
readonly exited: Promise<number>;
|
|
10
|
+
/** Ctrl-C to the whole process tree; SIGKILL after `graceMs` if it is still there. */
|
|
11
|
+
stop(graceMs?: number): void;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface SpawnRunOptions {
|
|
15
|
+
cwd: string;
|
|
16
|
+
env: NodeJS.ProcessEnv;
|
|
17
|
+
onOutput: (stream: 'stdout' | 'stderr', text: string) => void;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const isWindows = process.platform === 'win32';
|
|
21
|
+
|
|
22
|
+
export function spawnRun(command: string, args: readonly string[], options: SpawnRunOptions): RunHandle {
|
|
23
|
+
// Its own process group (POSIX), so stop() reaches npx, the runner and its workers.
|
|
24
|
+
const child = spawn(command, [...args], { cwd: options.cwd, env: options.env, stdio: ['ignore', 'pipe', 'pipe'], detached: !isWindows, shell: isWindows });
|
|
25
|
+
child.stdout.setEncoding('utf8').on('data', (t: string) => options.onOutput('stdout', t));
|
|
26
|
+
child.stderr.setEncoding('utf8').on('data', (t: string) => options.onOutput('stderr', t));
|
|
27
|
+
const exited = new Promise<number>((resolve) => {
|
|
28
|
+
child.on('error', (e) => {
|
|
29
|
+
options.onOutput('stderr', `${e.message}\n`);
|
|
30
|
+
resolve(127);
|
|
31
|
+
});
|
|
32
|
+
child.on('close', (code, signal) => resolve(code ?? (signal === 'SIGINT' ? 130 : signal !== null ? 143 : 1)));
|
|
33
|
+
});
|
|
34
|
+
const signal = (s: NodeJS.Signals) => {
|
|
35
|
+
if (child.pid === undefined || child.exitCode !== null || child.signalCode !== null) return;
|
|
36
|
+
try {
|
|
37
|
+
if (isWindows) spawn('taskkill', ['/pid', String(child.pid), '/T', ...(s === 'SIGKILL' ? ['/F'] : [])]);
|
|
38
|
+
else process.kill(-child.pid, s);
|
|
39
|
+
} catch {
|
|
40
|
+
// Already gone.
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
return {
|
|
44
|
+
exited,
|
|
45
|
+
stop(graceMs = 10_000) {
|
|
46
|
+
signal('SIGINT');
|
|
47
|
+
const timer = setTimeout(() => signal('SIGKILL'), graceMs);
|
|
48
|
+
timer.unref();
|
|
49
|
+
void exited.then(() => clearTimeout(timer));
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
package/src/targets.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What to run, as runner arguments (findings P0): the UI asks for all tests, one file, or some tests;
|
|
3
|
+
* each runner selects them its own way.
|
|
4
|
+
*
|
|
5
|
+
* - cucumber: `file:line[:line…]` (a Scenario line, or an Examples row's line). NOTE: cucumber-js adds
|
|
6
|
+
* command line paths to the `paths` of its config instead of replacing them, so a config with `paths`
|
|
7
|
+
* runs more than asked (Quiesco's init no longer writes `paths`).
|
|
8
|
+
* - vitest: `file:line` (a `test.each` line runs every row).
|
|
9
|
+
* - jest: `--runTestsByPath <files>` and `-t '^(full name|…)$'` (titles joined with spaces; Jest matches
|
|
10
|
+
* case-insensitively, so a test with the same name in another chosen file runs too).
|
|
11
|
+
*/
|
|
12
|
+
import type { RunnerName, TestRef } from '@quiesco/protocol';
|
|
13
|
+
|
|
14
|
+
export type RunTarget = { kind: 'all' } | { kind: 'file'; file: string } | { kind: 'tests'; ids: readonly string[] };
|
|
15
|
+
|
|
16
|
+
const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
17
|
+
|
|
18
|
+
/** Runner arguments selecting `target`; `tests` resolves test ids to their file and line. */
|
|
19
|
+
export function targetArgs(runner: RunnerName, target: RunTarget, tests: ReadonlyMap<string, TestRef>): string[] {
|
|
20
|
+
if (target.kind === 'all') return [];
|
|
21
|
+
if (target.kind === 'file') return runner === 'jest' ? ['--runTestsByPath', target.file] : [target.file];
|
|
22
|
+
|
|
23
|
+
const refs = target.ids.flatMap((id) => {
|
|
24
|
+
const t = tests.get(id);
|
|
25
|
+
return t !== undefined ? [t] : [];
|
|
26
|
+
});
|
|
27
|
+
if (refs.length === 0) throw new Error('none of the chosen tests is known (list the tests again)');
|
|
28
|
+
const byFile = new Map<string, TestRef[]>();
|
|
29
|
+
for (const t of refs) byFile.set(t.file, [...(byFile.get(t.file) ?? []), t]);
|
|
30
|
+
|
|
31
|
+
if (runner === 'jest') {
|
|
32
|
+
const names = [...new Set(refs.map((t) => escapeRegExp(t.path.join(' '))))];
|
|
33
|
+
return ['--runTestsByPath', ...byFile.keys(), '-t', `^(${names.join('|')})$`];
|
|
34
|
+
}
|
|
35
|
+
const out: string[] = [];
|
|
36
|
+
for (const [file, ts] of byFile) {
|
|
37
|
+
const lines = [...new Set(ts.flatMap((t) => (t.line !== undefined ? [t.line] : [])))].sort((a, b) => a - b);
|
|
38
|
+
if (lines.length === 0 || lines.length < ts.length) {
|
|
39
|
+
out.push(file); // a test without a line: the whole file
|
|
40
|
+
} else if (runner === 'cucumber') {
|
|
41
|
+
out.push(`${file}:${lines.join(':')}`);
|
|
42
|
+
} else {
|
|
43
|
+
for (const l of lines) out.push(`${file}:${l}`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
}
|