quiesco 0.2.0 → 0.4.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 (65) hide show
  1. package/README.md +3 -1
  2. package/dist/cli.d.ts +2 -1
  3. package/dist/cli.d.ts.map +1 -1
  4. package/dist/cli.js +11 -6
  5. package/dist/cli.js.map +1 -1
  6. package/dist/commands/doctor.d.ts.map +1 -1
  7. package/dist/commands/doctor.js +81 -7
  8. package/dist/commands/doctor.js.map +1 -1
  9. package/dist/commands/init.d.ts.map +1 -1
  10. package/dist/commands/init.js +108 -22
  11. package/dist/commands/init.js.map +1 -1
  12. package/dist/commands/list.d.ts +16 -0
  13. package/dist/commands/list.d.ts.map +1 -0
  14. package/dist/commands/list.js +56 -0
  15. package/dist/commands/list.js.map +1 -0
  16. package/dist/commands/test.d.ts +20 -1
  17. package/dist/commands/test.d.ts.map +1 -1
  18. package/dist/commands/test.js +14 -6
  19. package/dist/commands/test.js.map +1 -1
  20. package/dist/commands/ui.d.ts +43 -0
  21. package/dist/commands/ui.d.ts.map +1 -0
  22. package/dist/commands/ui.js +121 -0
  23. package/dist/commands/ui.js.map +1 -0
  24. package/dist/context.d.ts +22 -0
  25. package/dist/context.d.ts.map +1 -1
  26. package/dist/context.js +31 -0
  27. package/dist/context.js.map +1 -1
  28. package/dist/dev-server.d.ts +2 -0
  29. package/dist/dev-server.d.ts.map +1 -1
  30. package/dist/dev-server.js +4 -2
  31. package/dist/dev-server.js.map +1 -1
  32. package/dist/packages.d.ts +17 -0
  33. package/dist/packages.d.ts.map +1 -0
  34. package/dist/packages.js +40 -0
  35. package/dist/packages.js.map +1 -0
  36. package/dist/progress/render.d.ts +31 -0
  37. package/dist/progress/render.d.ts.map +1 -0
  38. package/dist/progress/render.js +89 -0
  39. package/dist/progress/render.js.map +1 -0
  40. package/dist/progress/run.d.ts +24 -0
  41. package/dist/progress/run.d.ts.map +1 -0
  42. package/dist/progress/run.js +95 -0
  43. package/dist/progress/run.js.map +1 -0
  44. package/dist/progress/sticky.d.ts +25 -0
  45. package/dist/progress/sticky.d.ts.map +1 -0
  46. package/dist/progress/sticky.js +90 -0
  47. package/dist/progress/sticky.js.map +1 -0
  48. package/dist/project.d.ts +23 -0
  49. package/dist/project.d.ts.map +1 -0
  50. package/dist/project.js +74 -0
  51. package/dist/project.js.map +1 -0
  52. package/package.json +3 -3
  53. package/src/cli.ts +11 -7
  54. package/src/commands/doctor.ts +83 -7
  55. package/src/commands/init.ts +101 -19
  56. package/src/commands/list.ts +65 -0
  57. package/src/commands/test.ts +17 -7
  58. package/src/commands/ui.ts +152 -0
  59. package/src/context.ts +50 -0
  60. package/src/dev-server.ts +6 -2
  61. package/src/packages.ts +42 -0
  62. package/src/progress/render.ts +117 -0
  63. package/src/progress/run.ts +105 -0
  64. package/src/progress/sticky.ts +95 -0
  65. package/src/project.ts +76 -0
