quiesco 0.3.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.
@@ -11,6 +11,8 @@ import path from 'node:path';
11
11
 
12
12
  import type { CliContext, CliPlatform } from '../context.js';
13
13
  import { PLATFORMS, takeFlag, takeOption } from '../context.js';
14
+ import { installedVersion, isQuiescoPackage } from '../packages.js';
15
+ import { entryFile, registeredRoot, rootSourceFiles, wrapRegisteredRoot } from '../project.js';
14
16
 
15
17
  type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';
16
18
 
@@ -22,7 +24,6 @@ interface PackageJson {
22
24
  devDependencies?: Record<string, string>;
23
25
  overrides?: Record<string, string>;
24
26
  resolutions?: Record<string, string>;
25
- pnpm?: { overrides?: Record<string, string> };
26
27
  [key: string]: unknown;
27
28
  }
28
29
 
@@ -64,6 +65,11 @@ export function findTarballs(dir: string, names: readonly string[], list: (d: st
64
65
  return found;
65
66
  }
66
67
 
68
+ /** An `overrides:` block for pnpm-workspace.yaml (names and paths quoted: `@` starts no plain YAML scalar). */
69
+ function pnpmOverrides(pins: Record<string, string>): string {
70
+ return `overrides:\n${Object.entries(pins).map(([n, f]) => ` ${JSON.stringify(n)}: ${JSON.stringify(f)}\n`).join('')}`;
71
+ }
72
+
67
73
  function addCommand(pm: PackageManager, dev: boolean, specs: string[]): { command: string; args: string[] } {
68
74
  switch (pm) {
69
75
  case 'pnpm':
@@ -173,6 +179,10 @@ const CUCUMBER_CONFIG = `export default {
173
179
 
174
180
  const SUPPORT = `// this.app (the Quiesco driver) in every step, and the lifecycle hooks: one app session per run,
175
181
  // a soft reset before each scenario, screenshot + element tree on failure.
182
+ //
183
+ // Step and support files run with Node's type stripping, not tsc: relative imports name the .ts file
184
+ // (import { TodoDriver } from './todo-driver.ts'), and TypeScript syntax that generates code is not
185
+ // supported (parameter properties such as constructor(private app: Driver), enum, namespace).
176
186
  import '@quiesco/cucumber/register';
177
187
  `;
178
188
 
@@ -231,10 +241,14 @@ export async function initCommand(args: readonly string[], ctx: CliContext): Pro
231
241
  // 1. Dependencies.
232
242
  const runtime = [...RUNTIME];
233
243
  const dev = [...DEV, ...(platforms.includes('web') ? WEB_DEV : [])];
234
- let spec = (name: string): string => name;
244
+ // Issue #17: the version of this CLI, not whatever the registry metadata in the package manager's cache
245
+ // calls latest (a project on an older Quiesco than the scripts init writes for it).
246
+ let spec = (name: string): string => (isQuiescoPackage(name) ? `${name}@${ctx.version}` : name);
247
+ /** The version each Quiesco package must have after the install. */
248
+ let expected = (_name: string): string => ctx.version;
235
249
  if (packagesOpt.value !== undefined) {
236
250
  const dir = path.resolve(ctx.cwd, packagesOpt.value);
237
- const ours = [...runtime, ...dev, ...TRANSITIVE].filter((n) => n === 'quiesco' || n.startsWith('@quiesco/'));
251
+ const ours = [...runtime, ...dev, ...TRANSITIVE].filter(isQuiescoPackage);
238
252
  const tarballs = findTarballs(dir, ours);
239
253
  const missing = ours.filter((n) => !tarballs.has(n));
240
254
  if (missing.length > 0) {
@@ -242,18 +256,31 @@ export async function initCommand(args: readonly string[], ctx: CliContext): Pro
242
256
  return 1;
243
257
  }
244
258
  spec = (name) => (tarballs.has(name) ? `file:${tarballs.get(name) as string}` : name);
259
+ expected = (name) => /-(\d[^/]*)\.tgz$/.exec(tarballs.get(name) ?? '')?.[1] ?? ctx.version;
245
260
  // Their own dependencies on each other ("@quiesco/protocol": "0.0.0") must resolve to the tarballs too.
246
261
  // npm refuses an override for a package that is also a direct dependency (EOVERRIDE) and reuses the
247
262
  // directly installed tarballs for those ranges anyway: pin only the indirect ones there. pnpm and
248
263
  // yarn resolve every dependency on its own, so they need all of them pinned.
249
264
  const direct = new Set([...runtime, ...dev]);
250
265
  const pins = Object.fromEntries([...tarballs].filter(([n]) => pm !== 'npm' || !direct.has(n)).map(([n, f]) => [n, `file:${f}`]));
251
- const current = readJson<PackageJson>(ctx, pkgFile) as PackageJson;
252
- if (pm === 'pnpm') current.pnpm = { ...current.pnpm, overrides: { ...current.pnpm?.overrides, ...pins } };
253
- else if (pm === 'yarn') current.resolutions = { ...current.resolutions, ...pins };
254
- else current.overrides = { ...current.overrides, ...pins };
255
- writeJson(ctx, pkgFile, current);
256
- steps.push({ status: 'updated', what: 'package.json', note: `installing from the tarballs in ${packagesOpt.value} (${Object.keys(pins).length} indirect ${Object.keys(pins).length === 1 ? 'dependency' : 'dependencies'} pinned)` });
266
+ const pinned = `installing from the tarballs in ${packagesOpt.value} (${Object.keys(pins).length} indirect ${Object.keys(pins).length === 1 ? 'dependency' : 'dependencies'} pinned)`;
267
+ if (pm === 'pnpm') {
268
+ // pnpm 10+ reads overrides from pnpm-workspace.yaml only; the "pnpm" field of package.json is ignored.
269
+ const yamlFile = path.join(ctx.cwd, 'pnpm-workspace.yaml');
270
+ const yaml = ctx.readFile(yamlFile) ?? '';
271
+ if (/^overrides:/m.test(yaml)) {
272
+ ctx.err(`quiesco init: pnpm-workspace.yaml already has overrides; add these and run quiesco init again:\n${pnpmOverrides(pins)}`);
273
+ return 1;
274
+ }
275
+ ctx.writeFile(yamlFile, `${yaml}${yaml === '' || yaml.endsWith('\n') ? '' : '\n'}${pnpmOverrides(pins)}`);
276
+ steps.push({ status: 'updated', what: 'pnpm-workspace.yaml', note: pinned });
277
+ } else {
278
+ const current = readJson<PackageJson>(ctx, pkgFile) as PackageJson;
279
+ if (pm === 'yarn') current.resolutions = { ...current.resolutions, ...pins };
280
+ else current.overrides = { ...current.overrides, ...pins };
281
+ writeJson(ctx, pkgFile, current);
282
+ steps.push({ status: 'updated', what: 'package.json', note: pinned });
283
+ }
257
284
  }
258
285
  const installs = [addCommand(pm, false, runtime.map(spec)), addCommand(pm, true, dev.map(spec))];
259
286
  for (const cmd of installs) {
@@ -271,6 +298,21 @@ export async function initCommand(args: readonly string[], ctx: CliContext): Pro
271
298
  }
272
299
  steps.push({ status: 'ran', what: 'install', note: line });
273
300
  }
301
+ if (!skipInstall.present) {
302
+ const ours = [...runtime, ...dev].filter(isQuiescoPackage);
303
+ const wrong = ours.map((name) => ({ name, want: expected(name), got: installedVersion(ctx, name) })).filter((p) => p.got !== p.want);
304
+ if (wrong.length > 0) {
305
+ ctx.err(`quiesco init: the installed Quiesco packages are not the version that was asked for:`);
306
+ for (const p of wrong) ctx.err(` ${p.name}: ${p.got ?? 'not found in node_modules'} (wanted ${p.want})`);
307
+ ctx.err('All Quiesco packages must have the same version as the CLI that writes the project files. The');
308
+ ctx.err("package manager may have used stale registry metadata from its cache, or held a new release back");
309
+ ctx.err('(pnpm minimumReleaseAge). Install them again with the version given:');
310
+ for (const cmd of [addCommand(pm, false, runtime.map(spec)), addCommand(pm, true, dev.filter(isQuiescoPackage).map(spec))]) ctx.err(` ${cmd.command} ${cmd.args.join(' ')}`);
311
+ ctx.err('then run quiesco init again.');
312
+ return 1;
313
+ }
314
+ steps.push({ status: 'ran', what: 'versions', note: `${ours.length} Quiesco packages at ${[...new Set(ours.map(expected))].join(', ')}` });
315
+ }
274
316
 
275
317
  // 2. Config plugin in app.json.
276
318
  const appFile = path.join(ctx.cwd, 'app.json');
@@ -321,15 +363,29 @@ export async function initCommand(args: readonly string[], ctx: CliContext): Pro
321
363
  steps.push({ status: 'created', what: 'index.ts', note: `imports @quiesco/agent, then ${original}; package.json "main" set to index.ts` });
322
364
  }
323
365
  } else {
324
- const entry = [main, `${main}.ts`, `${main}.tsx`, `${main}.js`].map((f) => path.join(ctx.cwd, f)).find((f) => ctx.exists(f));
325
- const src = entry !== undefined ? (ctx.readFile(entry) ?? '') : null;
326
- if (src === null || entry === undefined) {
366
+ const entry = entryFile(ctx, main);
367
+ const src = entry !== null ? (ctx.readFile(entry) ?? '') : null;
368
+ if (src === null || entry === null) {
327
369
  steps.push({ status: 'todo', what: 'entry file', note: `cannot find "${main}"; import '@quiesco/agent' on its first line` });
328
- } else if (src.includes('@quiesco/agent')) {
329
- steps.push({ status: 'skipped', what: path.basename(entry), note: 'already imports @quiesco/agent' });
330
370
  } else {
331
- ctx.writeFile(entry, `import '@quiesco/agent'; // first: Quiesco hooks into React before the app loads\n${src}`);
332
- steps.push({ status: 'updated', what: path.basename(entry), note: "added import '@quiesco/agent' as the first line" });
371
+ let next = src;
372
+ const notes: string[] = [];
373
+ if (!src.includes('@quiesco/agent')) {
374
+ next = `import '@quiesco/agent'; // first: Quiesco hooks into React before the app loads\n${src}`;
375
+ notes.push("added import '@quiesco/agent' as the first line");
376
+ }
377
+ // Issue #20: registerRootComponent(App) with a local App (the blank templates): wrap it here.
378
+ const wrapped = wrapRegisteredRoot(ctx, entry, next);
379
+ if (wrapped !== null) {
380
+ next = wrapped;
381
+ notes.push(`wrapped ${registeredRoot(ctx, entry, src)?.name ?? 'the root component'} in <QuiescoRoot>`);
382
+ }
383
+ if (next === src) {
384
+ steps.push({ status: 'skipped', what: path.basename(entry), note: 'already imports @quiesco/agent' });
385
+ } else {
386
+ ctx.writeFile(entry, next);
387
+ steps.push({ status: 'updated', what: path.basename(entry), note: notes.join('; ') });
388
+ }
333
389
  }
334
390
  }
335
391
 
@@ -350,6 +406,27 @@ export async function initCommand(args: readonly string[], ctx: CliContext): Pro
350
406
  write('features/app.feature', FEATURE, 'a first scenario');
351
407
  write('features/step_definitions/app.steps.ts', STEPS, 'its step');
352
408
 
409
+ // 5b. tsconfig.json (issue #21): step files import each other with .ts (Node's type stripping needs it).
410
+ const tsconfigFile = path.join(ctx.cwd, 'tsconfig.json');
411
+ const tsconfigText = ctx.readFile(tsconfigFile);
412
+ if (tsconfigText !== null) {
413
+ let tsconfig: { compilerOptions?: Record<string, unknown> } | null;
414
+ try {
415
+ tsconfig = JSON.parse(tsconfigText) as { compilerOptions?: Record<string, unknown> };
416
+ } catch {
417
+ tsconfig = null; // comments or trailing commas: leave the file to the user
418
+ }
419
+ if (tsconfig?.compilerOptions?.['allowImportingTsExtensions'] === true) {
420
+ steps.push({ status: 'skipped', what: 'tsconfig.json', note: 'already allows .ts imports' });
421
+ } else if (tsconfig === null || typeof tsconfig !== 'object' || Array.isArray(tsconfig)) {
422
+ steps.push({ status: 'todo', what: 'tsconfig.json', note: 'add "allowImportingTsExtensions": true to compilerOptions (step files import each other with .ts)' });
423
+ } else {
424
+ tsconfig.compilerOptions = { ...tsconfig.compilerOptions, allowImportingTsExtensions: true };
425
+ writeJson(ctx, tsconfigFile, tsconfig);
426
+ steps.push({ status: 'updated', what: 'tsconfig.json', note: 'allowImportingTsExtensions: step files import each other with .ts' });
427
+ }
428
+ }
429
+
353
430
  // 6. Scripts.
354
431
  const scripts = { ...(latest.scripts ?? {}) };
355
432
  const wanted: Record<string, string> = {
@@ -372,9 +449,14 @@ export async function initCommand(args: readonly string[], ctx: CliContext): Pro
372
449
  for (const s of steps) ctx.out(`${icon[s.status]} ${s.what}${s.note !== undefined ? ` — ${s.note}` : ''}`);
373
450
  ctx.out('');
374
451
  ctx.out('Next:');
375
- ctx.out(" 1. Wrap the root layout in <QuiescoRoot> (import { QuiescoRoot } from '@quiesco/agent').");
376
- ctx.out(' 2. Give the home screen testID="home" (features/step_definitions/app.steps.ts looks for it).');
377
- if (platforms.includes('web')) ctx.out(' 3. npx playwright install chromium, then npm run e2e:web');
452
+ const next: string[] = [];
453
+ const finalMain = (readJson<PackageJson>(ctx, pkgFile) as PackageJson).main;
454
+ if (!rootSourceFiles(ctx, finalMain).some((f) => (ctx.readFile(f) ?? '').includes('QuiescoRoot'))) {
455
+ next.push("Wrap the root layout in <QuiescoRoot> (import { QuiescoRoot } from '@quiesco/agent'): the app connects to Quiesco from it, and the soft reset remounts it.");
456
+ }
457
+ next.push('Give the home screen testID="home" (features/step_definitions/app.steps.ts looks for it).');
458
+ if (platforms.includes('web')) next.push('npx playwright install chromium, then npm run e2e:web');
459
+ next.forEach((line, i) => ctx.out(` ${i + 1}. ${line}`));
378
460
  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.');
379
461
  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.');
380
462
  return 0;
@@ -110,7 +110,7 @@ export async function testCommand(args: readonly string[], ctx: CliContext, deps
110
110
  }
111
111
  try {
112
112
  // npx runs the project's own runner (node_modules/.bin), the one the tests import.
113
- const env = { ...ctx.env, QUIESCO_PLATFORM: platform };
113
+ const env = { ...ctx.env, QUIESCO_PLATFORM: platform, ...devServer?.env };
114
114
  if (progressWanted(ctx, np.present)) {
115
115
  const formatArgs = runner === 'cucumber' ? cucumberFormatArgs(ctx) : [];
116
116
  return await runWithProgress(ctx, { command: 'npx', args: [...spec.command, ...workerArgs, ...formatArgs, ...rest], env, runner });
@@ -138,7 +138,7 @@ export async function uiCommand(args: readonly string[], ctx: CliContext, deps:
138
138
  ...(port !== undefined ? { port } : {}),
139
139
  listTests: () => deps.listTests({ runner, cwd: ctx.cwd, args: rest, env: ctx.env }),
140
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, ...env }, onOutput }),
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
142
  });
