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.
Files changed (52) hide show
  1. package/dist/cli.d.ts +2 -1
  2. package/dist/cli.d.ts.map +1 -1
  3. package/dist/cli.js +3 -6
  4. package/dist/cli.js.map +1 -1
  5. package/dist/commands/doctor.d.ts +2 -1
  6. package/dist/commands/doctor.d.ts.map +1 -1
  7. package/dist/commands/doctor.js +220 -8
  8. package/dist/commands/doctor.js.map +1 -1
  9. package/dist/commands/init.d.ts +2 -10
  10. package/dist/commands/init.d.ts.map +1 -1
  11. package/dist/commands/init.js +58 -129
  12. package/dist/commands/init.js.map +1 -1
  13. package/dist/commands/test.js +1 -1
  14. package/dist/commands/test.js.map +1 -1
  15. package/dist/commands/ui.js +1 -1
  16. package/dist/commands/ui.js.map +1 -1
  17. package/dist/commands/upgrade.d.ts +8 -0
  18. package/dist/commands/upgrade.d.ts.map +1 -0
  19. package/dist/commands/upgrade.js +185 -0
  20. package/dist/commands/upgrade.js.map +1 -0
  21. package/dist/context.d.ts +2 -0
  22. package/dist/context.d.ts.map +1 -1
  23. package/dist/context.js +1 -0
  24. package/dist/context.js.map +1 -1
  25. package/dist/dev-server.d.ts +2 -0
  26. package/dist/dev-server.d.ts.map +1 -1
  27. package/dist/dev-server.js +4 -2
  28. package/dist/dev-server.js.map +1 -1
  29. package/dist/packages.d.ts +17 -0
  30. package/dist/packages.d.ts.map +1 -0
  31. package/dist/packages.js +40 -0
  32. package/dist/packages.js.map +1 -0
  33. package/dist/project.d.ts +23 -0
  34. package/dist/project.d.ts.map +1 -0
  35. package/dist/project.js +74 -0
  36. package/dist/project.js.map +1 -0
  37. package/dist/setup-steps.d.ts +95 -0
  38. package/dist/setup-steps.d.ts.map +1 -0
  39. package/dist/setup-steps.js +289 -0
  40. package/dist/setup-steps.js.map +1 -0
  41. package/package.json +2 -2
  42. package/src/cli.ts +3 -7
  43. package/src/commands/doctor.ts +226 -9
  44. package/src/commands/init.ts +59 -153
  45. package/src/commands/test.ts +1 -1
  46. package/src/commands/ui.ts +1 -1
  47. package/src/commands/upgrade.ts +189 -0
  48. package/src/context.ts +3 -0
  49. package/src/dev-server.ts +6 -2
  50. package/src/packages.ts +42 -0
  51. package/src/project.ts +76 -0
  52. package/src/setup-steps.ts +330 -0
