quiesco 0.1.1 → 0.2.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.
@@ -121,9 +121,9 @@ function quiescoConfig(app: AppJson, platforms: readonly CliPlatform[]): string
121
121
  lines.push(
122
122
  ' ios: {',
123
123
  ` bundleId: '${app.expo?.ios?.bundleIdentifier ?? 'com.example.app'}',${app.expo?.ios?.bundleIdentifier === undefined ? ' // TODO: expo.ios.bundleIdentifier' : ''}`,
124
- ' // Simulator build made with EXPO_PUBLIC_QUIESCO=1 (expo prebuild + xcodebuild, or an EAS e2e build).',
124
+ ' // Simulator build made with EXPO_PUBLIC_QUIESCO=1: `npx quiesco build ios` writes it here (or an EAS e2e build).',
125
125
  ` binaryPath: 'ios/build/Build/Products/Debug-iphonesimulator/${ios.name}.app',${ios.exact ? '' : ' // TODO: check the .app name'}`,
126
- " // A dev client loading JS from Metro (EXPO_PUBLIC_QUIESCO=1 npx expo start). Remove for a bundled build.",
126
+ " // A dev client loading JS from Metro (quiesco test starts it when it is not running). Remove for a bundled build.",
127
127
  " devClient: { metroUrl: 'http://localhost:8081' },",
128
128
  ' },',
129
129
  );
@@ -132,6 +132,7 @@ function quiescoConfig(app: AppJson, platforms: readonly CliPlatform[]): string
132
132
  lines.push(
133
133
  ' android: {',
134
134
  ` package: '${app.expo?.android?.package ?? 'com.example.app'}',${app.expo?.android?.package === undefined ? ' // TODO: expo.android.package' : ''}`,
135
+ " // `npx quiesco build android` writes it here (EXPO_PUBLIC_QUIESCO=1).",
135
136
  " binaryPath: 'android/app/build/outputs/apk/debug/app-debug.apk',",
136
137
  ` devClient: { scheme: '${scheme ?? 'myapp'}', metroUrl: 'http://localhost:8081' },${scheme === undefined ? ' // TODO: expo.scheme' : ''}`,
137
138
  ' },',
@@ -162,8 +163,9 @@ function quiescoConfig(app: AppJson, platforms: readonly CliPlatform[]): string
162
163
  return lines.join('\n');
163
164
  }
164
165
 
