quiesco 0.3.0 → 0.4.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.
- package/dist/cli.d.ts +2 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +3 -6
- package/dist/cli.js.map +1 -1
- package/dist/commands/doctor.d.ts +2 -1
- package/dist/commands/doctor.d.ts.map +1 -1
- package/dist/commands/doctor.js +220 -8
- package/dist/commands/doctor.js.map +1 -1
- package/dist/commands/init.d.ts +2 -10
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +58 -129
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/test.js +1 -1
- package/dist/commands/test.js.map +1 -1
- package/dist/commands/ui.js +1 -1
- package/dist/commands/ui.js.map +1 -1
- package/dist/commands/upgrade.d.ts +8 -0
- package/dist/commands/upgrade.d.ts.map +1 -0
- package/dist/commands/upgrade.js +185 -0
- package/dist/commands/upgrade.js.map +1 -0
- package/dist/context.d.ts +2 -0
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +1 -0
- package/dist/context.js.map +1 -1
- package/dist/dev-server.d.ts +2 -0
- package/dist/dev-server.d.ts.map +1 -1
- package/dist/dev-server.js +4 -2
- package/dist/dev-server.js.map +1 -1
- package/dist/packages.d.ts +17 -0
- package/dist/packages.d.ts.map +1 -0
- package/dist/packages.js +40 -0
- package/dist/packages.js.map +1 -0
- package/dist/project.d.ts +23 -0
- package/dist/project.d.ts.map +1 -0
- package/dist/project.js +74 -0
- package/dist/project.js.map +1 -0
- package/dist/setup-steps.d.ts +95 -0
- package/dist/setup-steps.d.ts.map +1 -0
- package/dist/setup-steps.js +289 -0
- package/dist/setup-steps.js.map +1 -0
- package/package.json +2 -2
- package/src/cli.ts +3 -7
- package/src/commands/doctor.ts +226 -9
- package/src/commands/init.ts +59 -153
- package/src/commands/test.ts +1 -1
- package/src/commands/ui.ts +1 -1
- package/src/commands/upgrade.ts +189 -0
- package/src/context.ts +3 -0
- package/src/dev-server.ts +6 -2
- package/src/packages.ts +42 -0
- package/src/project.ts +76 -0
- package/src/setup-steps.ts +330 -0
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `quiesco init --upgrade [--dry-run] [--platforms …] [--packages <dir>] [--skip-install]` (issues #34, #35):
|
|
3
|
+
* bring a project set up by an older `quiesco init` to this version. Installs every Quiesco package at this
|
|
4
|
+
* CLI's version (`npx quiesco@latest init --upgrade` upgrades), then fixes what older inits wrote and the
|
|
5
|
+
* current one does not: the `paths` line in the cucumber config (#8), tsconfig's allowImportingTsExtensions
|
|
6
|
+
* (#21), app IDs and the config's TODO placeholders (#34), missing e2e scripts, <QuiescoRoot> (#20).
|
|
7
|
+
*
|
|
8
|
+
* Only changes it can make safely; anything else is listed with what to do. Running it again changes
|
|
9
|
+
* nothing. `--dry-run` lists the changes without making them.
|
|
10
|
+
*/
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
|
|
13
|
+
import type { QuiescoConfig } from '@quiesco/core';
|
|
14
|
+
import { loadConfig } from '@quiesco/core';
|
|
15
|
+
|
|
16
|
+
import type { CliContext, CliPlatform } from '../context.js';
|
|
17
|
+
import { PLATFORMS, takeFlag, takeOption } from '../context.js';
|
|
18
|
+
import { installedVersion, isQuiescoPackage } from '../packages.js';
|
|
19
|
+
import { entryFile, registeredRoot, rootSourceFiles, wrapRegisteredRoot } from '../project.js';
|
|
20
|
+
import type { AppJson, InitStep, PackageJson, StepLog } from '../setup-steps.js';
|
|
21
|
+
import { DEV, RUNTIME, WEB_DEV, detectPackageManager, ensureAppIds, ensureScripts, ensureTsconfig, firstScheme, installPackages, printSteps, readJson } from '../setup-steps.js';
|
|
22
|
+
|
|
23
|
+
export interface UpgradeDeps {
|
|
24
|
+
loadConfig: (cwd: string) => Promise<QuiescoConfig>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const defaultUpgradeDeps: UpgradeDeps = {
|
|
28
|
+
loadConfig: async (cwd) => (await loadConfig({ cwd })).config,
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const CONFIG_FILES = ['quiesco.config.mts', 'quiesco.config.ts', 'quiesco.config.mjs', 'quiesco.config.js'];
|
|
32
|
+
const CUCUMBER_FILES = ['cucumber.mjs', 'cucumber.js', 'cucumber.cjs', 'cucumber.json', 'cucumber.yaml', 'cucumber.yml'];
|
|
33
|
+
/** The line 0.1.x wrote into cucumber.mjs (issue #8). */
|
|
34
|
+
const OLD_PATHS_LINE = /^[ \t]*paths:[ \t]*\[[ \t]*['"]features\/\*\*\/\*\.feature['"][ \t]*\],?[ \t]*\r?\n/m;
|
|
35
|
+
|
|
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);
|
|
39
|
+
const present = [...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})].filter(isQuiescoPackage);
|
|
40
|
+
const all = [...new Set([...needed, ...present])];
|
|
41
|
+
// Keep each package in the group it is in; new ones go where init puts them.
|
|
42
|
+
const isRuntime = (n: string): boolean => pkg.dependencies?.[n] !== undefined || (pkg.devDependencies?.[n] === undefined && RUNTIME.includes(n));
|
|
43
|
+
return { runtime: all.filter(isRuntime), dev: all.filter((n) => !isRuntime(n)) };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function fixCucumberPaths(log: StepLog): void {
|
|
47
|
+
const { ctx, steps } = log;
|
|
48
|
+
const rel = CUCUMBER_FILES.find((f) => ctx.exists(path.join(ctx.cwd, f)));
|
|
49
|
+
if (rel === undefined) return;
|
|
50
|
+
const file = path.join(ctx.cwd, rel);
|
|
51
|
+
const text = ctx.readFile(file) ?? '';
|
|
52
|
+
if (OLD_PATHS_LINE.test(text)) {
|
|
53
|
+
if (!log.dryRun) ctx.writeFile(file, text.replace(OLD_PATHS_LINE, ''));
|
|
54
|
+
steps.push({ status: 'updated', what: rel, note: "removed paths: ['features/**/*.feature'] (the default; with it, quiesco test <file> ran every feature)" });
|
|
55
|
+
} else if (/\bpaths\b["']?\s*:/.test(text)) {
|
|
56
|
+
steps.push({ status: 'todo', what: rel, note: 'sets paths: cucumber-js adds them to the files given on the command line, so quiesco test <file> runs them all; remove it unless you need it' });
|
|
57
|
+
} else {
|
|
58
|
+
steps.push({ status: 'skipped', what: rel, note: 'no paths' });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const PLACEHOLDERS: readonly { todo: string; key: string; value: (app: AppJson) => string | undefined }[] = [
|
|
63
|
+
{ todo: 'expo.ios.bundleIdentifier', key: 'bundleId', value: (a) => a.expo?.ios?.bundleIdentifier },
|
|
64
|
+
{ todo: 'expo.android.package', key: 'package', value: (a) => a.expo?.android?.package },
|
|
65
|
+
{ todo: 'expo.scheme', key: 'scheme', value: (a) => firstScheme(a) },
|
|
66
|
+
];
|
|
67
|
+
|
|
68
|
+
/** Replace the placeholders older inits wrote (`'com.example.app', // TODO: expo.android.package`) with app.json's values. */
|
|
69
|
+
function fixConfigPlaceholders(log: StepLog, app: AppJson): void {
|
|
70
|
+
const { ctx, steps } = log;
|
|
71
|
+
const rel = CONFIG_FILES.find((f) => ctx.exists(path.join(ctx.cwd, f)));
|
|
72
|
+
if (rel === undefined) return;
|
|
73
|
+
const file = path.join(ctx.cwd, rel);
|
|
74
|
+
const text = ctx.readFile(file) ?? '';
|
|
75
|
+
const replaced: string[] = [];
|
|
76
|
+
const left: string[] = [];
|
|
77
|
+
const next = text
|
|
78
|
+
.split('\n')
|
|
79
|
+
.map((line) => {
|
|
80
|
+
const p = PLACEHOLDERS.find((x) => line.includes(`// TODO: ${x.todo}`));
|
|
81
|
+
if (p === undefined) return line;
|
|
82
|
+
const value = p.value(app);
|
|
83
|
+
const keyed = new RegExp(`(\\b${p.key}:\\s*)'[^']*'`);
|
|
84
|
+
if (value === undefined || !keyed.test(line)) {
|
|
85
|
+
left.push(p.todo);
|
|
86
|
+
return line;
|
|
87
|
+
}
|
|
88
|
+
replaced.push(`${p.key} '${value}'`);
|
|
89
|
+
return line.replace(keyed, `$1'${value.replace(/'/g, "\\'")}'`).replace(new RegExp(`\\s*// TODO: ${p.todo.replace(/\./g, '\\.')}`), '');
|
|
90
|
+
})
|
|
91
|
+
.join('\n');
|
|
92
|
+
if (replaced.length > 0) {
|
|
93
|
+
if (!log.dryRun) ctx.writeFile(file, next);
|
|
94
|
+
steps.push({ status: 'updated', what: rel, note: `placeholders replaced with app.json's values: ${replaced.join(', ')}` });
|
|
95
|
+
}
|
|
96
|
+
if (left.length > 0) steps.push({ status: 'todo', what: rel, note: `placeholders left (TODO: ${left.join(', ')}): set them to the values your app config uses` });
|
|
97
|
+
if (replaced.length === 0 && left.length === 0) steps.push({ status: 'skipped', what: rel, note: 'no placeholders' });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** <QuiescoRoot> around the component of registerRootComponent(App) (issue #20); other entries are listed. */
|
|
101
|
+
function ensureRoot(log: StepLog): void {
|
|
102
|
+
const { ctx, steps } = log;
|
|
103
|
+
const main = readJson<PackageJson>(ctx, path.join(ctx.cwd, 'package.json'))?.main;
|
|
104
|
+
if (rootSourceFiles(ctx, main).some((f) => (ctx.readFile(f) ?? '').includes('QuiescoRoot'))) {
|
|
105
|
+
steps.push({ status: 'skipped', what: '<QuiescoRoot>', note: 'the app uses it' });
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
const entry = entryFile(ctx, main);
|
|
109
|
+
const src = entry === null ? null : ctx.readFile(entry);
|
|
110
|
+
const wrapped = entry === null || src === null ? null : wrapRegisteredRoot(ctx, entry, src);
|
|
111
|
+
if (entry === null || src === null || wrapped === null) {
|
|
112
|
+
steps.push({ status: 'todo', what: '<QuiescoRoot>', note: "wrap the root layout in <QuiescoRoot> (import { QuiescoRoot } from '@quiesco/agent'): the app connects to Quiesco from it" });
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (!log.dryRun) ctx.writeFile(entry, wrapped);
|
|
116
|
+
steps.push({ status: 'updated', what: path.basename(entry), note: `wrapped ${registeredRoot(ctx, entry, src)?.name ?? 'the root component'} in <QuiescoRoot>` });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export async function upgradeCommand(args: readonly string[], ctx: CliContext, deps: UpgradeDeps = defaultUpgradeDeps): Promise<number> {
|
|
120
|
+
let rest = [...args];
|
|
121
|
+
const platformsOpt = takeOption(rest, '--platforms');
|
|
122
|
+
rest = platformsOpt.rest;
|
|
123
|
+
const packagesOpt = takeOption(rest, '--packages');
|
|
124
|
+
rest = packagesOpt.rest;
|
|
125
|
+
const skipInstall = takeFlag(rest, '--skip-install');
|
|
126
|
+
rest = skipInstall.rest;
|
|
127
|
+
const dryRun = takeFlag(rest, '--dry-run');
|
|
128
|
+
rest = dryRun.rest;
|
|
129
|
+
if (rest.length > 0) {
|
|
130
|
+
ctx.err(`quiesco init --upgrade: unknown arguments ${rest.join(' ')}`);
|
|
131
|
+
return 2;
|
|
132
|
+
}
|
|
133
|
+
const pkg = readJson<PackageJson>(ctx, path.join(ctx.cwd, 'package.json'));
|
|
134
|
+
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).`);
|
|
136
|
+
return 1;
|
|
137
|
+
}
|
|
138
|
+
let platforms: CliPlatform[];
|
|
139
|
+
if (platformsOpt.value !== undefined) {
|
|
140
|
+
const bad = platformsOpt.value.split(',').filter((p) => !(PLATFORMS as readonly string[]).includes(p));
|
|
141
|
+
if (bad.length > 0) {
|
|
142
|
+
ctx.err(`quiesco init --upgrade: unknown platform ${bad.join(', ')}`);
|
|
143
|
+
return 2;
|
|
144
|
+
}
|
|
145
|
+
platforms = platformsOpt.value.split(',') as CliPlatform[];
|
|
146
|
+
} 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
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const steps: InitStep[] = [];
|
|
158
|
+
const log: StepLog = { ctx, steps, dryRun: dryRun.present };
|
|
159
|
+
|
|
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),
|
|
168
|
+
runtime,
|
|
169
|
+
dev,
|
|
170
|
+
...(packagesOpt.value !== undefined ? { packagesDir: packagesOpt.value } : {}),
|
|
171
|
+
skipInstall: skipInstall.present,
|
|
172
|
+
});
|
|
173
|
+
if (!ok) return 1;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// 2. What older inits wrote.
|
|
177
|
+
fixCucumberPaths(log);
|
|
178
|
+
ensureTsconfig(log);
|
|
179
|
+
const app = ensureAppIds(log, platforms);
|
|
180
|
+
fixConfigPlaceholders(log, app);
|
|
181
|
+
ensureScripts(log, platforms);
|
|
182
|
+
ensureRoot(log);
|
|
183
|
+
|
|
184
|
+
printSteps(ctx, steps);
|
|
185
|
+
ctx.out('');
|
|
186
|
+
if (dryRun.present) ctx.out('Dry run: nothing was changed. Run quiesco init --upgrade without --dry-run to make these changes.');
|
|
187
|
+
else ctx.out(`Upgraded to Quiesco ${ctx.version}${steps.some((s) => s.status === 'todo') ? '; the lines marked ! need you' : ''}. Check the setup with: npx quiesco doctor`);
|
|
188
|
+
return 0;
|
|
189
|
+
}
|
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();
|
package/src/packages.ts
ADDED
|
@@ -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
|
+
}
|