@@ -0,0 +1,330 @@
1
+ /**
2
+ * The steps of `quiesco init` that `quiesco init --upgrade` repeats on an existing project: installing the
3
+ * Quiesco packages at this CLI's version, app IDs in app.json, tsconfig.json and the e2e scripts. Each step
4
+ * records what it did as an InitStep and, in a dry run, only says what it would do.
5
+ */
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+
9
+ import type { CliContext, CliPlatform } from './context.js';
10
+ import { installedVersion, isQuiescoPackage } from './packages.js';
11
+
12
+ export type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';
13
+
14
+ export interface PackageJson {
15
+ name?: string;
16
+ main?: string;
17
+ scripts?: Record<string, string>;
18
+ dependencies?: Record<string, string>;
19
+ devDependencies?: Record<string, string>;
20
+ overrides?: Record<string, string>;
21
+ resolutions?: Record<string, string>;
22
+ [key: string]: unknown;
23
+ }
24
+
25
+ export interface AppJson {
26
+ expo?: {
27
+ name?: string;
28
+ slug?: string;
29
+ scheme?: string | string[];
30
+ plugins?: unknown[];
31
+ ios?: { bundleIdentifier?: string; [key: string]: unknown };
32
+ android?: { package?: string; [key: string]: unknown };
33
+ [key: string]: unknown;
34
+ };
35
+ }
36
+
37
+ export interface InitStep {
38
+ status: 'created' | 'updated' | 'skipped' | 'ran' | 'todo';
39
+ what: string;
40
+ note?: string;
41
+ }
42
+
43
+ /** Where steps record what they did; `dryRun`: change nothing, only record what would change. */
44
+ export interface StepLog {
45
+ ctx: CliContext;
46
+ steps: InitStep[];
47
+ dryRun: boolean;
48
+ }
49
+
50
+ /** Installed into `dependencies`: the app bundles them (stubbed / excluded in production builds). */
51
+ export const RUNTIME = ['@quiesco/agent', '@quiesco/native'];
52
+ /** Installed into `devDependencies`. */
53
+ export const DEV = ['quiesco', '@quiesco/core', '@quiesco/cucumber', '@quiesco/expo-plugin', '@cucumber/cucumber'];
54
+ export const WEB_DEV = ['@quiesco/web', 'playwright'];
55
+ /** Internal packages pulled in by the ones above; only pinned when installing from tarballs. */
56
+ const TRANSITIVE = ['@quiesco/protocol'];
57
+
58
+ /** The app config files Quiesco cannot edit (JavaScript / TypeScript). */
59
+ export const DYNAMIC_APP_CONFIGS = ['app.config.js', 'app.config.ts', 'app.config.mjs', 'app.config.cjs'];
60
+
61
+ export function readJson<T>(ctx: CliContext, file: string): T | null {
62
+ const text = ctx.readFile(file);
63
+ if (text === null) return null;
64
+ try {
65
+ return JSON.parse(text) as T;
66
+ } catch {
67
+ return null;
68
+ }
69
+ }
70
+
71
+ export const writeJson = (ctx: CliContext, file: string, value: unknown): void => ctx.writeFile(file, `${JSON.stringify(value, null, 2)}\n`);
72
+
73
+ export function detectPackageManager(ctx: CliContext): PackageManager {
74
+ if (ctx.exists(path.join(ctx.cwd, 'pnpm-lock.yaml'))) return 'pnpm';
75
+ if (ctx.exists(path.join(ctx.cwd, 'yarn.lock'))) return 'yarn';
76
+ if (ctx.exists(path.join(ctx.cwd, 'bun.lock')) || ctx.exists(path.join(ctx.cwd, 'bun.lockb'))) return 'bun';
77
+ return 'npm';
78
+ }
79
+
80
+ /** `@quiesco/agent` → `quiesco-agent-<version>.tgz` (the file name `pnpm pack` / `npm pack` writes). */
81
+ export function findTarballs(dir: string, names: readonly string[], list: (d: string) => string[] = (d) => fs.readdirSync(d)): Map<string, string> {
82
+ const files = list(dir).filter((f) => f.endsWith('.tgz'));
83
+ const found = new Map<string, string>();
84
+ for (const name of names) {
85
+ const base = name.replace(/^@/, '').replace('/', '-');
86
+ const match = files.find((f) => new RegExp(`^${base.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}-\\d[^/]*\\.tgz$`).test(f));
87
+ if (match !== undefined) found.set(name, path.join(dir, match));
88
+ }
89
+ return found;
90
+ }
91
+
92
+ /** An `overrides:` block for pnpm-workspace.yaml (names and paths quoted: `@` starts no plain YAML scalar). */
93
+ function pnpmOverrides(pins: Record<string, string>): string {
94
+ return `overrides:\n${Object.entries(pins).map(([n, f]) => ` ${JSON.stringify(n)}: ${JSON.stringify(f)}\n`).join('')}`;
95
+ }
96
+
97
+ export function addCommand(pm: PackageManager, dev: boolean, specs: string[]): { command: string; args: string[] } {
98
+ switch (pm) {
99
+ case 'pnpm':
100
+ return { command: 'pnpm', args: ['add', ...(dev ? ['-D'] : []), ...specs] };
101
+ case 'yarn':
102
+ return { command: 'yarn', args: ['add', ...(dev ? ['-D'] : []), ...specs] };
103
+ case 'bun':
104
+ return { command: 'bun', args: ['add', ...(dev ? ['-d'] : []), ...specs] };
105
+ case 'npm':
106
+ return { command: 'npm', args: ['install', ...(dev ? ['--save-dev'] : []), ...specs] };
107
+ }
108
+ }
109
+
110
+ export interface InstallOptions {
111
+ pm: PackageManager;
112
+ runtime: readonly string[];
113
+ dev: readonly string[];
114
+ /** `--packages <dir>`: install from the tarballs in it. */
115
+ packagesDir?: string;
116
+ skipInstall: boolean;
117
+ }
118
+
119
+ /**
120
+ * Install `runtime` / `dev` with each Quiesco package at this CLI's version (issue #17: not whatever the
121
+ * package manager's cached registry metadata calls latest), then read the installed versions back.
122
+ * Returns false (after printing why) when it failed; the command should stop then.
123
+ */
124
+ export async function installPackages(log: StepLog, o: InstallOptions): Promise<boolean> {
125
+ const { ctx, steps } = log;
126
+ let spec = (name: string): string => (isQuiescoPackage(name) ? `${name}@${ctx.version}` : name);
127
+ /** The version each Quiesco package must have after the install. */
128
+ let expected = (_name: string): string => ctx.version;
129
+ if (o.packagesDir !== undefined) {
130
+ const dir = path.resolve(ctx.cwd, o.packagesDir);
131
+ const ours = [...o.runtime, ...o.dev, ...TRANSITIVE].filter(isQuiescoPackage);
132
+ const tarballs = findTarballs(dir, ours);
133
+ const missing = ours.filter((n) => !tarballs.has(n));
134
+ if (missing.length > 0) {
135
+ ctx.err(`quiesco init: no tarball for ${missing.join(', ')} in ${dir}`);
136
+ return false;
137
+ }
138
+ spec = (name) => (tarballs.has(name) ? `file:${tarballs.get(name) as string}` : name);
139
+ expected = (name) => /-(\d[^/]*)\.tgz$/.exec(tarballs.get(name) ?? '')?.[1] ?? ctx.version;
140
+ // Their own dependencies on each other ("@quiesco/protocol": "0.0.0") must resolve to the tarballs too.
141
+ // npm refuses an override for a package that is also a direct dependency (EOVERRIDE) and reuses the
142
+ // directly installed tarballs for those ranges anyway: pin only the indirect ones there. pnpm and
143
+ // yarn resolve every dependency on its own, so they need all of them pinned.
144
+ const direct = new Set([...o.runtime, ...o.dev]);
145
+ const pins = Object.fromEntries([...tarballs].filter(([n]) => o.pm !== 'npm' || !direct.has(n)).map(([n, f]) => [n, `file:${f}`]));
146
+ const pinned = `installing from the tarballs in ${o.packagesDir} (${Object.keys(pins).length} indirect ${Object.keys(pins).length === 1 ? 'dependency' : 'dependencies'} pinned)`;
147
+ if (o.pm === 'pnpm') {
148
+ // pnpm 10+ reads overrides from pnpm-workspace.yaml only; the "pnpm" field of package.json is ignored.
149
+ const yamlFile = path.join(ctx.cwd, 'pnpm-workspace.yaml');
150
+ const yaml = ctx.readFile(yamlFile) ?? '';
151
+ if (/^overrides:/m.test(yaml)) {
152
+ ctx.err(`quiesco init: pnpm-workspace.yaml already has overrides; add these and run quiesco init again:\n${pnpmOverrides(pins)}`);
153
+ return false;
154
+ }
155
+ if (!log.dryRun) ctx.writeFile(yamlFile, `${yaml}${yaml === '' || yaml.endsWith('\n') ? '' : '\n'}${pnpmOverrides(pins)}`);
156
+ steps.push({ status: 'updated', what: 'pnpm-workspace.yaml', note: pinned });
157
+ } else {
158
+ const pkgFile = path.join(ctx.cwd, 'package.json');
159
+ const current = readJson<PackageJson>(ctx, pkgFile) as PackageJson;
160
+ if (o.pm === 'yarn') current.resolutions = { ...current.resolutions, ...pins };
161
+ else current.overrides = { ...current.overrides, ...pins };
162
+ if (!log.dryRun) writeJson(ctx, pkgFile, current);
163
+ steps.push({ status: 'updated', what: 'package.json', note: pinned });
164
+ }
165
+ }
166
+ /** One command per dependency group that has packages (an upgrade may have no runtime ones to change). */
167
+ const commands = (names: (list: readonly string[]) => readonly string[]): { command: string; args: string[] }[] =>
168
+ ([[false, o.runtime], [true, o.dev]] as const).filter(([, list]) => names(list).length > 0).map(([dev, list]) => addCommand(o.pm, dev, names(list).map(spec)));
169
+ const installs = commands((list) => list);
170
+ for (const cmd of installs) {
171
+ const line = `${cmd.command} ${cmd.args.join(' ')}`;
172
+ if (o.skipInstall || log.dryRun) {
173
+ steps.push({ status: 'todo', what: 'install', note: line });
174
+ continue;
175
+ }
176
+ ctx.out(`$ ${line}`);
177
+ const r = await ctx.exec(cmd.command, cmd.args, { cwd: ctx.cwd });
178
+ if (r.code !== 0) {
179
+ ctx.err(r.stderr.trim() || r.stdout.trim());
180
+ ctx.err(`quiesco init: \`${line}\` failed (exit ${r.code}).`);
181
+ return false;
182
+ }
183
+ steps.push({ status: 'ran', what: 'install', note: line });
184
+ }
185
+ if (o.skipInstall || log.dryRun) return true;
186
+ const ours = [...o.runtime, ...o.dev].filter(isQuiescoPackage);
187
+ const wrong = ours.map((name) => ({ name, want: expected(name), got: installedVersion(ctx, name) })).filter((p) => p.got !== p.want);
188
+ if (wrong.length > 0) {
189
+ ctx.err(`quiesco init: the installed Quiesco packages are not the version that was asked for:`);
190
+ for (const p of wrong) ctx.err(` ${p.name}: ${p.got ?? 'not found in node_modules'} (wanted ${p.want})`);
191
+ ctx.err('All Quiesco packages must have the same version as the CLI that writes the project files. The');
192
+ ctx.err("package manager may have used stale registry metadata from its cache, or held a new release back");
193
+ ctx.err('(pnpm minimumReleaseAge). Install them again with the version given:');
194
+ for (const cmd of commands((list) => list.filter(isQuiescoPackage))) ctx.err(` ${cmd.command} ${cmd.args.join(' ')}`);
195
+ ctx.err('then run quiesco init again.');
196
+ return false;
197
+ }
198
+ steps.push({ status: 'ran', what: 'versions', note: `${ours.length} Quiesco packages at ${[...new Set(ours.map(expected))].join(', ')}` });
199
+ return true;
200
+ }
201
+
202
+ // ---- app IDs (issue #34) ----
203
+
204
+ /**
205
+ * IDs for an app.json that has none: `com.anonymous.<slug>` (letters and digits, as Expo's prebuild derives
206
+ * the Android package; for iOS it keeps hyphens, so the two would differ) and the slug as URL scheme.
207
+ */
208
+ export function defaultAppIds(app: AppJson, fallbackName: string | undefined): { id: string; scheme: string } {
209
+ const base = (app.expo?.slug ?? app.expo?.name ?? fallbackName ?? 'app').toLowerCase();
210
+ let idPart = base.replace(/[^a-z0-9]/g, '');
211
+ if (!/^[a-z]/.test(idPart)) idPart = `app${idPart}`;
212
+ let scheme = base.replace(/[^a-z0-9+.-]/g, '');
213
+ if (!/^[a-z]/.test(scheme)) scheme = `app${scheme}`;
214
+ return { id: `com.anonymous.${idPart}`, scheme };
215
+ }
216
+
217
+ export function firstScheme(app: AppJson): string | undefined {
218
+ const s = app.expo?.scheme;
219
+ return Array.isArray(s) ? s[0] : s;
220
+ }
221
+
222
+ /** The app config is JavaScript / TypeScript: Quiesco cannot read or change it. */
223
+ export function dynamicAppConfig(ctx: CliContext): string | undefined {
224
+ return DYNAMIC_APP_CONFIGS.find((f) => ctx.exists(path.join(ctx.cwd, f)));
225
+ }
226
+
227
+ /**
228
+ * Write the IDs the platforms need into app.json when it has none (issue #34): `ios.bundleIdentifier` for
229
+ * iOS, `android.package` and `scheme` (the dev client's deep link) for Android. Without them the build uses
230
+ * Expo's defaults, which differ per platform and are not what quiesco.config names. Returns app.json as
231
+ * it is now.
232
+ */
233
+ export function ensureAppIds(log: StepLog, platforms: readonly CliPlatform[]): AppJson {
234
+ const { ctx, steps } = log;
235
+ const appFile = path.join(ctx.cwd, 'app.json');
236
+ const app = readJson<AppJson>(ctx, appFile) ?? {};
237
+ const expo = app.expo;
238
+ if (expo === undefined || !platforms.some((p) => p !== 'web')) return app;
239
+ const dynamic = dynamicAppConfig(ctx);
240
+ const missing: string[] = [];
241
+ if (platforms.includes('ios') && expo.ios?.bundleIdentifier === undefined) missing.push('ios.bundleIdentifier');
242
+ if (platforms.includes('android') && expo.android?.package === undefined) missing.push('android.package');
243
+ if (platforms.includes('android') && firstScheme(app) === undefined) missing.push('scheme');
244
+ if (missing.length === 0) {
245
+ steps.push({ status: 'skipped', what: 'app IDs', note: 'app.json has them' });
246
+ return app;
247
+ }
248
+ if (dynamic !== undefined) {
249
+ steps.push({ status: 'todo', what: 'app IDs', note: `set expo.${missing.join(', expo.')} in ${dynamic} and use the same values in quiesco.config` });
250
+ return app;
251
+ }
252
+ const { id, scheme } = defaultAppIds(app, readJson<PackageJson>(ctx, path.join(ctx.cwd, 'package.json'))?.name);
253
+ const set: string[] = [];
254
+ if (missing.includes('ios.bundleIdentifier')) {
255
+ expo.ios = { ...expo.ios, bundleIdentifier: id };
256
+ set.push(`ios.bundleIdentifier "${id}"`);
257
+ }
258
+ if (missing.includes('android.package')) {
259
+ expo.android = { ...expo.android, package: id };
260
+ set.push(`android.package "${id}"`);
261
+ }
262
+ if (missing.includes('scheme')) {
263
+ expo.scheme = scheme;
264
+ set.push(`scheme "${scheme}"`);
265
+ }
266
+ if (!log.dryRun) writeJson(ctx, appFile, app);
267
+ steps.push({ status: 'updated', what: 'app.json', note: `set ${set.join(', ')}: the build and quiesco.config must name the same app (change them here and in quiesco.config if you like)` });
268
+ return app;
269
+ }
270
+
271
+ // ---- tsconfig.json (issue #21) ----
272
+
273
+ /** Step files import each other with .ts (Node's type stripping needs it): let tsc accept that. */
274
+ export function ensureTsconfig(log: StepLog): void {
275
+ const { ctx, steps } = log;
276
+ const tsconfigFile = path.join(ctx.cwd, 'tsconfig.json');
277
+ const tsconfigText = ctx.readFile(tsconfigFile);
278
+ if (tsconfigText === null) return;
279
+ let tsconfig: { compilerOptions?: Record<string, unknown> } | null;
280
+ try {
281
+ tsconfig = JSON.parse(tsconfigText) as { compilerOptions?: Record<string, unknown> };
282
+ } catch {
283
+ tsconfig = null; // comments or trailing commas: leave the file to the user
284
+ }
285
+ if (tsconfig?.compilerOptions?.['allowImportingTsExtensions'] === true || /"allowImportingTsExtensions"\s*:\s*true/.test(tsconfigText)) {
286
+ steps.push({ status: 'skipped', what: 'tsconfig.json', note: 'already allows .ts imports' });
287
+ } else if (tsconfig === null || typeof tsconfig !== 'object' || Array.isArray(tsconfig)) {
288
+ steps.push({ status: 'todo', what: 'tsconfig.json', note: 'add "allowImportingTsExtensions": true to compilerOptions (step files import each other with .ts)' });
289
+ } else {
290
+ tsconfig.compilerOptions = { ...tsconfig.compilerOptions, allowImportingTsExtensions: true };
291
+ if (!log.dryRun) writeJson(ctx, tsconfigFile, tsconfig);
292
+ steps.push({ status: 'updated', what: 'tsconfig.json', note: 'allowImportingTsExtensions: step files import each other with .ts' });
293
+ }
294
+ }
295
+
296
+ // ---- scripts ----
297
+
298
+ export function e2eScripts(platforms: readonly CliPlatform[]): Record<string, string> {
299
+ return {
300
+ 'e2e:start': 'EXPO_PUBLIC_QUIESCO=1 expo start',
301
+ ...(platforms.includes('web') ? { 'e2e:web': 'EXPO_PUBLIC_QUIESCO=1 expo export --platform web && quiesco test --platform web' } : {}),
302
+ ...(platforms.includes('android') ? { 'e2e:build:android': 'quiesco build android', 'e2e:android': 'quiesco test --platform android' } : {}),
303
+ ...(platforms.includes('ios') ? { 'e2e:build:ios': 'quiesco build ios', 'e2e:ios': 'quiesco test --platform ios' } : {}),
304
+ };
305
+ }
306
+
307
+ /** Add the e2e scripts that are missing; existing scripts of the same name are left alone. */
308
+ export function ensureScripts(log: StepLog, platforms: readonly CliPlatform[]): void {
309
+ const { ctx, steps } = log;
310
+ const pkgFile = path.join(ctx.cwd, 'package.json');
311
+ const pkg = readJson<PackageJson>(ctx, pkgFile) as PackageJson;
312
+ const scripts = { ...(pkg.scripts ?? {}) };
313
+ const wanted = e2eScripts(platforms);
314
+ const added = Object.keys(wanted).filter((k) => scripts[k] === undefined);
315
+ if (added.length === 0) {
316
+ steps.push({ status: 'skipped', what: 'scripts', note: 'the e2e scripts exist' });
317
+ return;
318
+ }
319
+ for (const k of added) scripts[k] = wanted[k] as string;
320
+ pkg.scripts = scripts;
321
+ if (!log.dryRun) writeJson(ctx, pkgFile, pkg);
322
+ steps.push({ status: 'updated', what: 'package.json', note: `scripts: ${added.join(', ')}` });
323
+ }
324
+
325
+ const ICON = { created: '+', updated: '~', skipped: '=', ran: '$', todo: '!' } as const;
326
+
327
+ export function printSteps(ctx: CliContext, steps: readonly InitStep[]): void {
328
+ ctx.out('');
329
+ for (const s of steps) ctx.out(`${ICON[s.status]} ${s.what}${s.note !== undefined ? ` — ${s.note}` : ''}`);
330
+ }