166
+ // No `paths`: cucumber-js already defaults to features/**/*.feature, and paths set here are merged with the
167
+ // ones given on the command line, so `quiesco test features/x.feature` would run every feature (issue #8).
165
168
  const CUCUMBER_CONFIG = `export default {
166
- paths: ['features/**/*.feature'],
167
169
  import: ['features/support/**/*.ts', 'features/step_definitions/**/*.ts'],
168
170
  format: ['progress'],
169
171
  };
@@ -342,7 +344,7 @@ export async function initCommand(args: readonly string[], ctx: CliContext): Pro
342
344
  steps.push({ status: 'created', what: rel, note });
343
345
  };
344
346
  write('quiesco.config.mts', quiescoConfig(app, platforms), `apps: ${platforms.join(', ')}`, ['quiesco.config.ts', 'quiesco.config.mts', 'quiesco.config.js', 'quiesco.config.mjs']);
345
- write('cucumber.mjs', CUCUMBER_CONFIG, 'features/**/*.feature', ['cucumber.mjs', 'cucumber.js', 'cucumber.cjs', 'cucumber.json', 'cucumber.yaml', 'cucumber.yml']);
347
+ write('cucumber.mjs', CUCUMBER_CONFIG, 'step files and format (features/**/*.feature by default)', ['cucumber.mjs', 'cucumber.js', 'cucumber.cjs', 'cucumber.json', 'cucumber.yaml', 'cucumber.yml']);
346
348
  write('features/package.json', '{ "type": "module" }\n', 'step files are ES modules');
347
349
  write('features/support/quiesco.ts', SUPPORT, 'this.app and the lifecycle hooks');
348
350
  write('features/app.feature', FEATURE, 'a first scenario');
@@ -353,8 +355,8 @@ export async function initCommand(args: readonly string[], ctx: CliContext): Pro
353
355
  const wanted: Record<string, string> = {
354
356
  'e2e:start': 'EXPO_PUBLIC_QUIESCO=1 expo start',
355
357
  ...(platforms.includes('web') ? { 'e2e:web': 'EXPO_PUBLIC_QUIESCO=1 expo export --platform web && quiesco test --platform web' } : {}),
356
- ...(platforms.includes('android') ? { 'e2e:android': 'quiesco test --platform android' } : {}),
357
- ...(platforms.includes('ios') ? { 'e2e:ios': 'quiesco test --platform ios' } : {}),
358
+ ...(platforms.includes('android') ? { 'e2e:build:android': 'quiesco build android', 'e2e:android': 'quiesco test --platform android' } : {}),
359
+ ...(platforms.includes('ios') ? { 'e2e:build:ios': 'quiesco build ios', 'e2e:ios': 'quiesco test --platform ios' } : {}),
358
360
  };
359
361
  const added = Object.keys(wanted).filter((k) => scripts[k] === undefined);
360
362
  if (added.length > 0) {
@@ -373,7 +375,7 @@ export async function initCommand(args: readonly string[], ctx: CliContext): Pro
373
375
  ctx.out(" 1. Wrap the root layout in <QuiescoRoot> (import { QuiescoRoot } from '@quiesco/agent').");
374
376
  ctx.out(' 2. Give the home screen testID="home" (features/step_definitions/app.steps.ts looks for it).');
375
377
  if (platforms.includes('web')) ctx.out(' 3. npx playwright install chromium, then npm run e2e:web');
376
- if (platforms.some((p) => p !== 'web')) ctx.out(' • iOS / Android: build the app with EXPO_PUBLIC_QUIESCO=1, check binaryPath in quiesco.config.mts, run `npx quiesco doctor`.');
378
+ if (platforms.some((p) => p !== 'web')) ctx.out(' • iOS / Android: npm run e2e:build:ios (or :android) builds the app into binaryPath, then npm run e2e:ios; quiesco test starts Metro when it is not running. `npx quiesco doctor` checks the setup.');
377
379
  ctx.out(' • A SYNC_TIMEOUT that names a decorative animation (the default template spins a glow): give it a testID and add it to sync.ignoreElements.');
378
380
  return 0;
379
381
  }
@@ -3,9 +3,30 @@
3
3
  * (requirements.md §6.12, Phase 6.10): sets QUIESCO_PLATFORM and runs the project's test runner with the
4
4
  * remaining arguments unchanged. Default runner: cucumber-js. `--workers N` (Phase 6.12) runs N workers,
5
5
  * each on its own device, with the runner's own flags; those flags can also be passed directly.
6
+ * Everything after a `--` goes to the runner as-is, and the `--` itself is dropped (issue #7): cucumber-js
7
+ * would read every argument after it as a path.
6
8
  */
9
+ import type { QuiescoConfig } from '@quiesco/core';
10
+ import { loadConfig } from '@quiesco/core';
11
+
7
12
  import type { CliContext } from '../context.js';
8
13
  import { parsePlatform, takeOption } from '../context.js';
14
+ import { ensureDevServer } from '../dev-server.js';
15
+
16
+ export interface TestDeps {
17
+ /** The project's quiesco.config (null when there is none: the runner reports that itself). */
18
+ loadConfig: (cwd: string, env: NodeJS.ProcessEnv) => Promise<QuiescoConfig | null>;
19
+ }
20
+
21
+ const defaultTestDeps: TestDeps = {
22
+ loadConfig: async (cwd, env) => {
23
+ try {
24
+ return (await loadConfig({ cwd, ...(env['QUIESCO_CONFIG'] !== undefined ? { file: env['QUIESCO_CONFIG'] } : {}), worker: { workerIndex: 0, workerCount: 1 } })).config;
25
+ } catch {
26
+ return null;
27
+ }
28
+ },
29
+ };
9
30
 
10
31
  const RUNNERS = {
11
32
  cucumber: { command: ['cucumber-js'], workers: (n: number) => (n > 1 ? ['--parallel', String(n)] : []) },
@@ -15,18 +36,47 @@ const RUNNERS = {
15
36
  } as const;
16
37
  type Runner = keyof typeof RUNNERS;
17
38
 
39
+ export const TEST_HELP = `Usage: quiesco test [options] [runner arguments…]
40
+
41
+ Sets QUIESCO_PLATFORM and runs the project's test runner. Arguments Quiesco does not know go to the runner
42
+ unchanged; everything after \`--\` goes to the runner as well (the \`--\` itself is dropped).
43
+
44
+ When nothing answers at devClient.metroUrl (native) or apps.web.url (web) on this machine, it starts
45
+ \`npx expo start\` first and stops it afterwards (config: devServer; log: artifacts/metro.log).
46
+
47
+ Options:
48
+ --platform ios|android|web Platform to test (or set QUIESCO_PLATFORM)
49
+ --runner cucumber|jest|vitest Test runner (default: cucumber, i.e. cucumber-js)
50
+ --workers N Run N workers, each on a device of its own
51
+ -h, --help Show this help (\`quiesco test -- --help\` shows the runner's)
52
+
53
+ Examples:
54
+ quiesco test --platform ios --tags @smoke
55
+ quiesco test --platform web features/login.feature
56
+ quiesco test --platform android --name "Add a todo"
57
+ quiesco test --platform web -- --tags @debug
58
+ quiesco test --platform ios --runner vitest --config vitest.e2e.config.mts`;
59
+
18
60
  function isRunner(v: string | undefined): v is Runner {
19
61
  return v !== undefined && Object.hasOwn(RUNNERS, v);
20
62
  }