@@ -0,0 +1,152 @@
1
+ /**
2
+ * `quiesco ui [--platform …] [--runner …] [--workers N] [--port N] [--no-open] [runner arguments…]` (P5):
3
+ * the test UI. Serves @quiesco/ui (installed in the project, loaded only here so the CLI stays small)
4
+ * on 127.0.0.1, keeps the Metro dev server up while it runs, and runs what the browser asks for the way
5
+ * `quiesco test` would (same runner, runner arguments, workers and cucumber formatter) with the chosen
6
+ * tests added. Ctrl-C stops it.
7
+ */
8
+ import path from 'node:path';
9
+ import { pathToFileURL } from 'node:url';
10
+
11
+ import type { QuiescoConfig, RunnerName, TestList } from '@quiesco/core';
12
+ import { listTests } from '@quiesco/core';
13
+
14
+ import type { CliContext } from '../context.js';
15
+ import { parsePlatform, takeFlag, takeOption } from '../context.js';
16
+ import { ensureDevServer } from '../dev-server.js';
17
+ import { cucumberFormatArgs } from '../progress/run.js';
18
+ import { RUNNERS, defaultTestDeps, isRunner } from './test.js';
19
+
20
+ export const UI_HELP = `Usage: quiesco ui [options] [runner arguments…]
21
+
22
+ Opens the test UI in the browser: the test tree, run all / a file / a test with a click, live progress,
23
+ failures with Quiesco's evidence. Needs @quiesco/ui in the project (npm i -D @quiesco/ui).
24
+
25
+ Options:
26
+ --platform ios|android|web Platform to test (or set QUIESCO_PLATFORM)
27
+ --runner cucumber|jest|vitest Test runner (default: cucumber)
28
+ --workers N Run N workers, each on a device of its own
29
+ --port N Port of the UI (default: a free one)
30
+ --no-open Do not open the browser
31
+ -h, --help Show this help
32
+
33
+ Runner arguments (e.g. --config vitest.e2e.config.mts) are used for every run and for listing the tests.
34
+
35
+ Examples:
36
+ quiesco ui --platform web
37
+ quiesco ui --platform ios --runner vitest --config vitest.e2e.config.mts`;
38
+
39
+ /** The parts of @quiesco/ui the CLI uses (structural: the CLI does not depend on it). */
40
+ interface RunHandleLike {
41
+ readonly exited: Promise<number>;
42
+ stop(graceMs?: number): void;
43
+ }
44
+ export interface UiModule {
45
+ startUiServer(options: {
46
+ cwd: string;
47
+ runner: RunnerName;
48
+ platform: string;
49
+ startRun(args: string[], env: Record<string, string>, onOutput: (stream: 'stdout' | 'stderr', text: string) => void): RunHandleLike;
50
+ listTests(): Promise<TestList>;
51
+ artifactsDir: string;
52
+ staticDir: string | null;
53
+ port?: number;
54
+ }): Promise<{ url: string; close(): Promise<void> }>;
55
+ spawnRun(command: string, args: readonly string[], options: { cwd: string; env: NodeJS.ProcessEnv; onOutput: (stream: 'stdout' | 'stderr', text: string) => void }): RunHandleLike;
56
+ }
57
+
58
+ export interface UiDeps {
59
+ loadUi(ctx: CliContext): Promise<{ module: UiModule; staticDir: string | null } | null>;
60
+ loadConfig(cwd: string, env: NodeJS.ProcessEnv): Promise<QuiescoConfig | null>;
61
+ listTests: typeof listTests;
62
+ /** Resolves when the user stops the UI (Ctrl-C). */
63
+ untilInterrupted(ctx: CliContext): Promise<void>;
64
+ }
65
+
66
+ export const defaultUiDeps: UiDeps = {
67
+ loadUi: async (ctx) => {
68
+ const entry = ctx.resolveFrom(ctx.cwd, '@quiesco/ui');
69
+ if (entry === null) return null;
70
+ const module = (await import(pathToFileURL(entry).href)) as UiModule;
71
+ const staticDir = path.join(path.dirname(entry), 'web');
72
+ return { module, staticDir: ctx.exists(path.join(staticDir, 'index.html')) ? staticDir : null };
73
+ },
74
+ loadConfig: defaultTestDeps.loadConfig,
75
+ listTests,
76
+ untilInterrupted: (ctx) => new Promise<void>((resolve) => void ctx.onInterrupt(async () => resolve())),
77
+ };
78
+
79
+ function openBrowser(ctx: CliContext, url: string): void {
80
+ const [command, args] = ctx.platform === 'darwin' ? ['open', [url]] : ctx.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : ['xdg-open', [url]];
81
+ void ctx.exec(command as string, args as string[]).catch(() => undefined);
82
+ }
83
+
84
+ export async function uiCommand(args: readonly string[], ctx: CliContext, deps: UiDeps = defaultUiDeps): Promise<number> {
85
+ if (args.includes('-h') || args.includes('--help')) {
86
+ ctx.out(UI_HELP);
87
+ return 0;
88
+ }
89
+ const p = takeOption(args, '--platform');
90
+ const r = takeOption(p.rest, '--runner');
91
+ const w = takeOption(r.rest, '--workers');
92
+ const portOpt = takeOption(w.rest, '--port');
93
+ const noOpen = takeFlag(portOpt.rest, '--no-open');
94
+ const rest = noOpen.rest.filter((a) => a !== '--');
95
+ const platform = parsePlatform(p.value) ?? parsePlatform(ctx.env['QUIESCO_PLATFORM']);
96
+ if (platform === undefined) {
97
+ ctx.err('quiesco ui: choose a platform with --platform ios|android|web (or set QUIESCO_PLATFORM). See quiesco ui --help.');
98
+ return 2;
99
+ }
100
+ const runner = r.value ?? 'cucumber';
101
+ if (!isRunner(runner)) {
102
+ ctx.err(`quiesco ui: unknown runner "${runner}" (cucumber, jest or vitest).`);
103
+ return 2;
104
+ }
105
+ const workers = w.value !== undefined ? Number(w.value) : undefined;
106
+ if (workers !== undefined && (!Number.isInteger(workers) || workers < 1)) {
107
+ ctx.err(`quiesco ui: --workers takes a whole number ≥ 1 (got "${w.value}").`);
108
+ return 2;
109
+ }
110
+ const port = portOpt.value !== undefined ? Number(portOpt.value) : undefined;
111
+ if (port !== undefined && (!Number.isInteger(port) || port < 0 || port > 65535)) {
112
+ ctx.err(`quiesco ui: --port takes a port number (got "${portOpt.value}").`);
113
+ return 2;
114
+ }
115
+
116
+ const ui = await deps.loadUi(ctx);
117
+ if (ui === null) {
118
+ ctx.err('quiesco ui: @quiesco/ui is not installed in this project. Install it: npm i -D @quiesco/ui');
119
+ return 1;
120
+ }
121
+ const config = await deps.loadConfig(ctx.cwd, ctx.env);
122
+ let devServer;
123
+ try {
124
+ devServer = config === null ? null : await ensureDevServer(ctx, config, platform);
125
+ } catch (e) {
126
+ ctx.err(`quiesco ui: ${(e as Error).message}`);
127
+ return 1;
128
+ }
129
+ const spec = RUNNERS[runner];
130
+ const base = [...spec.command, ...(workers !== undefined ? spec.workers(workers) : []), ...(runner === 'cucumber' ? cucumberFormatArgs(ctx) : []), ...rest];
131
+ try {
132
+ const server = await ui.module.startUiServer({
133
+ cwd: ctx.cwd,
134
+ runner,
135
+ platform,
136
+ artifactsDir: path.resolve(ctx.cwd, config?.artifacts?.dir ?? 'artifacts'),
137
+ staticDir: ui.staticDir,
138
+ ...(port !== undefined ? { port } : {}),
139
+ listTests: () => deps.listTests({ runner, cwd: ctx.cwd, args: rest, env: ctx.env }),
140
+ // npx runs the project's own runner; the chosen tests go last (after the user's arguments).
141
+ startRun: (targetArgs, env, onOutput) => ui.module.spawnRun('npx', [...base, ...targetArgs], { cwd: ctx.cwd, env: { ...ctx.env, QUIESCO_PLATFORM: platform, ...devServer?.env, ...env }, onOutput }),
142
+ });
143
+ ctx.out(`quiesco ui: ${server.url}`);
144
+ ctx.out('quiesco ui: Ctrl-C stops it.');
145
+ if (!noOpen.present && ctx.interactive) openBrowser(ctx, server.url);
146
+ await deps.untilInterrupted(ctx);
147
+ await server.close();
148
+ return 0;
149
+ } finally {
150
+ await devServer?.stop();
151
+ }
152
+ }
package/src/context.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { spawn as nodeSpawn } from 'node:child_process';
6
6
  import fs from 'node:fs';
