@sixbell-telco/sdk-tools 0.0.0 → 0.1.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.
Files changed (58) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +277 -2
  3. package/data/security-floors.json +47 -0
  4. package/package.json +35 -4
  5. package/recipes/README.md +53 -0
  6. package/recipes/crud-list.md +21 -0
  7. package/recipes/custom-component.md +35 -0
  8. package/recipes/detail-page.md +19 -0
  9. package/recipes/form-dialog.md +17 -0
  10. package/recipes/parts/crud-list/i18n.json +83 -0
  11. package/recipes/parts/crud-list/src/app/features/__name__/__name__.routes.ts.tpl +30 -0
  12. package/recipes/parts/crud-list/src/app/features/__name__/pages/__name__-list/__name__-list.component.html.tpl +102 -0
  13. package/recipes/parts/crud-list/src/app/features/__name__/pages/__name__-list/__name__-list.component.spec.ts.tpl +101 -0
  14. package/recipes/parts/crud-list/src/app/features/__name__/pages/__name__-list/__name__-list.component.ts.tpl +143 -0
  15. package/recipes/parts/detail-page/i18n.json +32 -0
  16. package/recipes/parts/detail-page/src/app/features/__name__/pages/__name__-detail/__name__-detail.component.html.tpl +35 -0
  17. package/recipes/parts/detail-page/src/app/features/__name__/pages/__name__-detail/__name__-detail.component.spec.ts.tpl +58 -0
  18. package/recipes/parts/detail-page/src/app/features/__name__/pages/__name__-detail/__name__-detail.component.ts.tpl +68 -0
  19. package/recipes/parts/entity/i18n.json +5 -0
  20. package/recipes/parts/entity/src/app/features/__name__/__name__.model.ts.tpl +9 -0
  21. package/recipes/parts/entity/src/app/features/__name__/__name__.service.spec.ts.tpl +29 -0
  22. package/recipes/parts/entity/src/app/features/__name__/__name__.service.ts.tpl +33 -0
  23. package/recipes/parts/form-dialog/i18n.json +35 -0
  24. package/recipes/parts/form-dialog/src/app/features/__name__/components/__name__-form-dialog/__name__-form-dialog.component.html.tpl +33 -0
  25. package/recipes/parts/form-dialog/src/app/features/__name__/components/__name__-form-dialog/__name__-form-dialog.component.spec.ts.tpl +69 -0
  26. package/recipes/parts/form-dialog/src/app/features/__name__/components/__name__-form-dialog/__name__-form-dialog.component.ts.tpl +73 -0
  27. package/src/add/add.mjs +251 -0
  28. package/src/check/config.mjs +112 -0
  29. package/src/check/exceptions.mjs +103 -0
  30. package/src/check/federation.mjs +224 -0
  31. package/src/check/finding.mjs +23 -0
  32. package/src/check/harness.mjs +146 -0
  33. package/src/check/i18n.mjs +218 -0
  34. package/src/check/integration.mjs +566 -0
  35. package/src/check/security.mjs +165 -0
  36. package/src/check/steps.mjs +37 -0
  37. package/src/check/styles.mjs +347 -0
  38. package/src/check/wiring.mjs +198 -0
  39. package/src/check.mjs +333 -0
  40. package/src/cli.mjs +551 -0
  41. package/src/docs/docs.mjs +154 -0
  42. package/src/doctor/doctor.mjs +492 -0
  43. package/src/format.mjs +102 -0
  44. package/src/info/info.mjs +149 -0
  45. package/src/init/init.mjs +490 -0
  46. package/src/init/merge.mjs +191 -0
  47. package/src/init/template.mjs +292 -0
  48. package/src/mcp/catalog.mjs +248 -0
  49. package/src/mcp/glossary.mjs +75 -0
  50. package/src/mcp/manifest.mjs +53 -0
  51. package/src/mcp/recipes.mjs +198 -0
  52. package/src/mcp/server.mjs +249 -0
  53. package/src/mcp/upgrade-guide.mjs +116 -0
  54. package/src/mcp/usage.mjs +48 -0
  55. package/src/project/project.mjs +220 -0
  56. package/src/types.d.ts +448 -0
  57. package/src/upgrade/lockstep.mjs +153 -0
  58. package/src/upgrade/upgrade.mjs +623 -0