21
63
 
22
- export async function testCommand(args: readonly string[], ctx: CliContext): Promise<number> {
23
- const p = takeOption(args, '--platform');
64
+ export async function testCommand(args: readonly string[], ctx: CliContext, deps: TestDeps = defaultTestDeps): Promise<number> {
65
+ // Quiesco reads its own options only before a `--`; what follows goes to the runner untouched.
66
+ const dashDash = args.indexOf('--');
67
+ const own = dashDash === -1 ? args : args.slice(0, dashDash);
68
+ const passThrough = dashDash === -1 ? [] : args.slice(dashDash + 1);
69
+ if (own.includes('-h') || own.includes('--help')) {
70
+ ctx.out(TEST_HELP);
71
+ return 0;
72
+ }
73
+ const p = takeOption(own, '--platform');
24
74
  const r = takeOption(p.rest, '--runner');
25
75
  const w = takeOption(r.rest, '--workers');
26
- const rest = w.rest;
76
+ const rest = [...w.rest, ...passThrough];
27
77
  const platform = parsePlatform(p.value) ?? parsePlatform(ctx.env['QUIESCO_PLATFORM']);
28
78
  if (platform === undefined) {
29
- ctx.err('quiesco test: choose a platform with --platform ios|android|web (or set QUIESCO_PLATFORM).');
79
+ ctx.err('quiesco test: choose a platform with --platform ios|android|web (or set QUIESCO_PLATFORM). See quiesco test --help.');
30
80
  return 2;
31
81
  }
32
82
  const runner = r.value ?? 'cucumber';
@@ -44,6 +94,19 @@ export async function testCommand(args: readonly string[], ctx: CliContext): Pro
44
94
  }
45
95
  workerArgs = [...spec.workers(n)];
46
96
  }
47
- // npx runs the project's own runner (node_modules/.bin), the one the tests import.
48
- return ctx.run('npx', [...spec.command, ...workerArgs, ...rest], { cwd: ctx.cwd, env: { ...ctx.env, QUIESCO_PLATFORM: platform } });
97
+ // The Metro dev server the app loads its JS from, started when nothing answers there (issue #5).
98
+ const config = await deps.loadConfig(ctx.cwd, ctx.env);
99
+ let devServer;
100
+ try {
101
+ devServer = config === null ? null : await ensureDevServer(ctx, config, platform);
102
+ } catch (e) {
103
+ ctx.err(`quiesco test: ${(e as Error).message}`);
104
+ return 1;
105
+ }
106
+ try {
107
+ // npx runs the project's own runner (node_modules/.bin), the one the tests import.
108
+ return await ctx.run('npx', [...spec.command, ...workerArgs, ...rest], { cwd: ctx.cwd, env: { ...ctx.env, QUIESCO_PLATFORM: platform } });
109
+ } finally {
110
+ await devServer?.stop();
111
+ }
49
112
  }
package/src/context.ts CHANGED
@@ -26,6 +26,23 @@ export interface CliContext {
26
26
  exists(path: string): boolean;
27
27
  platform: NodeJS.Platform;
28
28
  nodeVersion: string;
29
+ /** Whether a person is at the terminal (stdout is a TTY), not a CI job. */
30
+ interactive: boolean;
31
+ /** Start a long-running process (Metro) in its own process group, its output appended to `logFile`. */
32
+ spawnBackground(command: string, args: readonly string[], options: { cwd: string; env: NodeJS.ProcessEnv; logFile: string }): BackgroundProcess;
33
+ /** GET `url`; null when nothing answers (connection refused, timeout). */
34
+ httpGet(url: string, timeoutMs: number): Promise<{ status: number; body: string } | null>;
35
+ /** Run `cleanup` on Ctrl-C / SIGTERM before exiting; returns a function that removes it. */
36
+ onInterrupt(cleanup: () => Promise<void>): () => void;
37
+ /** Wait (polling a dev server). */
38
+ sleep(ms: number): Promise<void>;
39
+ }
40
+
41
+ export interface BackgroundProcess {
42
+ /** Resolves with the exit code when the process ends. */
43
+ readonly exited: Promise<number>;
44
+ /** Stop it and everything it started (SIGTERM to the group, SIGKILL after `graceMs`). */
45
+ stop(graceMs?: number): Promise<void>;
29
46
  }