7
+ import { createRequire } from 'node:module';
7
8
  import path from 'node:path';
8
9
 
9
10
  export interface ExecResult {
@@ -14,6 +15,8 @@ export interface ExecResult {
14
15
 
15
16
  export interface CliContext {
16
17
  cwd: string;
18
+ /** The version of this CLI (`quiesco init` installs the same version of every Quiesco package). */
19
+ version: string;
17
20
  env: NodeJS.ProcessEnv;
18
21
  out(line: string): void;
19
22
  err(line: string): void;
@@ -21,6 +24,12 @@ export interface CliContext {
21
24
  exec(command: string, args: readonly string[], options?: { cwd?: string; env?: NodeJS.ProcessEnv }): Promise<ExecResult>;
22
25
  /** Run a command with the terminal attached (cucumber-js); resolves with its exit code. */
23
26
  run(command: string, args: readonly string[], options?: { cwd?: string; env?: NodeJS.ProcessEnv }): Promise<number>;
27
+ /** Run a command with stdin attached and its output handed to the callbacks (the progress bar keeps the last line). */
28
+ runPiped(command: string, args: readonly string[], options: { cwd?: string; env?: NodeJS.ProcessEnv; onStdout: (chunk: string) => void; onStderr: (chunk: string) => void }): Promise<number>;
29
+ /** The terminal, when stdout is one (null when piped or redirected). */
30
+ terminal: Terminal | null;
31
+ /** Resolve `specifier` as code in `dir` would (the project's own packages); null when it is not installed. */
32
+ resolveFrom(dir: string, specifier: string): string | null;
24
33
  readFile(path: string): string | null;
25
34
  writeFile(path: string, content: string): void;
26
35
  exists(path: string): boolean;
@@ -38,6 +47,16 @@ export interface CliContext {
38
47
  sleep(ms: number): Promise<void>;
39
48
  }
40
49
 
50
+ export interface Terminal {
51
+ columns(): number;
52
+ /** Whether colors may be used (a color terminal, NO_COLOR not set). */
53
+ color: boolean;
54
+ stdout(text: string): void;
55
+ stderr(text: string): void;
56
+ /** Called on Ctrl-C without exiting (the child gets the signal too and ends the run); returns a remover. */
57
+ onInterrupt(handler: () => void): () => void;
58
+ }
59
+
41
60
  export interface BackgroundProcess {
42
61
  /** Resolves with the exit code when the process ends. */
43
62
  readonly exited: Promise<number>;
@@ -50,6 +69,7 @@ const isWindows = process.platform === 'win32';
50
69
  export function defaultContext(): CliContext {
51
70
  return {
52
71
  cwd: process.cwd(),
72
+ version: (createRequire(import.meta.url)('../package.json') as { version: string }).version,
53
73
  env: process.env,
54
74
  out: (line) => process.stdout.write(`${line}\n`),
55
75
  err: (line) => process.stderr.write(`${line}\n`),
@@ -69,6 +89,22 @@ export function defaultContext(): CliContext {
69
89
  child.on('error', () => resolve(127));
70
90
  child.on('close', (code) => resolve(code ?? 1));
71
91
  }),
92
+ runPiped: (command, args, options) =>
93
+ new Promise((resolve) => {
94
+ const child = nodeSpawn(command, [...args], { cwd: options.cwd, env: options.env ?? process.env, stdio: ['inherit', 'pipe', 'pipe'], shell: isWindows });
95
+ child.stdout?.setEncoding('utf8').on('data', options.onStdout);
96
+ child.stderr?.setEncoding('utf8').on('data', options.onStderr);
97
+ child.on('error', () => resolve(127));
98
+ child.on('close', (code, signal) => resolve(code ?? (signal === 'SIGINT' ? 130 : signal !== null ? 143 : 1)));
99
+ }),
100
+ terminal: process.stdout.isTTY === true ? ttyTerminal() : null,
101
+ resolveFrom: (dir, specifier) => {
102
+ try {
103
+ return createRequire(path.join(dir, 'package.json')).resolve(specifier);
104
+ } catch {
105
+ return null;
106
+ }
107
+ },
72
108
  readFile: (p) => {
73
109
  try {
74
110
  return fs.readFileSync(p, 'utf8');
@@ -136,6 +172,20 @@ export function defaultContext(): CliContext {
136
172
  };
137
173
  }
138
174
 
175
+ function ttyTerminal(): Terminal {
176
+ return {
177
+ // Some pseudo-terminals report 0 columns.
178
+ columns: () => (process.stdout.columns > 0 ? process.stdout.columns : 80),
179
+ color: process.env['NO_COLOR'] === undefined && process.stdout.hasColors?.() === true,
180
+ stdout: (text) => void process.stdout.write(text),
181
+ stderr: (text) => void process.stderr.write(text),
182
+ onInterrupt: (handler) => {
183
+ process.on('SIGINT', handler);
184
+ return () => void process.off('SIGINT', handler);
185
+ },
186
+ };
187
+ }
188
+
139
189
  /** `--name value` / `--name=value`; returns the value and the remaining arguments. */
140
190
  export function takeOption(args: readonly string[], name: string): { value: string | undefined; rest: string[] } {
141
191
  const rest: string[] = [];
package/src/dev-server.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  import path from 'node:path';
9
9
 
10
10
  import type { QuiescoConfig } from '@quiesco/core';
11
+ import { REUSED_DEV_SERVER_ENV } from '@quiesco/core';
11
12
 
12
13
  import type { BackgroundProcess, CliContext, CliPlatform } from './context.js';
13
14
 
@@ -31,9 +32,11 @@ export async function metroRunning(ctx: CliContext, url: string): Promise<boolea
31
32
  export interface DevServer {
32
33
  /** Stops Metro when this run started it; nothing otherwise. */
33
34
  stop(): Promise<void>;
35
+ /** For the runner: QUIESCO_DEV_SERVER_REUSED=<url> when a Metro Quiesco did not start is used (issue #19). */
36
+ env: Record<string, string>;
34
37
  }
35
38
 
36
- const NOTHING: DevServer = { stop: async () => {} };
39
+ const NOTHING: DevServer = { stop: async () => {}, env: {} };
37
40
 
38
41
  /**
39
42
  * Make sure the dev server the app needs is running. Returns how to stop what was started. Throws when it
@@ -44,7 +47,7 @@ export async function ensureDevServer(ctx: CliContext, config: QuiescoConfig, pl
44
47
  if (url === null) return NOTHING;
45
48
  if (await metroRunning(ctx, url)) {
46
49
  ctx.out(`quiesco: using the Metro dev server at ${url}`);
47
- return NOTHING;
50
+ return { ...NOTHING, env: { [REUSED_DEV_SERVER_ENV]: url } };
48
51
  }
49
52
  const opts = config.devServer ?? {};
50
53
  const where = new URL(url);
@@ -60,6 +63,7 @@ export async function ensureDevServer(ctx: CliContext, config: QuiescoConfig, pl
60
63
  const proc = ctx.spawnBackground(command, args, { cwd: ctx.cwd, env: { ...ctx.env, EXPO_PUBLIC_QUIESCO: '1' }, logFile });
61
64
  const offInterrupt = ctx.onInterrupt(() => proc.stop());
62
65
  const server: DevServer = {
66
+ env: {},
63
67
  stop: async () => {
64
68
  offInterrupt();
65
69
  await proc.stop();
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The Quiesco packages in a project and their installed versions (issue #17): `init` installs the
3
+ * version of the CLI that runs it and checks what landed; `doctor` checks that they agree.
4
+ */
5
+ import path from 'node:path';
6
+
7
+ import type { CliContext } from './context.js';
8
+
9
+ /** The CLI's subcommands, as `quiesco <command>` in package.json scripts may name them. */
10
+ export const CLI_COMMANDS = ['init', 'build', 'test', 'ui', 'list', 'doctor', 'tree', 'devices'] as const;
11
+
12
+ /** `quiesco` and `@quiesco/*`: released together, always the same version. */
13
+ export const isQuiescoPackage = (name: string): boolean => name === 'quiesco' || name.startsWith('@quiesco/');
14
+
15
+ /**
16
+ * The version of `name` that code in `dir` loads: `node_modules/<name>/package.json` in `dir` or the
17
+ * nearest parent that has one (hoisted workspaces). Read directly rather than resolved, because not
18
+ * every package exports `./package.json`. null when it is not installed.
19
+ */
20
+ export function installedVersion(ctx: CliContext, name: string, dir: string = ctx.cwd): string | null {
21
+ for (let d = path.resolve(dir); ; d = path.dirname(d)) {
22
+ const text = ctx.readFile(path.join(d, 'node_modules', name, 'package.json'));
23
+ if (text !== null) {
24
+ try {
25
+ const version = (JSON.parse(text) as { version?: unknown }).version;
26
+ return typeof version === 'string' ? version : null;
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+ if (path.dirname(d) === d) return null;
32
+ }
33
+ }
34
+
35
+ /** Every `quiesco <command>` in the scripts (not `@quiesco/…`, `quiesco.config`, `quiesco --version`). */
36
+ export function scriptCommands(scripts: Record<string, string> | undefined): { script: string; command: string }[] {
37
+ const found: { script: string; command: string }[] = [];
38
+ for (const [script, line] of Object.entries(scripts ?? {})) {
39
+ for (const m of line.matchAll(/(?:^|[^\w@/.-])quiesco\s+([a-z][\w:-]*)/g)) found.push({ script, command: m[1] as string });
40
+ }
41
+ return found;
42
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * The progress bar line of `quiesco test`, from a RunState. Pure (no terminal access) so it can be
3
+ * unit-tested:
4
+ *
5
+ * ▕██████████░░░░░░░░░░▏ 12/30 ✓10 ✗1 ↷1 2m13s ▶ adds a todo
6
+ *
7
+ * - `~30`: the total is an estimate (Vitest) or still growing (Jest).
8
+ * - Several workers: `▶ 1:adds a todo · 2:edits a todo` (worker numbers from 1).
9
+ * - Fits in `width` columns (CJK characters count as two).
10
+ */
11
+ import type { RunState } from '@quiesco/core';
12
+
13
+ export interface RenderOptions {
14
+ width: number;
15
+ color: boolean;
16
+ /** Bar cells (default 20). */
17
+ barWidth?: number;
18
+ /**
19
+ * When the runner was started (epoch ms): the time shown counts from there, so it includes starting the
20
+ * device and the app. Default: from the first test.
21
+ */
22
+ since?: number;
23
+ now?: () => number;
24
+ }
25
+
26
+ // eslint-disable-next-line no-control-regex -- ANSI escape sequences start with ESC
27
+ const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
28
+
29
+ export function stripAnsi(text: string): string {
30
+ return text.replace(ANSI, '');
31
+ }
32
+
33
+ /** East Asian wide and fullwidth characters, and emoji, take two columns. */
34
+ function isWide(code: number): boolean {
35
+ return (
36
+ (code >= 0x1100 && code <= 0x115f) ||
37
+ (code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f) ||
38
+ (code >= 0xac00 && code <= 0xd7a3) ||
39
+ (code >= 0xf900 && code <= 0xfaff) ||
40
+ (code >= 0xfe30 && code <= 0xfe4f) ||
41
+ (code >= 0xff00 && code <= 0xff60) ||
42
+ (code >= 0xffe0 && code <= 0xffe6) ||
43
+ (code >= 0x1f300 && code <= 0x1faff) ||
44
+ (code >= 0x20000 && code <= 0x3fffd)
45
+ );
46
+ }
47
+
48
+ /** Terminal columns taken by `text` (ANSI escapes take none). */
49
+ export function textWidth(text: string): number {
50
+ let w = 0;
51
+ for (const ch of stripAnsi(text)) {
52
+ const code = ch.codePointAt(0) ?? 0;
53
+ if (code < 0x20 || (code >= 0x7f && code < 0xa0) || (code >= 0x300 && code <= 0x36f) || code === 0x200d || (code >= 0xfe00 && code <= 0xfe0f)) continue;
54
+ w += isWide(code) ? 2 : 1;
55
+ }
56
+ return w;
57
+ }
58
+
59
+ /** Cut plain text (no ANSI) to `width` columns, ending with … when cut. */
60
+ export function truncate(text: string, width: number): string {
61
+ if (width <= 0) return '';
62
+ if (textWidth(text) <= width) return text;
63
+ let out = '';
64
+ let w = 0;
65
+ for (const ch of text) {
66
+ const cw = textWidth(ch);
67
+ if (w + cw > width - 1) break;
68
+ out += ch;
69
+ w += cw;
70
+ }
71
+ return `${out}…`;
72
+ }
73
+
74
+ export function formatDuration(ms: number): string {
75
+ const s = Math.floor(ms / 1000);
76
+ if (s < 60) return `${s}s`;
77
+ const m = Math.floor(s / 60);
78
+ if (m < 60) return `${m}m${String(s % 60).padStart(2, '0')}s`;
79
+ return `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`;
80
+ }
81
+
82
+ const paint = (on: boolean, code: string, text: string) => (on ? `\u001b[${code}m${text}\u001b[0m` : text);
83
+
84
+ export function renderBar(state: RunState, options: RenderOptions): string {
85
+ const { width, color } = options;
86
+ const cells = options.barWidth ?? 20;
87
+ if (state.phase === 'idle') return truncate('quiesco: waiting for the test runner…', width - 1);
88
+
89
+ const total = state.total;
90
+ const done = state.done;
91
+ const ratio = total > 0 ? Math.min(1, done / total) : 0;
92
+ const filled = Math.round(ratio * cells);
93
+ const failed = state.counts.failed > 0 || state.fileErrors.size > 0 || state.runErrors.length > 0;
94
+ const bar = `▕${paint(color, failed ? '31' : '32', '█'.repeat(filled))}${paint(color, '2', '░'.repeat(cells - filled))}▏`;
95
+
96
+ const totalText = `${state.totalIsApproximate ? '~' : ''}${total}`;
97
+ const c = state.counts;
98
+ const skipped = c.skipped + c.pending + c.todo + c.undefined + c.notRun;
99
+ const parts = [
100
+ `${bar} ${done}/${totalText}`,
101
+ [paint(color, '32', `✓${c.passed}`), ...(c.failed > 0 ? [paint(color, '31', `✗${c.failed}`)] : []), ...(skipped > 0 ? [paint(color, '33', `↷${skipped}`)] : [])].join(' '),
102
+ formatDuration(options.since !== undefined ? Math.max(0, (state.endedAt ?? (options.now ?? Date.now)()) - options.since) : state.elapsedMs),
103
+ ];
104
+ let line = parts.join(' ');
105
+
106
+ // What is running now, in the space left.
107
+ const room = width - 1 - textWidth(line) - 4;
108
+ if (state.phase === 'running' && state.running.size > 0 && room > 8) {
109
+ const running = [...state.running.values()].sort((a, b) => (a.worker ?? 0) - (b.worker ?? 0));
110
+ const many = running.length > 1;
111
+ const text = running.map((r) => `${many && r.worker !== undefined ? `${r.worker + 1}:` : ''}${r.test.name}`).join(' · ');
112
+ line += ` ${paint(color, '36', '▶')} ${truncate(text, room)}`;
113
+ } else if (state.phase === 'ended') {
114
+ line += ` ${state.interrupted ? paint(color, '33', 'interrupted') : state.success === true ? paint(color, '32', 'passed') : paint(color, '31', 'failed')}`;
115
+ }
116
+ return textWidth(line) <= width - 1 ? line : truncate(stripAnsi(line), width - 1);
117
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Run the test runner with the progress bar (P3): a run-events socket the runner's Quiesco reporter
3
+ * connects to (QUIESCO_EVENTS), the runner's output piped through so the bar stays on the last line.
4
+ */
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+
9
+ import { RunEventServer, RunState } from '@quiesco/core';
10
+
11
+ import type { CliContext, Terminal } from '../context.js';
12
+ import { renderBar } from './render.js';
13
+ import { StickyTerminal } from './sticky.js';
14
+
15
+ export type RunnerName = 'cucumber' | 'jest' | 'vitest';
16
+
17
+ /** Redraw at most this often for events; the clock ticks once a second. */
18
+ const FRAME_MS = 80;
19
+
20
+ /**
21
+ * Whether to show the bar: a terminal, not CI, not turned off (`--no-progress`, QUIESCO_PROGRESS=0).
22
+ */
23
+ export function progressWanted(ctx: CliContext, noProgressFlag: boolean): ctx is CliContext & { terminal: Terminal } {
24
+ if (noProgressFlag || ctx.terminal === null) return false;
25
+ const env = ctx.env;
26
+ if (env['QUIESCO_PROGRESS'] === '0' || env['QUIESCO_PROGRESS'] === 'false') return false;
27
+ const ci = env['CI'];
28
+ return ci === undefined || ci === '' || ci === '0' || ci === 'false';
29
+ }
30
+
31
+ /**
32
+ * The cucumber-js arguments that add Quiesco's events formatter, from the project's own
33
+ * @quiesco/cucumber; [] when it is not installed. The file target keeps the user's stdout formatter
34
+ * (a format without one would replace it).
35
+ */
36
+ export function cucumberFormatArgs(ctx: CliContext): string[] {
37
+ const file = ctx.resolveFrom(ctx.cwd, '@quiesco/cucumber/events');
38
+ if (file === null) return [];
39
+ const url = pathToFileURL(file).href;
40
+ // Windows: a temp file (cucumber creates the target's directory, which fails for the null device).
41
+ const target = ctx.platform === 'win32' ? path.join(os.tmpdir(), `quiesco-events-${process.pid}.out`) : '/dev/null';
42
+ const descriptor = `"${url}":"${target}"`;
43
+ // Through cmd.exe (Windows runs npx with a shell) the quotes must survive the argument parsing.
44
+ return ['--format', ctx.platform === 'win32' ? `"${descriptor.replaceAll('"', '\\"')}"` : descriptor];
45
+ }
46
+
47
+ const HINTS: Record<RunnerName, string> = {
48
+ cucumber: "quiesco: no test progress was received. Install @quiesco/cucumber in this project (quiesco test adds its formatter by itself).",
49
+ vitest: "quiesco: no test progress was received. Add quiescoPlugin() to your Vitest config: `import { quiesco, quiescoPlugin } from '@quiesco/vitest/config'` and `plugins: [quiescoPlugin()]`.",
50
+ jest: "quiesco: no test progress was received. Your Jest config replaces the preset's reporters: add '@quiesco/jest/reporter' to `reporters` (next to 'default').",
51
+ };
52
+
53
+ export interface ProgressRun {
54
+ command: string;
55
+ args: readonly string[];
56
+ env: NodeJS.ProcessEnv;
57
+ runner: RunnerName;
58
+ }
59
+
60
+ export async function runWithProgress(ctx: CliContext & { terminal: Terminal }, run: ProgressRun): Promise<number> {
61
+ const term = ctx.terminal;
62
+ const state = new RunState();
63
+ const since = Date.now();
64
+ const sticky = new StickyTerminal({ write: term.stdout, columns: term.columns });
65
+ const draw = () => sticky.setBar(renderBar(state, { width: term.columns(), color: term.color, since }));
66
+ let frame: NodeJS.Timeout | null = null;
67
+ const schedule = () => {
68
+ frame ??= setTimeout(() => {
69
+ frame = null;
70
+ draw();
71
+ }, FRAME_MS);
72
+ };
73
+ const server = new RunEventServer({
74
+ onEvent: (event) => {
75
+ state.apply(event);
76
+ schedule();
77
+ },
78
+ });
79
+ await server.listen();
80
+ const clock = setInterval(draw, 1000);
81
+ clock.unref();
82
+ const offInterrupt = term.onInterrupt(() => sticky.stop());
83
+ draw();
84
+
85
+ const env: NodeJS.ProcessEnv = { ...run.env, ...server.env() };
86
+ // The runner's output is a pipe now: keep its colors and width as on the terminal.
87
+ if (term.color && env['FORCE_COLOR'] === undefined && env['NO_COLOR'] === undefined) env['FORCE_COLOR'] = '1';
88
+ if (env['COLUMNS'] === undefined) env['COLUMNS'] = String(term.columns());
89
+
90
+ let code: number;
91
+ try {
92
+ code = await ctx.runPiped(run.command, run.args, { cwd: ctx.cwd, env, onStdout: (c) => sticky.output(c, term.stdout), onStderr: (c) => sticky.output(c, term.stderr) });
93
+ await server.drain();
94
+ } finally {
95
+ clearInterval(clock);
96
+ if (frame !== null) clearTimeout(frame);
97
+ offInterrupt();
98
+ await server.close();
99
+ }
100
+ state.runnerExited(code);
101
+ const received = server.hellos.length > 0;
102
+ sticky.stop(received ? renderBar(state, { width: term.columns(), color: term.color, since }) : undefined);
103
+ if (!received) ctx.err(HINTS[run.runner]);
104
+ return code;
105
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Keeps one status line at the bottom of the terminal while a child's output scrolls above it.
3
+ *
4
+ * The bottom region is [the child's current unfinished line, if any] + [the status line]. Before the
5
+ * child's output is written the region is erased (cursor up, clear to the end of the screen); complete
6
+ * lines are written; the region is drawn again. An unfinished line (cucumber's progress dots
7
+ * `....F..`) stays visible above the bar and is completed in place by later output.
8
+ */
9
+ import { textWidth } from './render.js';
10
+
11
+ export interface StickyOutput {
12
+ /** Writes escape sequences and the bottom region (stdout). */
13
+ write(text: string): void;
14
+ /** Current terminal width. */
15
+ columns(): number;
16
+ }
17
+
18
+ export class StickyTerminal {
19
+ private partial = '';
20
+ private bar = '';
21
+ private drawnRows = 0;
22
+ private stopped = false;
23
+
24
+ constructor(private readonly out: StickyOutput) {}
25
+
26
+ /** The child wrote `chunk` (to stdout or stderr: `write` is that stream). */
27
+ output(chunk: string, write: (text: string) => void): void {
28
+ if (this.stopped) {
29
+ write(chunk);
30
+ return;
31
+ }
32
+ this.erase();
33
+ const text = this.partial + chunk;
34
+ const nl = text.lastIndexOf('\n');
35
+ if (nl === -1) {
36
+ this.partial = text;
37
+ } else {
38
+ write(text.slice(0, nl + 1));
39
+ this.partial = text.slice(nl + 1);
40
+ }
41
+ this.draw();
42
+ }
43
+
44
+ /** Show `line` as the status line (no wider than the terminal). */
45
+ setBar(line: string): void {
46
+ if (this.stopped || line === this.bar) return;
47
+ this.erase();
48
+ this.bar = line;
49
+ this.draw();
50
+ }
51
+
52
+ /** Remove the region; write the unfinished line back, then `finalLine` (if any) as plain output. */
53
+ stop(finalLine?: string): void {
54
+ if (this.stopped) return;
55
+ this.erase();
56
+ this.stopped = true;
57
+ let tail = this.partial;
58
+ this.partial = '';
59
+ if (finalLine !== undefined) tail += `${tail === '' ? '' : '\n'}${finalLine}\n`;
60
+ if (tail !== '') this.out.write(tail);
61
+ }
62
+
63
+ private visiblePartial(): string {
64
+ // A carriage return inside the unfinished line rewrites it from the start, as a terminal would.
65
+ const cr = this.partial.lastIndexOf('\r');
66
+ return cr === -1 ? this.partial : this.partial.slice(cr + 1);
67
+ }
68
+
69
+ private rows(text: string): number {
70
+ const cols = Math.max(1, this.out.columns());
71
+ return Math.max(1, Math.ceil(textWidth(text) / cols));
72
+ }
73
+
74
+ private draw(): void {
75
+ const partial = this.visiblePartial();
76
+ if (partial === '' && this.bar === '') return;
77
+ let text = '';
78
+ let rows = 0;
79
+ if (partial !== '') {
80
+ text += `${partial}\n`;
81
+ rows += this.rows(partial);
82
+ }
83
+ text += this.bar;
84
+ rows += 1;
85
+ this.out.write(text);
86
+ this.drawnRows = rows;
87
+ }
88
+
89
+ private erase(): void {
90
+ if (this.drawnRows === 0) return;
91
+ const up = this.drawnRows - 1;
92
+ this.out.write(`\r${up > 0 ? `\u001b[${up}A` : ''}\u001b[0J`);
93
+ this.drawnRows = 0;
94
+ }
95
+ }