@@ -0,0 +1,623 @@
1
+ /**
2
+ * `sdk-tools upgrade`: moves an app to a newer @sixbell-telco/sdk through the SDK's own `ng update`
3
+ * migrations, with pre-checks before and `check` after, and one report.
4
+ *
5
+ * 1. Pre-checks (exit 3 when one blocks): the app uses the SDK, a clean git tree, the target exists
6
+ * and is not older, Angular stays on 19.2, the installed peers meet the target's floors, and in a
7
+ * host every remote found locally is on the target (federation lockstep, see lockstep.mjs).
8
+ * 2. Plan: the migrations between the installed and the target version run in dry-run mode against
9
+ * the target package; the planned edits and manual items are the inventory.
10
+ * 3. Apply (not with --dry-run): install the target, run the same migrations from the installed
11
+ * package, format the files they changed with the app's own Prettier (when the app has it), then
12
+ * `check`. The report lists what was applied, what is manual and what still fails.
13
+ */
14
+ import { execFileSync, spawnSync } from 'node:child_process';
15
+ import { createHash } from 'node:crypto';
16
+ import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
17
+ import { createRequire } from 'node:module';
18
+ import { isAbsolute, join, relative, resolve } from 'node:path';
19
+ import { styleText } from 'node:util';
20
+ import { lockstep } from './lockstep.mjs';
21
+
22
+ /**
23
+ * @typedef {import('../types.js').UpgradeOptions} UpgradeOptions
24
+ * @typedef {import('../types.js').UpgradeReport} UpgradeReport
25
+ * @typedef {import('../types.js').UpgradeItem} UpgradeItem
26
+ * @typedef {import('../types.js').Precheck} Precheck
27
+ * @typedef {{ version: string, dir: string, spec: string, source: 'registry' | 'tarball' }} Target
28
+ */
29
+
30
+ const SDK = '@sixbell-telco/sdk';
31
+ const FOUNDATION_CONFIG = 'mfe-foundation.config.json';
32
+ const ANGULAR = { major: 19, minor: 2 };
33
+
34
+ /** @param {string} value @returns {[number, number, number] | null} */
35
+ function parseVersion(value) {
36
+ const match = /(\d+)\.(\d+)\.(\d+)/.exec(value ?? '');
37
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
38
+ }
39
+
40
+ /** Negative, zero or positive, like a sort comparator. Unparseable versions sort first. */
41
+ export function compareVersions(/** @type {string} */ a, /** @type {string} */ b) {
42
+ const x = parseVersion(a) ?? [-1, 0, 0];
43
+ const y = parseVersion(b) ?? [-1, 0, 0];
44
+ return x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
45
+ }
46
+
47
+ /** @param {string} file */
48
+ function readJson(file) {
49
+ try {
50
+ return JSON.parse(readFileSync(file, 'utf8'));
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+
56
+ /**
57
+ * The version of `name` the app resolves: package-lock, then node_modules, then the package.json range.
58
+ * @param {string} cwd
59
+ * @param {string} name
60
+ * @returns {string | null}
61
+ */
62
+ function installedVersion(cwd, name) {
63
+ const lock = readJson(join(cwd, 'package-lock.json'));
64
+ const locked = lock?.packages?.[`node_modules/${name}`]?.version;
65
+ if (locked) return locked;
66
+ const installed = readJson(join(cwd, 'node_modules', name, 'package.json'))?.version;
67
+ if (installed) return installed;
68
+ const pkg = readJson(join(cwd, 'package.json'));
69
+ const range = pkg?.dependencies?.[name] ?? pkg?.devDependencies?.[name];
70
+ return /(\d+\.\d+\.\d+)/.exec(range ?? '')?.[1] ?? null;
71
+ }
72
+
73
+ /**
74
+ * @param {string} command
75
+ * @param {string[]} args
76
+ * @param {string} cwd
77
+ */
78
+ const run = (command, args, cwd) => execFileSync(command, args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
79
+
80
+ /** npm and Prettier can print far more than execFileSync's 1 MB default before they exit. */
81
+ const OUTPUT_LIMIT = 256 * 1024 * 1024;
82
+
83
+ /**
84
+ * `npm install` of the target. Only npm's exit status decides: npm prints peer conflicts it resolved
85
+ * (`npm warn ERESOLVE overriding peer dependency`) on stderr and still exits 0, and that output alone
86
+ * can pass execFileSync's buffer limit, which kills npm and reported a good install as failed.
87
+ * @param {string} spec
88
+ * @param {string} cwd
89
+ * @returns {{ ok: true, eresolve: number } | { ok: false, message: string }}
90
+ */
91
+ function npmInstall(spec, cwd) {
92
+ const result = spawnSync('npm', ['install', '--save-exact', '--no-audit', '--no-fund', spec], {
93
+ cwd,
94
+ encoding: 'utf8',
95
+ stdio: ['ignore', 'pipe', 'pipe'],
96
+ maxBuffer: OUTPUT_LIMIT,
97
+ });
98
+ const stderr = result.stderr ?? '';
99
+ if (result.error) return { ok: false, message: `npm could not run: ${result.error.message}` };
100
+ if (result.status !== 0) {
101
+ const lines = stderr.split('\n').filter((line) => line.trim());
102
+ const message = lines.find((line) => /^npm (error|ERR!)/.test(line) && !/^npm (error|ERR!)\s*$/.test(line)) ?? lines[0];
103
+ return { ok: false, message: message ?? `npm install exited with ${result.status ?? result.signal}` };
104
+ }
105
+ return { ok: true, eresolve: stderr.split('\n').filter((line) => /^npm warn ERESOLVE/.test(line)).length };
106
+ }
107
+
108
+ /**
109
+ * Formats `files` with the app's own Prettier (node_modules/.bin/prettier), so the upgrade diff follows
110
+ * the app's style. Never a Prettier of its own: an app without one is left as the migrations wrote it.
111
+ * @param {string} cwd
112
+ * @param {string[]} files app-relative paths the upgrade changed
113
+ * @returns {import('../types.js').UpgradeFormat}
114
+ */
115
+ function formatChanged(cwd, files) {
116
+ const bin = join(cwd, 'node_modules', '.bin', process.platform === 'win32' ? 'prettier.cmd' : 'prettier');
117
+ const present = files.filter((file) => existsSync(join(cwd, file)));
118
+ if (!present.length) return { tool: 'prettier', status: 'skipped', files: [], reason: 'the upgrade changed no files' };
119
+ if (!existsSync(bin)) return { tool: 'prettier', status: 'skipped', files: [], reason: 'the app has no node_modules/.bin/prettier' };
120
+ const result = spawnSync(bin, ['--write', '--ignore-unknown', '--', ...present], {
121
+ cwd,
122
+ encoding: 'utf8',
123
+ stdio: ['ignore', 'pipe', 'pipe'],
124
+ maxBuffer: OUTPUT_LIMIT,
125
+ shell: process.platform === 'win32',
126
+ });
127
+ if (result.error || result.status !== 0) {
128
+ const reason = result.error?.message ?? (result.stderr ?? '').split('\n').find((line) => line.trim()) ?? `exit ${result.status}`;
129
+ return { tool: 'prettier', status: 'failed', files: present, reason };
130
+ }
131
+ return { tool: 'prettier', status: 'formatted', files: present };
132
+ }
133
+
134
+ /**
135
+ * Downloads (registry) or takes (tarball) the target package and unpacks it under the app's
136
+ * node_modules/.cache, so its migrations resolve @angular/compiler and the devkit from the app.
137
+ * @param {string} cwd
138
+ * @param {string | undefined} to a version, a dist-tag or a path to a packed .tgz
139
+ * @returns {Target | { error: string }}
140
+ */
141
+ function fetchTarget(cwd, to) {
142
+ const cache = join(cwd, 'node_modules', '.cache', 'sdk-tools', 'upgrade');
143
+ mkdirSync(cache, { recursive: true });
144
+ let tarball;
145
+ let spec;
146
+ /** @type {'registry' | 'tarball'} */
147
+ let source = 'registry';
148
+ if (to && /\.(tgz|tar\.gz)$/.test(to)) {
149
+ tarball = isAbsolute(to) ? to : resolve(cwd, to);
150
+ if (!existsSync(tarball)) return { error: `no tarball at ${to}` };
151
+ spec = tarball;
152
+ source = 'tarball';
153
+ } else {
154
+ spec = `${SDK}@${to ?? 'latest'}`;
155
+ try {
156
+ const version = JSON.parse(run('npm', ['view', spec, 'version', '--json'], cwd) || 'null');
157
+ const resolved = Array.isArray(version) ? version.at(-1) : version;
158
+ if (!resolved) return { error: `${spec} is not published` };
159
+ spec = `${SDK}@${resolved}`;
160
+ const packed = JSON.parse(run('npm', ['pack', spec, '--json', '--pack-destination', cache], cwd));
161
+ tarball = join(cache, packed[0].filename);
162
+ } catch (error) {
163
+ return { error: `${spec} could not be fetched from the registry: ${firstLine(error)}` };
164
+ }
165
+ }
166
+ const dir = join(cache, createHash('sha256').update(readFileSync(tarball)).digest('hex').slice(0, 16));
167
+ rmSync(dir, { recursive: true, force: true });
168
+ mkdirSync(dir, { recursive: true });
169
+ run('tar', ['-xzf', tarball, '-C', dir], cwd);
170
+ const pkg = readJson(join(dir, 'package', 'package.json'));
171
+ if (pkg?.name !== SDK) return { error: `${to} is not a ${SDK} package` };
172
+ return { version: pkg.version, dir: join(dir, 'package'), spec: source === 'registry' ? `${SDK}@${pkg.version}` : spec, source };
173
+ }
174
+
175
+ /**
176
+ * The ignore rule (`source:line:pattern`) that makes git ignore `file`, or null when git does not
177
+ * ignore it (a tracked file is never ignored).
178
+ * @param {string} cwd
179
+ * @param {string} file
180
+ */
181
+ function ignoredBy(cwd, file) {
182
+ try {
183
+ const out = run('git', ['check-ignore', '-v', file], cwd).trim();
184
+ return out ? out.split('\t')[0] : null;
185
+ } catch {
186
+ return null;
187
+ }
188
+ }
189
+
190
+ /** @param {unknown} error */
191
+ function firstLine(error) {
192
+ const stderr = /** @type {{ stderr?: string }} */ (error)?.stderr;
193
+ const text = stderr || (error instanceof Error ? error.message : String(error));
194
+ return text.split('\n').find((line) => line.trim()) ?? text;
195
+ }
196
+
197
+ /** @param {string} file */
198
+ function readText(file) {
199
+ try {
200
+ return readFileSync(file, 'utf8');
201
+ } catch {
202
+ return null;
203
+ }
204
+ }
205
+
206
+ /**
207
+ * The unblock for peers below the target's floors: the package.json edits (direct dependencies and
208
+ * overrides that pin the low version; `npm install x@v` fails with EOVERRIDE while an override pins
209
+ * x elsewhere), then the npm install that succeeds after them.
210
+ * @param {Record<string, any>} pkg the app's package.json
211
+ * @param {{ name: string, floor: string | null, installed: string | null }[]} low
212
+ */
213
+ function peerFloorUnblock(pkg, low) {
214
+ /** @type {string[]} */
215
+ const edits = [];
216
+ /** @type {string[]} */
217
+ const transitive = [];
218
+ for (const peer of low) {
219
+ const floor = /** @type {string} */ (peer.floor);
220
+ let edited = false;
221
+ for (const section of ['dependencies', 'devDependencies']) {
222
+ const range = pkg[section]?.[peer.name];
223
+ if (typeof range !== 'string') continue;
224
+ const prefix = /^[~^]/.exec(range)?.[0] ?? '';
225
+ edits.push(`${section}.${peer.name} ${JSON.stringify(range)} -> ${JSON.stringify(`${prefix}${floor}`)}`);
226
+ edited = true;
227
+ }
228
+ const override = pkg.overrides?.[peer.name];
229
+ if (typeof override === 'string' && !override.startsWith('$') && override !== floor) {
230
+ edits.push(`overrides.${peer.name} ${JSON.stringify(override)} -> ${JSON.stringify(floor)}`);
231
+ edited = true;
232
+ }
233
+ if (!edited) transitive.push(`${peer.name}@${floor}`);
234
+ }
235
+ if (!edits.length) return `npm install ${transitive.join(' ')}`;
236
+ const install = transitive.length ? `npm install ${transitive.join(' ')}` : 'npm install';
237
+ return `in package.json set ${edits.join(', ')}, then run ${install} (it updates package-lock.json), commit both files and run sdk-tools upgrade again`;
238
+ }
239
+
240
+ /** The lowest version a peer range allows (`~19.2.25` -> 19.2.25). @param {string} range */
241
+ const floorOf = (range) => /(\d+\.\d+\.\d+)/.exec(range)?.[1] ?? null;
242
+
243
+ /**
244
+ * The migrations of `pkgDir` that `ng update` runs from `from` to `to`: from < version <= to.
245
+ * @param {string} pkgDir
246
+ * @param {string} from
247
+ * @param {string} to
248
+ */
249
+ export function selectMigrations(pkgDir, from, to) {
250
+ const pkg = readJson(join(pkgDir, 'package.json'));
251
+ const collectionPath = pkg?.['ng-update']?.migrations;
252
+ if (typeof collectionPath !== 'string') return { collection: null, migrations: [] };
253
+ const collection = join(pkgDir, collectionPath);
254
+ const schematics = readJson(collection)?.schematics ?? {};
255
+ const migrations = Object.entries(schematics)
256
+ .map(([name, entry]) => ({ name, version: String(entry.version ?? ''), description: String(entry.description ?? '') }))
257
+ .filter((m) => parseVersion(m.version) && compareVersions(m.version, from) > 0 && compareVersions(m.version, to) <= 0)
258
+ .sort((a, b) => compareVersions(a.version, b.version));
259
+ return { collection, migrations };
260
+ }
261
+
262
+ /**
263
+ * Runs migrations with the Angular devkit's NodeWorkflow (the engine behind `ng update`), resolved
264
+ * from the app. Returns the report items the migrations logged, the files they touched and errors.
265
+ * @param {string} cwd
266
+ * @param {string} collection
267
+ * @param {{ name: string }[]} migrations
268
+ * @param {boolean} dryRun
269
+ * @param {string | null} from the installed version
270
+ */
271
+ async function runMigrations(cwd, collection, migrations, dryRun, from) {
272
+ let require;
273
+ try {
274
+ require = createRequire(join(cwd, 'package.json'));
275
+ require.resolve('@angular-devkit/schematics/tools');
276
+ } catch {
277
+ require = createRequire(import.meta.url);
278
+ }
279
+ // Untyped on purpose: the devkit comes from the app, and its core must be the one schematics uses.
280
+ /** @type {any} */
281
+ const { NodeWorkflow } = require('@angular-devkit/schematics/tools');
282
+ /** @type {any} */
283
+ const { logging } = createRequire(require.resolve('@angular-devkit/schematics'))('@angular-devkit/core');
284
+ /** @type {UpgradeItem[]} */
285
+ const items = [];
286
+ /** @type {Map<string, string>} */
287
+ const files = new Map();
288
+ /** @type {string[]} */
289
+ const errors = [];
290
+ for (const migration of migrations) {
291
+ const workflow = new NodeWorkflow(cwd, { dryRun, force: false, resolvePaths: [cwd], schemaValidation: true, packageManager: 'npm' });
292
+ workflow.reporter.subscribe((/** @type {{ kind: string, path: string, description?: string }} */ event) => {
293
+ if (event.kind === 'error') errors.push(`${event.path.replace(/^\//, '')}: ${event.description ?? 'error'}`);
294
+ else files.set(event.path.replace(/^\//, ''), event.kind);
295
+ });
296
+ const logger = new logging.Logger('sdk-upgrade');
297
+ logger.subscribe((/** @type {{ sdkUpgrade?: UpgradeItem }} */ entry) => {
298
+ // A step no migration applies (manual-steps.json) carries its version: drop the ones the app passed.
299
+ if (entry.sdkUpgrade && !(entry.sdkUpgrade.since && from && compareVersions(entry.sdkUpgrade.since, from) <= 0)) items.push(entry.sdkUpgrade);
300
+ });
301
+ try {
302
+ await new Promise((/** @type {(value?: unknown) => void} */ done, fail) =>
303
+ workflow
304
+ .execute({ collection, schematic: migration.name, options: {}, allowPrivate: true, logger })
305
+ .subscribe({ error: fail, complete: done }),
306
+ );
307
+ } catch (error) {
308
+ errors.push(`${migration.name}: ${error instanceof Error ? error.message : String(error)}`);
309
+ }
310
+ }
311
+ const isStep = (/** @type {UpgradeItem} */ i) => i.rule.startsWith('manual-step:');
312
+ return {
313
+ applied: items.filter((i) => i.kind === 'applied'),
314
+ manual: items.filter((i) => i.kind === 'manual' && !isStep(i)),
315
+ steps: items.filter(isStep),
316
+ files: [...files].map(([path, action]) => ({ path, action })).sort((a, b) => a.path.localeCompare(b.path)),
317
+ errors,
318
+ };
319
+ }
320
+
321
+ /**
322
+ * @param {UpgradeOptions} options
323
+ * @returns {Promise<{ code: 0 | 1 | 3, data: UpgradeReport }>}
324
+ */
325
+ export async function upgrade({ cwd = process.cwd(), to, dryRun = false, check: runCheck = true, roots = [], install, onProgress = () => {} }) {
326
+ /** @type {UpgradeReport} */
327
+ const report = {
328
+ dryRun,
329
+ from: installedVersion(cwd, SDK),
330
+ to: null,
331
+ source: null,
332
+ prechecks: [],
333
+ migrations: [],
334
+ planned: { applied: [], manual: [], files: [] },
335
+ applied: [],
336
+ manual: [],
337
+ steps: [],
338
+ failing: [],
339
+ files: [],
340
+ warnings: [],
341
+ format: null,
342
+ };
343
+ /** @param {Precheck} precheck */
344
+ const precheck = (precheck) => report.prechecks.push(precheck);
345
+ const blocked = () => ({ code: /** @type {3} */ (3), data: report });
346
+
347
+ onProgress('pre-checks');
348
+ if (!existsSync(join(cwd, 'package.json')) || !report.from) {
349
+ precheck({
350
+ id: 'sdk-installed',
351
+ ok: false,
352
+ message: `no ${SDK} in this directory's package.json`,
353
+ unblock: 'run sdk-tools upgrade in the app folder (the one with package.json)',
354
+ });
355
+ return blocked();
356
+ }
357
+ precheck({ id: 'sdk-installed', ok: true, message: `${SDK} ${report.from}` });
358
+
359
+ let status;
360
+ try {
361
+ status = run('git', ['status', '--porcelain'], cwd);
362
+ } catch {
363
+ status = null;
364
+ }
365
+ if (status === null) {
366
+ precheck({
367
+ id: 'git-clean',
368
+ ok: false,
369
+ message: 'not a git repository',
370
+ unblock: 'run inside the app git repository, so the upgrade is one reviewable diff',
371
+ });
372
+ if (!dryRun) return blocked();
373
+ } else if (status.trim()) {
374
+ const count = status.trim().split('\n').length;
375
+ precheck({
376
+ id: 'git-clean',
377
+ ok: dryRun,
378
+ message: `${count} uncommitted change(s)`,
379
+ unblock: 'commit or stash them (git stash -u), then run sdk-tools upgrade again',
380
+ });
381
+ if (!dryRun) return blocked();
382
+ } else precheck({ id: 'git-clean', ok: true, message: 'clean working tree' });
383
+ if (status !== null) {
384
+ const ignored = ignoredBy(cwd, FOUNDATION_CONFIG);
385
+ if (ignored)
386
+ report.warnings.push(
387
+ `${FOUNDATION_CONFIG} is ignored by git (${ignored}), so its layout block cannot be committed: delete that line from the ignore file (or run git add -f ${FOUNDATION_CONFIG}), then commit ${FOUNDATION_CONFIG}`,
388
+ );
389
+ }
390
+
391
+ const angular = installedVersion(cwd, '@angular/core');
392
+ const angularParts = angular ? parseVersion(angular) : null;
393
+ if (angularParts && (angularParts[0] !== ANGULAR.major || angularParts[1] !== ANGULAR.minor)) {
394
+ precheck({
395
+ id: 'angular-19.2',
396
+ ok: false,
397
+ message: `@angular/core ${angular} installed; the kit supports Angular 19.2 only`,
398
+ unblock: 'move the app back to Angular 19.2 (npm install @angular/core@~19.2.25 and the other @angular packages), then retry',
399
+ });
400
+ return blocked();
401
+ }
402
+
403
+ onProgress(`fetching ${to ?? 'the latest'} ${SDK}`);
404
+ const target = fetchTarget(cwd, to);
405
+ if ('error' in target) {
406
+ precheck({
407
+ id: 'target-exists',
408
+ ok: false,
409
+ message: target.error,
410
+ unblock: 'pass an existing version (npm view @sixbell-telco/sdk versions) or a packed .tgz to --to',
411
+ });
412
+ return blocked();
413
+ }
414
+ report.to = target.version;
415
+ report.source = target.source;
416
+ precheck({ id: 'target-exists', ok: true, message: `${SDK} ${target.version} (${target.source})` });
417
+ if (compareVersions(target.version, report.from) < 0) {
418
+ precheck({
419
+ id: 'target-newer',
420
+ ok: false,
421
+ message: `${target.version} is older than the installed ${report.from}`,
422
+ unblock: 'pass a newer version to --to; downgrades are not migrated',
423
+ });
424
+ return blocked();
425
+ }
426
+
427
+ onProgress('checking the federation lockstep');
428
+ const fleet = lockstep({ cwd, target: target.version, roots, installed: (dir) => installedVersion(dir, SDK) });
429
+ const verify = (/** @type {{ name: string, repo?: string }} */ remote) => `${remote.name}${remote.repo ? ` (${remote.repo})` : ''}`;
430
+ if (fleet.mismatched.length) {
431
+ precheck({
432
+ id: 'federation-lockstep',
433
+ ok: false,
434
+ message: `remote(s) on another ${SDK} than ${target.version}: ${fleet.mismatched.map((r) => `${r.name} ${r.sdk ?? 'not installed'} (${r.dir})`).join(', ')}`,
435
+ unblock: `upgrade each remote to ${target.version} first (sdk-tools upgrade --to ${target.version} in its folder), then this host; host and remotes share one SDK at run time`,
436
+ });
437
+ return blocked();
438
+ }
439
+ if (fleet.unknown.length)
440
+ report.warnings.push(
441
+ `no local checkout found below ${fleet.searched.join(', ')} for remote(s) ${fleet.unknown.map(verify).join(', ')}: verify they are on ${SDK} ${target.version} before you deploy, or pass --root <dir> to find them`,
442
+ );
443
+ if (fleet.role === 'host')
444
+ precheck({
445
+ id: 'federation-lockstep',
446
+ ok: true,
447
+ message: `${fleet.matched.length} remote(s) on ${target.version}, ${fleet.unknown.length} not found locally`,
448
+ });
449
+ else if (fleet.role === 'child' && fleet.hosts.length) {
450
+ precheck({
451
+ id: 'federation-lockstep',
452
+ ok: true,
453
+ message: `move together with the host(s) that load this remote: ${fleet.hosts.map((h) => `${h.name} ${h.sdk ?? 'not installed'} (${h.dir})`).join(', ')}`,
454
+ });
455
+ }
456
+
457
+ const targetPkg = readJson(join(target.dir, 'package.json')) ?? {};
458
+ /** @type {Record<string, string>} */
459
+ const peers = targetPkg.peerDependencies ?? {};
460
+ const angularFloor = parseVersion(floorOf(peers['@angular/core'] ?? '') ?? '');
461
+ if (angularFloor && (angularFloor[0] !== ANGULAR.major || angularFloor[1] !== ANGULAR.minor)) {
462
+ precheck({
463
+ id: 'angular-19.2',
464
+ ok: false,
465
+ message: `${SDK} ${target.version} needs @angular/core ${peers['@angular/core']}; apps stay on Angular 19.2`,
466
+ unblock: `pick a ${SDK} version whose peers stay on Angular 19.2: sdk-tools upgrade --to <version>`,
467
+ });
468
+ return blocked();
469
+ }
470
+ precheck({
471
+ id: 'angular-19.2',
472
+ ok: true,
473
+ message: `@angular/core ${angular ?? 'not installed'}; target needs ${peers['@angular/core'] ?? 'no Angular peer'}`,
474
+ });
475
+
476
+ const low = Object.entries(peers)
477
+ .map(([name, range]) => ({ name, floor: floorOf(range), installed: installedVersion(cwd, name) }))
478
+ .filter((p) => p.floor && p.installed && compareVersions(p.installed, p.floor) < 0);
479
+ if (low.length) {
480
+ precheck({
481
+ id: 'peer-floors',
482
+ ok: false,
483
+ message: low.map((p) => `${p.name} ${p.installed} < ${p.floor}`).join(', '),
484
+ unblock: peerFloorUnblock(readJson(join(cwd, 'package.json')) ?? {}, low),
485
+ });
486
+ return blocked();
487
+ }
488
+ /** @type {Record<string, { optional?: boolean }>} */
489
+ const peersMeta = targetPkg.peerDependenciesMeta ?? {};
490
+ const legacyPeers = /^\s*legacy-peer-deps\s*=\s*true\s*$/m.test(readText(join(cwd, '.npmrc')) ?? '');
491
+ const absent = Object.keys(peers).filter((name) => !installedVersion(cwd, name));
492
+ // npm 7+ installs a missing peer together with the SDK, unless the peer is optional or the app sets legacy-peer-deps.
493
+ const mustAdd = absent.filter((name) => legacyPeers || peersMeta[name]?.optional);
494
+ const withSdk = absent.filter((name) => !mustAdd.includes(name));
495
+ if (mustAdd.length)
496
+ report.warnings.push(
497
+ `peers the app must add (${legacyPeers ? 'legacy-peer-deps=true in .npmrc, so npm does not install peers' : 'optional peers npm does not install'}): npm install ${mustAdd.map((name) => `${name}@${floorOf(peers[name]) ?? 'latest'}`).join(' ')}`,
498
+ );
499
+ precheck({
500
+ id: 'peer-floors',
501
+ ok: true,
502
+ message: `${Object.keys(peers).length - absent.length} peer(s) at or above the target's floors${withSdk.length ? `; npm installs ${withSdk.length} more with the SDK: ${withSdk.join(', ')}` : ''}`,
503
+ });
504
+
505
+ const plan = selectMigrations(target.dir, report.from, target.version);
506
+ report.migrations = plan.migrations;
507
+ if (plan.collection && plan.migrations.length) {
508
+ onProgress('planning migrations');
509
+ const planned = await runMigrations(cwd, plan.collection, plan.migrations, true, report.from);
510
+ report.planned = { applied: planned.applied, manual: planned.manual, files: planned.files };
511
+ report.steps = planned.steps;
512
+ if (planned.errors.length) {
513
+ report.failing.push(...planned.errors.map((message) => ({ rule: 'migration', file: '', message })));
514
+ return { code: 1, data: report };
515
+ }
516
+ } else if (compareVersions(target.version, report.from) === 0) report.warnings.push(`already on ${target.version}: no migrations to run`);
517
+ if (dryRun) return { code: 0, data: report };
518
+
519
+ onProgress(`installing ${target.spec}`);
520
+ try {
521
+ if (install) await install(target.spec, cwd);
522
+ else {
523
+ const installed = npmInstall(target.spec, cwd);
524
+ if (!installed.ok) throw new Error(installed.message);
525
+ if (installed.eresolve)
526
+ report.warnings.push(
527
+ `npm installed ${target.spec} with ${installed.eresolve} ERESOLVE peer warning(s) it resolved itself; npm ls --all lists the tree to review`,
528
+ );
529
+ }
530
+ } catch (error) {
531
+ report.failing.push({ rule: 'install', file: 'package.json', message: firstLine(error) });
532
+ return { code: 1, data: report };
533
+ }
534
+ if (target.source === 'tarball')
535
+ report.warnings.push(
536
+ `installed from a tarball: package.json points at ${relative(cwd, target.spec) || target.spec}; pin the published version before you commit`,
537
+ );
538
+
539
+ if (plan.migrations.length) {
540
+ onProgress('running migrations');
541
+ const installed = selectMigrations(join(cwd, 'node_modules', SDK), report.from, target.version);
542
+ const result = await runMigrations(cwd, installed.collection ?? plan.collection ?? '', installed.migrations, false, report.from);
543
+ report.applied = result.applied;
544
+ report.manual = result.manual;
545
+ report.steps = result.steps;
546
+ report.files = result.files;
547
+ report.failing.push(...result.errors.map((message) => ({ rule: 'migration', file: '', message })));
548
+ }
549
+
550
+ onProgress("formatting the changed files with the app's Prettier");
551
+ report.format = formatChanged(
552
+ cwd,
553
+ report.files.filter((f) => f.action !== 'delete').map((f) => f.path),
554
+ );
555
+ if (report.format.status === 'failed')
556
+ report.failing.push({ rule: 'format', file: '', message: `the app's Prettier could not format the changed files: ${report.format.reason}` });
557
+
558
+ if (runCheck) {
559
+ onProgress('running sdk-tools check');
560
+ try {
561
+ const { check } = await import('../check.mjs');
562
+ const result = await check({ cwd, paths: ['src'], onProgress });
563
+ for (const f of result.findings.filter((f) => f.severity === 'error'))
564
+ report.failing.push({ rule: f.rule, file: f.file, line: f.line, message: f.message });
565
+ } catch (error) {
566
+ report.failing.push({ rule: 'check', file: '', message: `sdk-tools check could not run: ${firstLine(error)}` });
567
+ }
568
+ }
569
+ return { code: report.manual.length || report.failing.length ? 1 : 0, data: report };
570
+ }
571
+
572
+ /**
573
+ * The report for people in a terminal (agents read --json).
574
+ * @param {UpgradeReport} report
575
+ * @param {{ paint?: (format: Parameters<typeof import('node:util').styleText>[0], text: string) => string }} [options]
576
+ */
577
+ export function formatUpgrade(report, { paint = (format, text) => styleText(format, text, { validateStream: true, stream: process.stdout }) } = {}) {
578
+ /** @param {UpgradeItem | import('../types.js').UpgradeFailure} item */
579
+ const where = (item) => paint('dim', `${item.file || '(project)'}${item.line ? `:${item.line}` : ''}`);
580
+ const lines = [`${SDK} ${report.from ?? '?'} -> ${report.to ?? '?'}${report.dryRun ? paint('dim', ' (dry run)') : ''}`];
581
+ for (const p of report.prechecks) {
582
+ lines.push(` ${p.ok ? paint('green', '✔') : paint('red', '✖')} ${p.id}: ${p.message}`);
583
+ if (!p.ok && p.unblock) lines.push(` ${paint('bold', 'to unblock:')} ${p.unblock}`);
584
+ }
585
+ if (report.prechecks.some((p) => !p.ok) && !report.dryRun) return lines.join('\n');
586
+ if (report.migrations.length) lines.push('', `Migrations: ${report.migrations.map((m) => `${m.name} (${m.version})`).join(', ')}`);
587
+ const applied = report.dryRun ? report.planned.applied : report.applied;
588
+ const manual = report.dryRun ? report.planned.manual : report.manual;
589
+ if (applied.length) {
590
+ lines.push('', paint('bold', report.dryRun ? `Planned (${applied.length})` : `Applied (${applied.length})`));
591
+ for (const item of applied) lines.push(` ${where(item)} ${item.message} ${paint('dim', item.rule)}`);
592
+ }
593
+ if (manual.length) {
594
+ lines.push('', paint('bold', `Manual (${manual.length})`));
595
+ for (const item of manual) lines.push(` ${where(item)} ${item.message} ${paint('dim', item.rule)}`);
596
+ }
597
+ if (report.steps.length) {
598
+ lines.push('', paint('bold', `Manual steps no migration applies (${report.steps.length})`));
599
+ for (const item of report.steps)
600
+ lines.push(` ${item.message} ${paint('dim', `${item.rule.slice('manual-step:'.length)}, ${item.since ?? item.migration}`)}`);
601
+ }
602
+ if (report.failing.length) {
603
+ lines.push('', paint('bold', `Still failing (${report.failing.length})`));
604
+ for (const item of report.failing) lines.push(` ${where(item)} ${paint('red', item.message)} ${paint('dim', item.rule)}`);
605
+ }
606
+ if (report.format) {
607
+ const { status, files, reason } = report.format;
608
+ lines.push(
609
+ '',
610
+ status === 'formatted'
611
+ ? `${paint('green', '✔')} format: ${files.length} changed file(s) formatted with the app's Prettier`
612
+ : `${status === 'failed' ? paint('red', '✖') : paint('dim', '-')} format: ${status === 'failed' ? 'failed' : 'skipped'}, ${reason}`,
613
+ );
614
+ }
615
+ for (const warning of report.warnings) lines.push(`${paint('yellow', '⚠')} ${warning}`);
616
+ lines.push(
617
+ '',
618
+ report.dryRun
619
+ ? `Dry run: nothing changed. ${applied.length} planned edit(s), ${manual.length} manual item(s). Run without --dry-run to apply.`
620
+ : `${report.applied.length} applied, ${report.manual.length} manual, ${report.failing.length} still failing.`,
621
+ );
622
+ return lines.join('\n');
623
+ }