143
143
  ctx.out(`quiesco ui: ${server.url}`);
144
144
  ctx.out('quiesco ui: Ctrl-C stops it.');
package/src/context.ts CHANGED
@@ -15,6 +15,8 @@ export interface ExecResult {
15
15
 
16
16
  export interface CliContext {
17
17
  cwd: string;
18
+ /** The version of this CLI (`quiesco init` installs the same version of every Quiesco package). */
19
+ version: string;
18
20
  env: NodeJS.ProcessEnv;
19
21
  out(line: string): void;
20
22
  err(line: string): void;
@@ -67,6 +69,7 @@ const isWindows = process.platform === 'win32';
67
69
  export function defaultContext(): CliContext {
68
70
  return {
69
71
  cwd: process.cwd(),
72
+ version: (createRequire(import.meta.url)('../package.json') as { version: string }).version,
70
73
  env: process.env,
71
74
  out: (line) => process.stdout.write(`${line}\n`),
72
75
  err: (line) => process.stderr.write(`${line}\n`),
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
+ }
package/src/project.ts ADDED
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Where an Expo project renders its root (issue #20): the entry file, the component it registers, and
3
+ * the files `<QuiescoRoot>` may be in.
4
+ */
5
+ import path from 'node:path';
6
+
7
+ import type { CliContext } from './context.js';
8
+
9
+ const SOURCE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js'];
10
+
11
+ /** Root layouts of Expo Router apps and the usual root component files. */
12
+ const ROOT_CANDIDATES = ['app/_layout', 'src/app/_layout', 'App', 'src/App'].flatMap((base) => SOURCE_EXTENSIONS.map((ext) => `${base}${ext}`));
13
+
14
+ /** `file` as given or with a source extension (or as a directory with an index file); null when none exists. */
15
+ export function resolveSource(ctx: CliContext, file: string): string | null {
16
+ const candidates = [file, ...SOURCE_EXTENSIONS.map((ext) => `${file}${ext}`), ...SOURCE_EXTENSIONS.map((ext) => path.join(file, `index${ext}`))];
17
+ return candidates.find((f) => /\.[cm]?[jt]sx?$/.test(f) && ctx.exists(f)) ?? null;
18
+ }
19
+
20
+ /** The project's entry file from package.json "main"; null for package entries (expo-router/entry) or when missing. */
21
+ export function entryFile(ctx: CliContext, main: string | undefined): string | null {
22
+ return main === undefined ? null : resolveSource(ctx, path.join(ctx.cwd, main));
23
+ }
24
+
25
+ /**
26
+ * The component an entry registers with `registerRootComponent(App)`, when `App` is imported from a local
27
+ * file: its name and that file. null for anything else (inline components, packages, several calls).
28
+ */
29
+ export function registeredRoot(ctx: CliContext, entry: string, source: string): { name: string; file: string | null; importPath: string } | null {
30
+ const calls = [...source.matchAll(/registerRootComponent\(\s*([A-Za-z_$][\w$]*)\s*\)/g)];
31
+ if (calls.length !== 1) return null;
32
+ const name = (calls[0] as RegExpMatchArray)[1] as string;
33
+ const imported = new RegExp(`import\\s+(?:${name}\\b|\\{[^}]*\\b(?:default\\s+as\\s+)?${name}\\b[^}]*\\})[^;'"]*from\\s+['"](\\.{1,2}/[^'"]+)['"]`).exec(source);
34
+ if (imported === null) return null;
35
+ const importPath = imported[1] as string;
36
+ return { name, file: resolveSource(ctx, path.resolve(path.dirname(entry), importPath)), importPath };
37
+ }
38
+
39
+ /** The files `<QuiescoRoot>` is looked for in: the usual root files, the entry and the component it registers. */
40
+ export function rootSourceFiles(ctx: CliContext, main: string | undefined): string[] {
41
+ const files = ROOT_CANDIDATES.map((f) => path.join(ctx.cwd, f));
42
+ const entry = entryFile(ctx, main);
43
+ if (entry !== null) {
44
+ files.push(entry);
45
+ const root = registeredRoot(ctx, entry, ctx.readFile(entry) ?? '');
46
+ if (root?.file != null) files.push(root.file);
47
+ }
48
+ return [...new Set(files)].filter((f) => ctx.exists(f));
49
+ }
50
+
51
+ /**
52
+ * Issue #20: wrap the component an entry registers in `<QuiescoRoot>`, without JSX (the entry is often
53
+ * index.ts). Returns the new source, or null when the entry does not have the plain
54
+ * `registerRootComponent(App)` shape with a local `App`, or already mentions QuiescoRoot.
55
+ */
56
+ export function wrapRegisteredRoot(ctx: CliContext, entry: string, source: string): string | null {
57
+ if (source.includes('QuiescoRoot')) return null;
58
+ const root = registeredRoot(ctx, entry, source);
59
+ if (root === null) return null;
60
+ const agentImport = /^import '@quiesco\/agent';/m;
61
+ let out = agentImport.test(source)
62
+ ? source.replace(agentImport, "import { QuiescoRoot } from '@quiesco/agent';")
63
+ : `import { QuiescoRoot } from '@quiesco/agent'; // first: Quiesco hooks into React before the app loads\n${source}`;
64
+ out = out.replace(/(import\s[^;]*?from\s+['"]expo['"];?\n|import\s+['"]expo['"];?\n)/, `$1import { createElement } from 'react';\n`);
65
+ if (!out.includes("import { createElement } from 'react';")) out = out.replace(/(^import \{ QuiescoRoot \}[^\n]*\n)/m, `$1import { createElement } from 'react';\n`);
66
+ const wrapper = [
67
+ `// <QuiescoRoot> connects the app to Quiesco and remounts it for the soft reset before each scenario`,
68
+ `// (it renders ${root.name} unchanged in builds without EXPO_PUBLIC_QUIESCO=1).`,
69
+ `function QuiescoApp() {`,
70
+ ` return createElement(QuiescoRoot, null, createElement(${root.name}));`,
71
+ `}`,
72
+ ``,
73
+ `registerRootComponent(QuiescoApp)`,
74
+ ].join('\n');
75
+ return out.replace(/registerRootComponent\(\s*[A-Za-z_$][\w$]*\s*\)/, wrapper);
76
+ }