30
47
 
31
48
  const isWindows = process.platform === 'win32';
@@ -66,6 +83,56 @@ export function defaultContext(): CliContext {
66
83
  exists: (p) => fs.existsSync(p),
67
84
  platform: process.platform,
68
85
  nodeVersion: process.versions.node,
86
+ interactive: process.stdout.isTTY === true,
87
+ spawnBackground: (command, args, options) => {
88
+ fs.mkdirSync(path.dirname(options.logFile), { recursive: true });
89
+ const log = fs.openSync(options.logFile, 'a');
90
+ // Its own process group (detached): `expo start` starts children; stopping the group stops them all.
91
+ const child = nodeSpawn(command, [...args], { cwd: options.cwd, env: options.env, stdio: ['ignore', log, log], detached: !isWindows, shell: isWindows });
92
+ fs.closeSync(log);
93
+ const exited = new Promise<number>((resolve) => {
94
+ child.on('error', () => resolve(127));
95
+ child.on('exit', (code, signal) => resolve(code ?? (signal !== null ? 128 : 1)));
96
+ });
97
+ const signal = (s: NodeJS.Signals) => {
98
+ try {
99
+ if (!isWindows && child.pid !== undefined) process.kill(-child.pid, s);
100
+ else child.kill(s);
101
+ } catch {
102
+ // already gone
103
+ }
104
+ };
105
+ return {
106
+ exited,
107
+ stop: async (graceMs = 5000) => {
108
+ if (child.exitCode !== null || child.signalCode !== null) return;
109
+ signal('SIGTERM');
110
+ const timer = setTimeout(() => signal('SIGKILL'), graceMs);
111
+ await exited;
112
+ clearTimeout(timer);
113
+ },
114
+ };
115
+ },
116
+ httpGet: async (url, timeoutMs) => {
117
+ try {
118
+ const r = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
119
+ return { status: r.status, body: await r.text() };
120
+ } catch {
121
+ return null;
122
+ }
123
+ },
124
+ onInterrupt: (cleanup) => {
125
+ const handler = (s: NodeJS.Signals) => {
126
+ void cleanup().finally(() => process.exit(s === 'SIGINT' ? 130 : 143));
127
+ };
128
+ process.once('SIGINT', handler);
129
+ process.once('SIGTERM', handler);
130
+ return () => {
131
+ process.off('SIGINT', handler);
132
+ process.off('SIGTERM', handler);
133
+ };
134
+ },
135
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
69
136
  };
70
137
  }
