quiesco 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `quiesco build ios|android [--force]` (issue #5): the e2e build of the app, written where the config's
2
+ * `quiesco build ios|android [--force] [--clean]` (issue #5): the e2e build of the app, written where the config's
3
3
  * `binaryPath` says, so `quiesco test` finds it. `expo prebuild` with EXPO_PUBLIC_QUIESCO=1, then
4
4
  * - iOS: `xcodebuild` for the simulator, with the derived data path, configuration and scheme read from
5
5
  * `apps.ios.binaryPath` (`<derivedData>/Build/Products/<Configuration>-iphonesimulator/<Name>.app`);
@@ -7,7 +7,10 @@
7
7
  * `binaryPath` when that is somewhere else.
8
8
  * A Debug build is skipped when its native inputs (app config, dependencies and their installed versions)
9
9
  * did not change since the last build and the binary is still there; `--force` builds anyway. Release builds
10
- * embed the JS bundle, so they are always built.
10
+ * embed the JS bundle, so they are always built. `--clean` runs `expo prebuild --clean` (ios/ / android/ are
11
+ * deleted and generated again) and so builds anyway too.
12
+ * With `appDir` (or `--app-dir`, issue #54) the app is built in that directory; `binaryPath` stays relative
13
+ * to the working directory (the config's).
11
14
  */
12
15
  import { createHash } from 'node:crypto';
13
16
  import fs from 'node:fs';
@@ -16,14 +19,17 @@ import path from 'node:path';
16
19
  import type { QuiescoConfig } from '@quiesco/core';
17
20
  import { loadConfig } from '@quiesco/core';
18
21
 
22
+ import { APP_DIR_OPTION, appContext } from '../app-dir.js';
19
23
  import type { CliContext } from '../context.js';
20
24
  import { takeOption } from '../context.js';
21
25
 
22
- export const BUILD_HELP = `Usage: quiesco build ios|android [--force]
26
+ export const BUILD_HELP = `Usage: quiesco build ios|android [--force] [--clean] [--app-dir <dir>]
23
27
 
24
28
  Builds the app for e2e tests (EXPO_PUBLIC_QUIESCO=1: expo prebuild, then xcodebuild / gradle) and writes it
25
29
  to apps.<platform>.binaryPath in quiesco.config. A Debug build is skipped when the native inputs (app config,
26
- dependencies) did not change since the last one; --force builds anyway.`;
30
+ dependencies) did not change since the last one; --force builds anyway. --clean deletes ios/ / android/ and
31
+ generates them again (expo prebuild --clean; changes made by hand in them are lost), then builds. The app is the one in appDir
32
+ (quiesco.config) or --app-dir when the tests are in a package of their own.`;
27
33
 
28
34
  export interface BuildDeps {
29
35
  loadConfig: (cwd: string) => Promise<QuiescoConfig>;
@@ -73,8 +79,20 @@ export async function buildCommand(args: readonly string[], ctx: CliContext, dep
73
79
  ctx.out(BUILD_HELP);
74
80
  return 0;
75
81
  }
76
- const force = args.includes('--force');
77
- const rest = takeOption(args.filter((a) => a !== '--force'), '--platform');
82
+ const clean = args.includes('--clean');
83
+ const force = clean || args.includes('--force');
84
+ const appDirOpt = takeOption(args.filter((a) => a !== '--force' && a !== '--clean'), APP_DIR_OPTION);
85
+ const rest = takeOption(appDirOpt.rest, '--platform');
86
+ const unknown = rest.rest.find((a) => a.startsWith('-'));
87
+ if (unknown !== undefined) {
88
+ ctx.err(`quiesco build: unknown option ${unknown}\n\n${BUILD_HELP}`);
89
+ return 2;
90
+ }
91
+ const extra = rest.value === undefined ? rest.rest.slice(1) : rest.rest;
92
+ if (extra.length > 0) {
93
+ ctx.err(`quiesco build: unexpected argument ${extra[0]}\n\n${BUILD_HELP}`);
94
+ return 2;
95
+ }
78
96
  const platform = rest.value ?? rest.rest[0];
79
97
  if (platform !== 'ios' && platform !== 'android') {
80
98
  ctx.err(`quiesco build: choose ios or android (quiesco build ios). The web needs no build: quiesco test starts Metro, or export it with EXPO_PUBLIC_QUIESCO=1 npx expo export --platform web.`);
@@ -87,6 +105,7 @@ export async function buildCommand(args: readonly string[], ctx: CliContext, dep
87
105
  ctx.err(`quiesco build: ${(e as Error).message}`);
88
106
  return 1;
89
107
  }
108
+ const app = appContext(ctx, config, appDirOpt.value);
90
109
  const binaryPath = config.apps[platform]?.binaryPath;
91
110
  if (binaryPath === undefined) {
92
111
  ctx.err(`quiesco build: apps.${platform}.binaryPath is not set in quiesco.config: that is where the build goes (npx quiesco init writes it).`);
@@ -99,8 +118,8 @@ export async function buildCommand(args: readonly string[], ctx: CliContext, dep
99
118
  }
100
119
  const release = platform === 'ios' ? !/^debug$/i.test(ios?.configuration ?? '') : androidVariant(binaryPath) === 'release';
101
120
  const binary = path.resolve(ctx.cwd, binaryPath);
102
- const stampFile = path.join(ctx.cwd, '.expo', 'quiesco', `build-${platform}.json`);
103
- const fingerprint = nativeFingerprint(ctx, platform, binaryPath);
121
+ const stampFile = path.join(app.cwd, '.expo', 'quiesco', `build-${platform}.json`);
122
+ const fingerprint = nativeFingerprint(app, platform, binaryPath);
104
123
  if (!force && !release && ctx.exists(binary)) {
105
124
  const stamp = ctx.readFile(stampFile);
106
125
  if (stamp !== null && (JSON.parse(stamp) as { fingerprint?: string }).fingerprint === fingerprint) {
@@ -110,28 +129,32 @@ export async function buildCommand(args: readonly string[], ctx: CliContext, dep
110
129
  }
111
130
 
112
131
  const env = { ...ctx.env, EXPO_PUBLIC_QUIESCO: '1' };
113
- ctx.out(`quiesco build: expo prebuild --platform ${platform} (EXPO_PUBLIC_QUIESCO=1)`);
114
- let code = await ctx.run('npx', ['expo', 'prebuild', '--platform', platform], { cwd: ctx.cwd, env });
132
+ const prebuild = ['expo', 'prebuild', '--platform', platform, ...(clean ? ['--clean'] : [])];
133
+ ctx.out(`quiesco build: ${prebuild.join(' ')} (EXPO_PUBLIC_QUIESCO=1)`);
134
+ if (app !== ctx) ctx.out(`quiesco build: the app in ${app.cwd}`);
135
+ let code = await ctx.run('npx', prebuild, { cwd: app.cwd, env });
115
136
  if (code !== 0) return fail(ctx, 'expo prebuild', code);
116
137
 
117
138
  if (ios !== null) {
118
139
  const workspace = path.join('ios', `${ios.name}.xcworkspace`);
119
- if (!ctx.exists(path.join(ctx.cwd, workspace))) {
140
+ if (!app.exists(path.join(app.cwd, workspace))) {
120
141
  ctx.err(`quiesco build: ${workspace} not found after prebuild. The .app name in apps.ios.binaryPath must be the Xcode scheme (expo prebuild names it after expo.name).`);
121
142
  return 1;
122
143
  }
123
- const xcode = ['-workspace', workspace, '-scheme', ios.name, '-configuration', ios.configuration, '-sdk', 'iphonesimulator', '-destination', 'generic/platform=iOS Simulator', '-derivedDataPath', ios.derivedData, '-quiet', 'build'];
144
+ // binaryPath (and so the derived data) is relative to the working directory; xcodebuild runs in the app.
145
+ const derivedData = path.relative(app.cwd, path.resolve(ctx.cwd, ios.derivedData)) || '.';
146
+ const xcode = ['-workspace', workspace, '-scheme', ios.name, '-configuration', ios.configuration, '-sdk', 'iphonesimulator', '-destination', 'generic/platform=iOS Simulator', '-derivedDataPath', derivedData, '-quiet', 'build'];
124
147
  ctx.out(`quiesco build: xcodebuild ${xcode.join(' ')}`);
125
- code = await ctx.run('xcodebuild', xcode, { cwd: ctx.cwd, env });
148
+ code = await ctx.run('xcodebuild', xcode, { cwd: app.cwd, env });
126
149
  if (code !== 0) return fail(ctx, 'xcodebuild', code);
127
150
  } else {
128
151
  const variant = androidVariant(binaryPath);
129
152
  const task = `assemble${variant === 'release' ? 'Release' : 'Debug'}`;
130
153
  const gradlew = ctx.platform === 'win32' ? 'gradlew.bat' : './gradlew';
131
154
  ctx.out(`quiesco build: ${gradlew} ${task} (in android/)`);
132
- code = await ctx.run(gradlew, [task], { cwd: path.join(ctx.cwd, 'android'), env });
155
+ code = await ctx.run(gradlew, [task], { cwd: path.join(app.cwd, 'android'), env });
133
156
  if (code !== 0) return fail(ctx, `gradle ${task}`, code);
134
- const output = path.join(ctx.cwd, 'android', 'app', 'build', 'outputs', 'apk', variant, `app-${variant}.apk`);
157
+ const output = path.join(app.cwd, 'android', 'app', 'build', 'outputs', 'apk', variant, `app-${variant}.apk`);
135
158
  if (path.resolve(output) !== binary) {
136
159
  fs.mkdirSync(path.dirname(binary), { recursive: true });
137
160
  fs.copyFileSync(output, binary);
@@ -1,7 +1,8 @@
1
1
  /**
2
- * `quiesco doctor [--platform ios|android|web]` (requirements.md §6.12): check the environment and the
3
- * project's Quiesco setup. Every check says what is wrong and how to fix it; exit code 1 when a check
4
- * fails (warnings do not fail).
2
+ * `quiesco doctor [--platform ios|android|web] [--app-dir <dir>]` (requirements.md §6.12): check the
3
+ * environment and the project's Quiesco setup. Every check says what is wrong and how to fix it; exit code
4
+ * 1 when a check fails (warnings do not fail). With `appDir` (issue #54) the app's checks run in the app's
5
+ * directory and the test setup's (runner, config, features) in the working directory.
5
6
  */
6
7
  import fs from 'node:fs';
7
8
  import net from 'node:net';
@@ -10,6 +11,7 @@ import path from 'node:path';
10
11
  import type { QuiescoConfig } from '@quiesco/core';
11
12
  import { loadConfig, serverPort } from '@quiesco/core';
12
13
 
14
+ import { APP_DIR_OPTION, appContext, inApp } from '../app-dir.js';
13
15
  import type { CliContext, CliPlatform } from '../context.js';
14
16
  import { PLATFORMS, parsePlatform, takeOption } from '../context.js';
15
17
  import { MIN_EXPO_SDK, UPGRADE_SDK_FIX, expoSdk } from '../expo-sdk.js';
@@ -83,29 +85,46 @@ function expoCheck(ctx: CliContext, pkg: PackageJson): CheckResult {
83
85
  return sdk.sdk >= MIN_EXPO_SDK ? { name: 'Expo project', status: 'ok', detail } : { name: 'Expo project', status: 'fail', detail, fix: UPGRADE_SDK_FIX };
84
86
  }
85
87
 
86
- function projectChecks(ctx: CliContext): CheckResult[] {
88
+ /**
89
+ * The app (expo, @quiesco/agent, config plugin, Metro, entry) in `app`, the test setup (runner packages,
90
+ * older inits' files) in `ctx`: the same directory unless appDir is set (issue #54).
91
+ */
92
+ function projectChecks(ctx: CliContext, app: CliContext): CheckResult[] {
87
93
  const results: CheckResult[] = [];
88
- const pkg = readJson<PackageJson>(ctx, path.join(ctx.cwd, 'package.json'));
94
+ const separate = app !== ctx;
95
+ const pkg = readJson<PackageJson>(app, path.join(app.cwd, 'package.json'));
89
96
  if (pkg === null) {
90
- return [{ name: 'project', status: 'fail', detail: `no package.json in ${ctx.cwd}`, fix: 'Run quiesco in the Expo app directory.' }];
97
+ return [
98
+ {
99
+ name: 'project',
100
+ status: 'fail',
101
+ detail: `no package.json in ${app.cwd}`,
102
+ fix: separate ? 'appDir (quiesco.config) or --app-dir must name the Expo app\'s directory.' : 'Run quiesco in the Expo app directory, or set appDir in quiesco.config to where the app is.',
103
+ },
104
+ ];
91
105
  }
92
- results.push(expoCheck(ctx, pkg));
93
- // The runner the commands use without --runner, with Quiesco's integration and the runner itself.
94
- const wanted = ['@quiesco/agent', ...RUNNER_PACKAGES[projectRunner(ctx)]];
95
- const missing = wanted.filter((d) => !hasDep(pkg, d));
106
+ const testPkg = separate ? readJson<PackageJson>(ctx, path.join(ctx.cwd, 'package.json')) : pkg;
107
+ results.push(expoCheck(app, pkg));
108
+ // The app has the agent; the test project has the runner the commands use without --runner, with
109
+ // Quiesco's integration and the runner itself.
110
+ const runnerPkgs = RUNNER_PACKAGES[projectRunner(ctx)];
111
+ const missing = [
112
+ ...(hasDep(pkg, '@quiesco/agent') ? [] : [`@quiesco/agent${separate ? ` (in ${inApp(ctx, app)})` : ''}`]),
113
+ ...runnerPkgs.filter((d) => testPkg === null || !hasDep(testPkg, d)),
114
+ ];
96
115
  results.push(
97
116
  missing.length === 0
98
- ? { name: 'Quiesco packages', status: 'ok', detail: wanted.join(', ') }
117
+ ? { name: 'Quiesco packages', status: 'ok', detail: ['@quiesco/agent', ...runnerPkgs].join(', ') }
99
118
  : { name: 'Quiesco packages', status: 'fail', detail: `missing ${missing.join(', ')}`, fix: 'Run `npx quiesco init`, or install them.' },
100
119
  );
101
120
 
102
- results.push(...versionChecks(ctx, pkg));
121
+ results.push(...versionChecks(ctx, [{ ctx: app, pkg }, ...(separate && testPkg !== null ? [{ ctx, pkg: testPkg }] : [])]));
103
122
  results.push(...legacyChecks(ctx));
104
123
 
105
- const appJson = readJson<{ expo?: { plugins?: unknown[] } }>(ctx, path.join(ctx.cwd, 'app.json'));
124
+ const appJson = readJson<{ expo?: { plugins?: unknown[] } }>(app, path.join(app.cwd, 'app.json'));
106
125
  const plugins = appJson?.expo?.plugins ?? [];
107
126
  const listed = plugins.some((p) => p === '@quiesco/expo-plugin' || (Array.isArray(p) && p[0] === '@quiesco/expo-plugin'));
108
- const dynamic = ['app.config.ts', 'app.config.js', 'app.config.mjs'].some((f) => ctx.exists(path.join(ctx.cwd, f)));
127
+ const dynamic = ['app.config.ts', 'app.config.js', 'app.config.mjs'].some((f) => app.exists(path.join(app.cwd, f)));
109
128
  results.push(
110
129
  listed
111
130
  ? { name: 'config plugin', status: 'ok', detail: '@quiesco/expo-plugin in app.json' }
@@ -114,8 +133,8 @@ function projectChecks(ctx: CliContext): CheckResult[] {
114
133
  : { name: 'config plugin', status: 'warn', detail: '@quiesco/expo-plugin is not in app.json plugins', fix: 'Add "@quiesco/expo-plugin" to expo.plugins (needed for iOS / Android e2e builds, not for web).' },
115
134
  );
116
135
 
117
- const metro = ['metro.config.js', 'metro.config.cjs', 'metro.config.mjs', 'metro.config.ts'].map((f) => path.join(ctx.cwd, f)).find((f) => ctx.exists(f));
118
- const metroSrc = metro !== undefined ? ctx.readFile(metro) : null;
136
+ const metro = ['metro.config.js', 'metro.config.cjs', 'metro.config.mjs', 'metro.config.ts'].map((f) => path.join(app.cwd, f)).find((f) => app.exists(f));
137
+ const metroSrc = metro !== undefined ? app.readFile(metro) : null;
119
138
  results.push(
120
139
  metroSrc !== null && metroSrc.includes('withQuiesco')
121
140
  ? { name: 'Metro', status: 'ok', detail: `${path.basename(metro as string)} uses withQuiesco()` }
@@ -136,8 +155,8 @@ function projectChecks(ctx: CliContext): CheckResult[] {
136
155
  fix: "Create index.ts with `import '@quiesco/agent';` as the first line followed by the original entry (e.g. `import 'expo-router/entry';`), and set \"main\": \"index.ts\".",
137
156
  });
138
157
  } else {
139
- const entry = [main, `${main}.ts`, `${main}.tsx`, `${main}.js`].map((f) => path.join(ctx.cwd, f)).find((f) => ctx.exists(f));
140
- const src = entry !== undefined ? ctx.readFile(entry) : null;
158
+ const entry = [main, `${main}.ts`, `${main}.tsx`, `${main}.js`].map((f) => path.join(app.cwd, f)).find((f) => app.exists(f));
159
+ const src = entry !== undefined ? app.readFile(entry) : null;
141
160
  const first = src !== null ? firstImport(src) : null;
142
161
  results.push(
143
162
  first === '@quiesco/agent'
@@ -152,13 +171,18 @@ function projectChecks(ctx: CliContext): CheckResult[] {
152
171
 
153
172
  /**
154
173
  * Issue #17: every Quiesco package in package.json is installed at one version, and every `quiesco <cmd>`
155
- * in the scripts exists in it.
174
+ * in the scripts exists in it. With appDir (issue #54) the app's and the test project's packages together.
156
175
  */
157
- function versionChecks(ctx: CliContext, pkg: PackageJson): CheckResult[] {
176
+ function versionChecks(ctx: CliContext, projects: readonly { ctx: CliContext; pkg: PackageJson }[]): CheckResult[] {
158
177
  const results: CheckResult[] = [];
159
- const names = [...new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})])].filter(isQuiescoPackage).sort();
178
+ const declared = projects.flatMap((p) =>
179
+ [...new Set([...Object.keys(p.pkg.dependencies ?? {}), ...Object.keys(p.pkg.devDependencies ?? {})])].filter(isQuiescoPackage).map((name) => ({ name, dir: p.ctx })),
180
+ );
181
+ const names = [...new Set(declared.map((d) => d.name))].sort();
160
182
  if (names.length === 0) return results;
161
- const installed = names.map((name) => ({ name, version: installedVersion(ctx, name) }));
183
+ const installed = declared
184
+ .sort((a, b) => a.name.localeCompare(b.name))
185
+ .map((d) => ({ name: d.dir === ctx ? d.name : `${d.name} (${inApp(ctx, d.dir)})`, version: installedVersion(d.dir, d.name) }));
162
186
  const missing = installed.filter((p) => p.version === null).map((p) => p.name);
163
187
  const versions = [...new Set(installed.flatMap((p) => (p.version !== null ? [p.version] : [])))];
164
188
  const list = installed.map((p) => `${p.name} ${p.version ?? '(not installed)'}`).join(', ');
@@ -186,7 +210,7 @@ function versionChecks(ctx: CliContext, pkg: PackageJson): CheckResult[] {
186
210
  },
187
211
  );
188
212
  }
189
- const unknown = scriptCommands(pkg.scripts).filter((c) => !(CLI_COMMANDS as readonly string[]).includes(c.command));
213
+ const unknown = projects.flatMap((p) => scriptCommands(p.pkg.scripts)).filter((c) => !(CLI_COMMANDS as readonly string[]).includes(c.command));
190
214
  if (unknown.length > 0) {
191
215
  results.push({
192
216
  name: 'scripts',
@@ -267,7 +291,7 @@ interface AppJsonIds {
267
291
  * uses) and, when they exist, with the prebuilt Android project and the iOS build. Placeholders left by
268
292
  * init fail.
269
293
  */
270
- async function appIdChecks(ctx: CliContext, config: QuiescoConfig): Promise<CheckResult[]> {
294
+ async function appIdChecks(ctx: CliContext, app: CliContext, config: QuiescoConfig): Promise<CheckResult[]> {
271
295
  const { ios, android } = config.apps;
272
296
  if (ios === undefined && android === undefined) return [];
273
297
  const configFile = CONFIG_FILES.find((f) => ctx.exists(path.join(ctx.cwd, f)));
@@ -282,12 +306,12 @@ async function appIdChecks(ctx: CliContext, config: QuiescoConfig): Promise<Chec
282
306
  },
283
307
  ];
284
308
  }
285
- const dynamic = DYNAMIC_APP_CONFIGS.find((f) => ctx.exists(path.join(ctx.cwd, f)));
309
+ const dynamic = DYNAMIC_APP_CONFIGS.find((f) => app.exists(path.join(app.cwd, f)));
286
310
  const results: CheckResult[] = [];
287
311
  if (dynamic !== undefined) {
288
312
  results.push({ name: 'app IDs', status: 'warn', detail: `${dynamic} found; cannot compare the app IDs with it`, fix: 'Make sure apps.ios.bundleId, apps.android.package and devClient.scheme are the values your app config sets.' });
289
313
  } else {
290
- const expo = readJson<AppJsonIds>(ctx, path.join(ctx.cwd, 'app.json'))?.expo ?? {};
314
+ const expo = readJson<AppJsonIds>(app, path.join(app.cwd, 'app.json'))?.expo ?? {};
291
315
  const schemes = expo.scheme === undefined ? [] : Array.isArray(expo.scheme) ? expo.scheme : [expo.scheme];
292
316
  const problems: string[] = [];
293
317
  const compare = (what: string, want: string, have: string | undefined): void => {
@@ -308,9 +332,9 @@ async function appIdChecks(ctx: CliContext, config: QuiescoConfig): Promise<Chec
308
332
  }
309
333
  // The builds: an app built before the IDs changed is another app.
310
334
  if (android !== undefined) {
311
- const gradle = ctx.readFile(path.join(ctx.cwd, 'android/app/build.gradle'));
335
+ const gradle = app.readFile(path.join(app.cwd, 'android/app/build.gradle'));
312
336
  const built = gradle === null ? undefined : /applicationId\s*(?:=\s*)?['"]([^'"]+)['"]/.exec(gradle)?.[1];
313
- const manifest = ctx.readFile(path.join(ctx.cwd, 'android/app/src/main/AndroidManifest.xml'));
337
+ const manifest = app.readFile(path.join(app.cwd, 'android/app/src/main/AndroidManifest.xml'));
314
338
  const scheme = android.devClient?.scheme;
315
339
  const wrong: string[] = [];
316
340
  if (built !== undefined && built !== android.package) wrong.push(`android/app/build.gradle has applicationId ${built}`);
@@ -466,7 +490,7 @@ export const defaultDoctorDeps: DoctorDeps = {
466
490
  }),
467
491
  };
468
492
 
469
- export async function runChecks(ctx: CliContext, only: CliPlatform | undefined, deps: DoctorDeps = defaultDoctorDeps): Promise<CheckResult[]> {
493
+ export async function runChecks(ctx: CliContext, only: CliPlatform | undefined, deps: DoctorDeps = defaultDoctorDeps, appDirFlag?: string): Promise<CheckResult[]> {
470
494
  const results: CheckResult[] = [];
471
495
  const major = Number.parseInt(ctx.nodeVersion, 10);
472
496
  results.push(
@@ -484,17 +508,27 @@ export async function runChecks(ctx: CliContext, only: CliPlatform | undefined,
484
508
  fix: 'Metro started with CI set does not watch files, so code changes do not reach the app under test. Unset it (unset CI) before EXPO_PUBLIC_QUIESCO=1 npx expo start.',
485
509
  });
486
510
  }
487
- results.push(...projectChecks(ctx));
488
- results.push(rootCheck(ctx, readJson<PackageJson>(ctx, path.join(ctx.cwd, 'package.json'))?.main));
489
-
511
+ // The config first: its appDir says where the app is (issue #54).
490
512
  let config: QuiescoConfig | null = null;
513
+ let configError: string | null = null;
491
514
  try {
492
515
  config = await deps.loadConfig(ctx.cwd);
493
- results.push({ name: 'quiesco.config', status: 'ok', detail: `apps: ${Object.keys(config.apps).join(', ') || 'none'}` });
494
- results.push(...(await appIdChecks(ctx, config)));
495
- results.push(...buildScriptChecks(readJson<PackageJson>(ctx, path.join(ctx.cwd, 'package.json')), config));
496
516
  } catch (e) {
497
- results.push({ name: 'quiesco.config', status: 'fail', detail: (e as Error).message.split('\n')[0] ?? '', fix: 'Create quiesco.config.mts (npx quiesco init writes one).' });
517
+ configError = (e as Error).message.split('\n')[0] ?? '';
518
+ }
519
+ const app = appContext(ctx, config, appDirFlag);
520
+ if (app !== ctx) results.push({ name: 'app', status: 'ok', detail: `${inApp(ctx, app)} (${appDirFlag !== undefined ? APP_DIR_OPTION : 'appDir'}); the test setup in ${ctx.cwd}` });
521
+ results.push(...projectChecks(ctx, app));
522
+ results.push(rootCheck(app, readJson<PackageJson>(app, path.join(app.cwd, 'package.json'))?.main));
523
+
524
+ if (config !== null) {
525
+ results.push({ name: 'quiesco.config', status: 'ok', detail: `apps: ${Object.keys(config.apps).join(', ') || 'none'}` });
526
+ results.push(...(await appIdChecks(ctx, app, config)));
527
+ // A script that builds may be in either package.json.
528
+ const scripts = { ...readJson<PackageJson>(app, path.join(app.cwd, 'package.json'))?.scripts, ...readJson<PackageJson>(ctx, path.join(ctx.cwd, 'package.json'))?.scripts };
529
+ results.push(...buildScriptChecks({ scripts }, config));
530
+ } else {
531
+ results.push({ name: 'quiesco.config', status: 'fail', detail: configError ?? '', fix: 'Create quiesco.config.mts (npx quiesco init writes one), in the test project when the app is elsewhere (appDir).' });
498
532
  }
499
533
 
500
534
  const platforms = only !== undefined ? [only] : PLATFORMS.filter((p) => config?.apps[p] !== undefined);
@@ -512,12 +546,13 @@ export async function runChecks(ctx: CliContext, only: CliPlatform | undefined,
512
546
  }
513
547
 
514
548
  export async function doctorCommand(args: readonly string[], ctx: CliContext, deps: DoctorDeps = defaultDoctorDeps): Promise<number> {
515
- const { value, rest } = takeOption(args, '--platform');
516
- if (rest.length > 0) {
517
- ctx.err(`quiesco doctor: unknown arguments ${rest.join(' ')}`);
549
+ const { value, rest: afterPlatform } = takeOption(args, '--platform');
550
+ const appDir = takeOption(afterPlatform, APP_DIR_OPTION);
551
+ if (appDir.rest.length > 0) {
552
+ ctx.err(`quiesco doctor: unknown arguments ${appDir.rest.join(' ')}`);
518
553
  return 2;
519
554
  }
520
- const results = await runChecks(ctx, parsePlatform(value), deps);
555
+ const results = await runChecks(ctx, parsePlatform(value), deps, appDir.value);
521
556
  for (const r of results) {
522
557
  ctx.out(`${ICON[r.status]} ${r.name}: ${r.detail}`);
523
558
  if (r.fix !== undefined && r.status !== 'ok') ctx.out(` → ${r.fix}`);
@@ -136,7 +136,13 @@ import { defineConfig } from 'vitest/config';
136
136
 
137
137
  export default defineConfig({
138
138
  plugins: [quiescoPlugin()],
139
- test: { ...quiesco(), include: ['e2e/**/*.test.ts'] },
139
+ test: {
140
+ ...quiesco(),
141
+ include: ['e2e/**/*.test.ts'],
142
+ // Hooks shared by every test file (test.beforeEach …) go in a setup file: a module imported by several
143
+ // files runs once per worker (files share their modules), so its hooks would only apply to the first.
144
+ // setupFiles: ['e2e/setup.ts'],
145
+ },
140
146
  });
141
147
  `;
142
148
 
@@ -7,12 +7,16 @@
7
7
  *
8
8
  * Only changes it can make safely; anything else is listed with what to do. Running it again changes
9
9
  * nothing. `--dry-run` lists the changes without making them.
10
+ *
11
+ * With `appDir` (or `--app-dir`, issue #54) the app's packages (agent, native, expo-plugin) and files
12
+ * (app.json, <QuiescoRoot>) are upgraded in the app's directory, the rest in the working directory.
10
13
  */
11
14
  import path from 'node:path';
12
15
 
13
16
  import type { QuiescoConfig } from '@quiesco/core';
14
17
  import { loadConfig } from '@quiesco/core';
15
18
 
19
+ import { APP_DIR_OPTION, appContext } from '../app-dir.js';
16
20
  import type { CliContext, CliPlatform } from '../context.js';
17
21
  import { PLATFORMS, takeFlag, takeOption } from '../context.js';
18
22
  import { installedVersion, isQuiescoPackage } from '../packages.js';
@@ -33,11 +37,13 @@ const CUCUMBER_FILES = ['cucumber.mjs', 'cucumber.js', 'cucumber.cjs', 'cucumber
33
37
  /** The line 0.1.x wrote into cucumber.mjs (issue #8). */
34
38
  const OLD_PATHS_LINE = /^[ \t]*paths:[ \t]*\[[ \t]*['"]features\/\*\*\/\*\.feature['"][ \t]*\],?[ \t]*\r?\n/m;
35
39
 
36
- /** Quiesco packages to install: the ones the platforms need and every other one the project already has. */
37
- function packagesToInstall(pkg: PackageJson, platforms: readonly CliPlatform[]): { runtime: string[]; dev: string[] } {
38
- const needed = [...RUNTIME, ...DEV, ...(platforms.includes('web') ? WEB_DEV : [])].filter(isQuiescoPackage);
40
+ /** The app's own packages, installed in the app when the tests are elsewhere (appDir, issue #54). */
41
+ const APP_PACKAGES = [...RUNTIME, '@quiesco/expo-plugin'];
42
+
43
+ /** Quiesco packages to install: the `needed` ones and every other one the project already has. */
44
+ function packagesToInstall(pkg: PackageJson, needed: readonly string[]): { runtime: string[]; dev: string[] } {
39
45
  const present = [...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})].filter(isQuiescoPackage);
40
- const all = [...new Set([...needed, ...present])];
46
+ const all = [...new Set([...needed.filter(isQuiescoPackage), ...present])];
41
47
  // Keep each package in the group it is in; new ones go where init puts them.
42
48
  const isRuntime = (n: string): boolean => pkg.dependencies?.[n] !== undefined || (pkg.devDependencies?.[n] === undefined && RUNTIME.includes(n));
43
49
  return { runtime: all.filter(isRuntime), dev: all.filter((n) => !isRuntime(n)) };
@@ -126,13 +132,24 @@ export async function upgradeCommand(args: readonly string[], ctx: CliContext, d
126
132
  rest = skipInstall.rest;
127
133
  const dryRun = takeFlag(rest, '--dry-run');
128
134
  rest = dryRun.rest;
135
+ const appDirOpt = takeOption(rest, APP_DIR_OPTION);
136
+ rest = appDirOpt.rest;
129
137
  if (rest.length > 0) {
130
138
  ctx.err(`quiesco init --upgrade: unknown arguments ${rest.join(' ')}`);
131
139
  return 2;
132
140
  }
133
- const pkg = readJson<PackageJson>(ctx, path.join(ctx.cwd, 'package.json'));
141
+ let config: QuiescoConfig | null = null;
142
+ let configError = '';
143
+ try {
144
+ config = await deps.loadConfig(ctx.cwd);
145
+ } catch (e) {
146
+ configError = (e as Error).message.split('\n')[0] ?? '';
147
+ }
148
+ const app = appContext(ctx, config, appDirOpt.value);
149
+ const separate = app !== ctx;
150
+ const pkg = readJson<PackageJson>(app, path.join(app.cwd, 'package.json'));
134
151
  if (pkg === null || (pkg.dependencies?.['expo'] === undefined && pkg.devDependencies?.['expo'] === undefined)) {
135
- ctx.err(`quiesco init --upgrade: ${ctx.cwd} is not an Expo project (no expo dependency in package.json).`);
152
+ ctx.err(`quiesco init --upgrade: ${app.cwd} is not an Expo project (no expo dependency in package.json).${separate ? '' : ' Tests in a package of their own: set appDir in quiesco.config or pass --app-dir.'}`);
136
153
  return 1;
137
154
  }
138
155
  let platforms: CliPlatform[];
@@ -143,43 +160,57 @@ export async function upgradeCommand(args: readonly string[], ctx: CliContext, d
143
160
  return 2;
144
161
  }
145
162
  platforms = platformsOpt.value.split(',') as CliPlatform[];
163
+ } else if (config !== null) {
164
+ platforms = PLATFORMS.filter((p) => config.apps[p] !== undefined);
146
165
  } else {
147
- try {
148
- const config = await deps.loadConfig(ctx.cwd);
149
- platforms = PLATFORMS.filter((p) => config.apps[p] !== undefined);
150
- } catch (e) {
151
- ctx.err(`quiesco init --upgrade: cannot read quiesco.config (${(e as Error).message.split('\n')[0] ?? ''}).`);
152
- ctx.err('Run quiesco init for a new setup, or name the platforms: quiesco init --upgrade --platforms ios,android,web');
153
- return 1;
154
- }
166
+ ctx.err(`quiesco init --upgrade: cannot read quiesco.config (${configError}).`);
167
+ ctx.err('Run quiesco init for a new setup, or name the platforms: quiesco init --upgrade --platforms ios,android,web');
168
+ return 1;
155
169
  }
156
170
 
157
171
  const steps: InitStep[] = [];
158
172
  const log: StepLog = { ctx, steps, dryRun: dryRun.present };
173
+ // The app's steps; the same as `log` unless the app is elsewhere.
174
+ const appLog: StepLog = { ...log, ctx: app };
159
175
 
160
- // 1. Every Quiesco package at this CLI's version.
161
- const { runtime, dev } = packagesToInstall(pkg, platforms);
162
- const current = [...runtime, ...dev].map((n) => installedVersion(ctx, n));
163
- if (packagesOpt.value === undefined && current.every((v) => v === ctx.version)) {
164
- steps.push({ status: 'skipped', what: 'versions', note: `${current.length} Quiesco packages at ${ctx.version}` });
165
- } else {
166
- const ok = await installPackages(log, {
167
- pm: detectPackageManager(ctx),
176
+ // 1. Every Quiesco package at this CLI's version: one project, or the app's in the app and the rest here.
177
+ const needed = [...RUNTIME, ...DEV, ...(platforms.includes('web') ? WEB_DEV : [])];
178
+ const testPkg = separate ? readJson<PackageJson>(ctx, path.join(ctx.cwd, 'package.json')) : null;
179
+ if (separate && testPkg === null) {
180
+ ctx.err(`quiesco init --upgrade: no package.json in ${ctx.cwd} (the test project).`);
181
+ return 1;
182
+ }
183
+ const sets: { log: StepLog; packages: { runtime: string[]; dev: string[] } }[] = separate
184
+ ? [
185
+ { log: appLog, packages: packagesToInstall(pkg, APP_PACKAGES) },
186
+ { log, packages: packagesToInstall(testPkg as PackageJson, needed.filter((n) => !APP_PACKAGES.includes(n))) },
187
+ ]
188
+ : [{ log, packages: packagesToInstall(pkg, needed) }];
189
+ for (const set of sets) {
190
+ const { runtime, dev } = set.packages;
191
+ const where = separate ? ` in ${path.relative(ctx.cwd, set.log.ctx.cwd) || '.'}` : '';
192
+ const current = [...runtime, ...dev].map((n) => installedVersion(set.log.ctx, n));
193
+ if (packagesOpt.value === undefined && current.every((v) => v === ctx.version)) {
194
+ steps.push({ status: 'skipped', what: 'versions', note: `${current.length} Quiesco packages at ${ctx.version}${where}` });
195
+ continue;
196
+ }
197
+ const ok = await installPackages(set.log, {
198
+ pm: detectPackageManager(set.log.ctx),
168
199
  runtime,
169
200
  dev,
170
- ...(packagesOpt.value !== undefined ? { packagesDir: packagesOpt.value } : {}),
201
+ ...(packagesOpt.value !== undefined ? { packagesDir: path.resolve(ctx.cwd, packagesOpt.value) } : {}),
171
202
  skipInstall: skipInstall.present,
172
203
  });
173
204
  if (!ok) return 1;
174
205
  }
175
206
 
176
- // 2. What older inits wrote.
207
+ // 2. What older inits wrote: the test setup here, app.json and <QuiescoRoot> in the app.
177
208
  fixCucumberPaths(log);
178
209
  ensureTsconfig(log);
179
- const app = ensureAppIds(log, platforms);
180
- fixConfigPlaceholders(log, app);
210
+ const appJson = ensureAppIds(appLog, platforms);
211
+ fixConfigPlaceholders(log, appJson);
181
212
  ensureScripts(log, platforms);
182
- ensureRoot(log);
213
+ ensureRoot(appLog);
183
214
 
184
215
  printSteps(ctx, steps);
185
216
  ctx.out('');
package/src/dev-server.ts CHANGED
@@ -59,8 +59,10 @@ export async function ensureDevServer(ctx: CliContext, config: QuiescoConfig, pl
59
59
  const [command, ...args] = (opts.command ?? ['npx', 'expo', 'start', '--port', '{port}']).map((a) => a.replaceAll('{port}', port));
60
60
  if (command === undefined) throw new Error('devServer.command is empty');
61
61
  const logFile = path.join(ctx.cwd, config.artifacts?.dir ?? 'artifacts', 'metro.log');
62
- ctx.out(`quiesco: starting Metro (${[command, ...args].join(' ')}) with EXPO_PUBLIC_QUIESCO=1; log: ${path.relative(ctx.cwd, logFile)}`);
63
- const proc = ctx.spawnBackground(command, args, { cwd: ctx.cwd, env: { ...ctx.env, EXPO_PUBLIC_QUIESCO: '1' }, logFile });
62
+ // Metro serves the app: in appDir when the tests are a package of their own (issue #54).
63
+ const appDir = config.appDir ?? ctx.cwd;
64
+ ctx.out(`quiesco: starting Metro (${[command, ...args].join(' ')})${appDir !== ctx.cwd ? ` in ${appDir}` : ''} with EXPO_PUBLIC_QUIESCO=1; log: ${path.relative(ctx.cwd, logFile)}`);
65
+ const proc = ctx.spawnBackground(command, args, { cwd: appDir, env: { ...ctx.env, EXPO_PUBLIC_QUIESCO: '1' }, logFile });
64
66
  const offInterrupt = ctx.onInterrupt(() => proc.stop());
65
67
  const server: DevServer = {
66
68
  env: {},