71
138
 
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The Metro dev server for `quiesco test` (issue #5), like Playwright's `webServer`: when the app loads its JS
3
+ * from Metro (`devClient.metroUrl` on iOS / Android, `apps.web.url` on the web) and nothing answers there,
4
+ * start `expo start` with EXPO_PUBLIC_QUIESCO=1, wait until it is ready, and stop it when the run ends. A
5
+ * Metro that is already running is used as it is. Here, in the CLI, because it is the one process of the run:
6
+ * parallel workers (cucumber-js child processes, Jest workers) would each start and stop their own.
7
+ */
8
+ import path from 'node:path';
9
+
10
+ import type { QuiescoConfig } from '@quiesco/core';
11
+
12
+ import type { BackgroundProcess, CliContext, CliPlatform } from './context.js';
13
+
14
+ export const DEFAULT_DEV_SERVER_TIMEOUT_MS = 120_000;
15
+ const POLL_MS = 500;
16
+ const DEFAULT_METRO_URL = 'http://localhost:8081';
17
+
18
+ /** Where the app loads its JS from on `platform`, or null when it does not use a dev server. */
19
+ export function devServerUrl(config: QuiescoConfig, platform: CliPlatform): string | null {
20
+ if (platform === 'web') return config.apps.web?.url ?? null;
21
+ const dc = config.apps[platform]?.devClient;
22
+ return dc === undefined ? null : (dc.metroUrl ?? DEFAULT_METRO_URL);
23
+ }
24
+
25
+ /** Whether Metro answers at `url` (its `/status` says `packager-status:running`). */
26
+ export async function metroRunning(ctx: CliContext, url: string): Promise<boolean> {
27
+ const r = await ctx.httpGet(new URL('/status', url).toString(), 2000);
28
+ return r !== null && r.body.includes('packager-status:running');
29
+ }
30
+
31
+ export interface DevServer {
32
+ /** Stops Metro when this run started it; nothing otherwise. */
33
+ stop(): Promise<void>;
34
+ }
35
+
36
+ const NOTHING: DevServer = { stop: async () => {} };
37
+
38
+ /**
39
+ * Make sure the dev server the app needs is running. Returns how to stop what was started. Throws when it
40
+ * was started but did not become ready (with the end of its log).
41
+ */
42
+ export async function ensureDevServer(ctx: CliContext, config: QuiescoConfig, platform: CliPlatform): Promise<DevServer> {
43
+ const url = devServerUrl(config, platform);
44
+ if (url === null) return NOTHING;
45
+ if (await metroRunning(ctx, url)) {
46
+ ctx.out(`quiesco: using the Metro dev server at ${url}`);
47
+ return NOTHING;
48
+ }
49
+ const opts = config.devServer ?? {};
50
+ const where = new URL(url);
51
+ if (opts.autoStart === false || !['localhost', '127.0.0.1', '[::1]'].includes(where.hostname)) {
52
+ ctx.out(`quiesco: nothing answers at ${url}; start Metro there (EXPO_PUBLIC_QUIESCO=1 npx expo start) — ${opts.autoStart === false ? 'devServer.autoStart is false' : 'it is not on this machine'}`);
53
+ return NOTHING;
54
+ }
55
+ const port = where.port !== '' ? where.port : where.protocol === 'https:' ? '443' : '80';
56
+ const [command, ...args] = (opts.command ?? ['npx', 'expo', 'start', '--port', '{port}']).map((a) => a.replaceAll('{port}', port));
57
+ if (command === undefined) throw new Error('devServer.command is empty');
58
+ const logFile = path.join(ctx.cwd, config.artifacts?.dir ?? 'artifacts', 'metro.log');
59
+ ctx.out(`quiesco: starting Metro (${[command, ...args].join(' ')}) with EXPO_PUBLIC_QUIESCO=1; log: ${path.relative(ctx.cwd, logFile)}`);
60
+ const proc = ctx.spawnBackground(command, args, { cwd: ctx.cwd, env: { ...ctx.env, EXPO_PUBLIC_QUIESCO: '1' }, logFile });
61
+ const offInterrupt = ctx.onInterrupt(() => proc.stop());
62
+ const server: DevServer = {
63
+ stop: async () => {
64
+ offInterrupt();
65
+ await proc.stop();
66
+ },
67
+ };
68
+ await waitReady(ctx, url, proc, opts.timeoutMs ?? DEFAULT_DEV_SERVER_TIMEOUT_MS, logFile).catch(async (e: unknown) => {
69
+ await server.stop();
70
+ throw e;
71
+ });
72
+ ctx.out(`quiesco: Metro is ready at ${url}`);
73
+ return server;
74
+ }
75
+
76
+ async function waitReady(ctx: CliContext, url: string, proc: BackgroundProcess, timeoutMs: number, logFile: string): Promise<void> {
77
+ let exitCode: number | null = null;
78
+ void proc.exited.then((c) => (exitCode = c));
79
+ for (let waited = 0; ; waited += POLL_MS) {
80
+ if (await metroRunning(ctx, url)) return;
81
+ if (exitCode !== null) throw new Error(`Metro exited (code ${exitCode}) before it was ready.${tail(ctx, logFile)}`);
82
+ if (waited >= timeoutMs) throw new Error(`Metro was not ready at ${url} within ${timeoutMs}ms (devServer.timeoutMs).${tail(ctx, logFile)}`);
83
+ await ctx.sleep(POLL_MS);
84
+ }
85
+ }
86
+
87
+ function tail(ctx: CliContext, logFile: string): string {
88
+ const text = ctx.readFile(logFile);
89
+ if (text === null || text.trim() === '') return '';
90
+ return `\nLast lines of ${logFile}:\n${text.trimEnd().split('\n').slice(-15).join('\n')}`;
91
+ }