@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
package/src/cli.mjs ADDED
@@ -0,0 +1,551 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * sdk-tools: the CLI for apps built with @sixbell-telco/sdk.
4
+ *
5
+ * Exit codes: 0 ok, 1 findings or failure, 2 usage error, 3 blocked by a pre-check.
6
+ * `--json` prints one envelope: { ok, code, data, error? }.
7
+ */
8
+ import { readFileSync } from 'node:fs';
9
+ import { parseArgs } from 'node:util';
10
+
11
+ /**
12
+ * @typedef {import('./types.js').Envelope} Envelope
13
+ * @typedef {{ write(chunk: string): unknown }} Sink
14
+ * @typedef {{ code: 0 | 1 | 2 | 3, data: unknown, text: string }} VerbResult
15
+ * @typedef {{
16
+ * summary: string,
17
+ * usage: string,
18
+ * help: string,
19
+ * options: import('node:util').ParseArgsOptionsConfig,
20
+ * run(values: Record<string, string | boolean | (string | boolean)[] | undefined>, positionals: string[]): Promise<VerbResult>,
21
+ * }} Verb
22
+ */
23
+
24
+ /** @type {Record<string, Verb>} */
25
+ const VERBS = {
26
+ check: {
27
+ summary: 'Check an app against the installed SDK: kit API, design rules and template types',
28
+ usage: 'sdk-tools check [paths...] [options]',
29
+ help: [
30
+ 'Lints templates (.html and inline), imports and classes against the installed',
31
+ '@sixbell-telco/sdk and its theme, then type-checks templates with the Angular compiler.',
32
+ 'On the whole app (src, the default) it also checks the project: federation and remote',
33
+ 'shell, dev harness and kit shell, pubsub and menu wiring, scripts and targets, i18n, CSS',
34
+ 'and theme catalogs, and security floors. These findings keep their mfe-tools ids',
35
+ '(MFE_CHILD_003, DS_COLOR_LITERAL, MFE_SEC_DEPS_003, ...).',
36
+ '',
37
+ 'Exceptions: sdk-tools.exceptions.json at the app root, an array of',
38
+ '{ rule, path (glob), reason, owner?, until? }. Matched findings are listed under',
39
+ '"excepted" in --json and do not count; an entry past its until date is a finding.',
40
+ '',
41
+ '--integration checks the wiring between repos instead: the hosts, children, integration',
42
+ 'and database repos found under --root (host manifest vs child name and exposes, route',
43
+ 'mounts, proxy entries, served manifest and translations, permission translations, seed',
44
+ 'files, themes.json), with ids MFE_INT_001..010 and MFE_INT_ASSET_001..004. Files only.',
45
+ '',
46
+ 'Options:',
47
+ ' --json one JSON envelope on stdout, for agents and scripts',
48
+ ' --fix apply safe fixes (deprecated tokens, outline-none)',
49
+ ' --quiet show errors only',
50
+ ' --max-warnings <n> fail when there are more than n warnings',
51
+ ' --no-typecheck lint only (faster)',
52
+ ' --project <tsconfig> tsconfig to type-check (default tsconfig.app.json, then tsconfig.json)',
53
+ ' --manifest <file> check against this manifest instead of the installed SDK',
54
+ ' --integration check the cross-repo wiring under --root (no lint or typecheck)',
55
+ ' --root <dir> with --integration: the folder holding the repos (default .)',
56
+ '',
57
+ 'Examples:',
58
+ ' sdk-tools check',
59
+ ' sdk-tools check src/app/orders --no-typecheck',
60
+ ' sdk-tools check --json > findings.json',
61
+ ' sdk-tools check --integration --root ~/work/irp --json',
62
+ ].join('\n'),
63
+ options: {
64
+ json: { type: 'boolean', default: false },
65
+ fix: { type: 'boolean', default: false },
66
+ quiet: { type: 'boolean', default: false },
67
+ 'max-warnings': { type: 'string' },
68
+ 'no-typecheck': { type: 'boolean', default: false },
69
+ project: { type: 'string' },
70
+ manifest: { type: 'string' },
71
+ integration: { type: 'boolean', default: false },
72
+ root: { type: 'string' },
73
+ help: { type: 'boolean', short: 'h', default: false },
74
+ },
75
+ async run(values, positionals) {
76
+ /** @param {string} name */
77
+ const flag = (name) => values[name] === true;
78
+ if (typeof values.root === 'string' && !flag('integration')) throw new UsageError('--root needs --integration');
79
+ if (flag('integration')) {
80
+ if (positionals.length) throw new UsageError('--integration takes no paths; pass the folder with --root');
81
+ const { resolve } = await import('node:path');
82
+ const { checkIntegration } = await import('./check/integration.mjs');
83
+ const { formatCheck } = await import('./format.mjs');
84
+ const started = Date.now();
85
+ const data = checkIntegration({ root: resolve(typeof values.root === 'string' ? values.root : '.') });
86
+ return {
87
+ code: data.counts.errors > 0 ? 1 : 0,
88
+ data,
89
+ text: formatCheck(data, { quiet: flag('quiet'), durationMs: Date.now() - started }),
90
+ };
91
+ }
92
+ const { check } = await import('./check.mjs');
93
+ const { formatCheck, progress } = await import('./format.mjs');
94
+ const maxWarnings = typeof values['max-warnings'] === 'string' ? Number(values['max-warnings']) : undefined;
95
+ if (maxWarnings !== undefined && !Number.isInteger(maxWarnings)) throw new UsageError('--max-warnings takes a whole number');
96
+ const report = flag('json') ? () => {} : progress();
97
+ const started = Date.now();
98
+ let data;
99
+ try {
100
+ data = await check({
101
+ cwd: process.cwd(),
102
+ paths: positionals.length ? positionals : undefined,
103
+ fix: flag('fix'),
104
+ typecheck: !flag('no-typecheck'),
105
+ project: typeof values.project === 'string' ? values.project : undefined,
106
+ manifestPath: typeof values.manifest === 'string' ? values.manifest : undefined,
107
+ onProgress: report,
108
+ });
109
+ } finally {
110
+ report('');
111
+ }
112
+ const failed = data.counts.errors > 0 || (maxWarnings !== undefined && data.counts.warnings > maxWarnings);
113
+ return { code: failed ? 1 : 0, data, text: formatCheck(data, { quiet: flag('quiet'), durationMs: Date.now() - started, maxWarnings }) };
114
+ },
115
+ },
116
+ mcp: {
117
+ summary: 'Start the MCP server over stdio: kit facts and check_usage for agents',
118
+ usage: 'sdk-tools mcp [options]',
119
+ help: [
120
+ 'Starts an MCP server on stdin/stdout (server name SixbellSdk). Its tools answer from the',
121
+ '@sixbell-telco/sdk installed in the current folder and run the same checks as sdk-tools check:',
122
+ 'list_components, search_components, get_component, get_tokens, check_usage, get_recipe.',
123
+ "Resources: the app's DESIGN.md and the recipes. Start it from the app's folder.",
124
+ '',
125
+ 'Options:',
126
+ ' --manifest <file> answer from this manifest instead of the installed SDK',
127
+ '',
128
+ 'Example (.mcp.json of an app):',
129
+ ' { "mcpServers": { "SixbellSdk": { "command": "npx", "args": ["@sixbell-telco/sdk-tools", "mcp"] } } }',
130
+ ].join('\n'),
131
+ options: {
132
+ manifest: { type: 'string' },
133
+ help: { type: 'boolean', short: 'h', default: false },
134
+ },
135
+ async run(values) {
136
+ const { serve } = await import('./mcp/server.mjs');
137
+ await serve({ cwd: process.cwd(), manifestPath: typeof values.manifest === 'string' ? values.manifest : undefined });
138
+ // The client is gone: exit without writing to stdout, which carried the protocol.
139
+ process.exit(0);
140
+ },
141
+ },
142
+ init: {
143
+ summary: 'Create an MFE from its template repo, or bring an existing MFE up to the template',
144
+ usage: 'sdk-tools init [dir] [--host|--child] [options]',
145
+ help: [
146
+ 'In an empty folder, creates a host or child MFE from its template repo',
147
+ '(EnghouseGlobal/nw-sx-starters-mfe-{host,child}-template). In an existing MFE, adds the',
148
+ 'template files it lacks, updates untouched copies of older template versions and merges',
149
+ 'template keys into its JSON; product code, themes and i18n keys stay. A foundation file the',
150
+ 'product changed, or a file init cannot read, is reported as manual and left alone (exit 1).',
151
+ 'The whole plan is built before anything is written.',
152
+ '',
153
+ 'The template is a local checkout found by its origin remote (--template-root, else up to six',
154
+ 'folders above the app, nearest first), else a clone cached in ~/.cache/sdk-tools/templates from the host of',
155
+ "the app's origin remote (override with SDK_TOOLS_TEMPLATE_REMOTE, '{repo}' for the repo).",
156
+ '',
157
+ 'Options:',
158
+ ' --host, --child the MFE kind (required for a new MFE; read from the app otherwise)',
159
+ ' --dry-run print the plan and write nothing',
160
+ ' --json one JSON envelope on stdout, for agents and scripts',
161
+ ' --name <name> project name of a new MFE (default: the folder name)',
162
+ ' --display-name <text> display name of a new MFE (default: the name in title case)',
163
+ ' --template <dir> use this template checkout',
164
+ ' --template-root <dir> search here for a template checkout (repeatable)',
165
+ ' --offline never clone; fail if no local checkout is found',
166
+ '',
167
+ 'Examples:',
168
+ ' sdk-tools init my-mfe --child',
169
+ ' sdk-tools init --dry-run',
170
+ ' sdk-tools init --dry-run --json > plan.json',
171
+ ].join('\n'),
172
+ options: {
173
+ json: { type: 'boolean', default: false },
174
+ host: { type: 'boolean', default: false },
175
+ child: { type: 'boolean', default: false },
176
+ 'dry-run': { type: 'boolean', default: false },
177
+ name: { type: 'string' },
178
+ 'display-name': { type: 'string' },
179
+ template: { type: 'string' },
180
+ 'template-root': { type: 'string', multiple: true },
181
+ offline: { type: 'boolean', default: false },
182
+ help: { type: 'boolean', short: 'h', default: false },
183
+ },
184
+ async run(values, positionals) {
185
+ if (values.host === true && values.child === true) throw new UsageError('pass --host or --child, not both');
186
+ if (positionals.length > 1) throw new UsageError('init takes one folder');
187
+ const { init, formatInit, InitUsageError } = await import('./init/init.mjs');
188
+ /** @param {string} name */
189
+ const text = (name) => (typeof values[name] === 'string' ? /** @type {string} */ (values[name]) : undefined);
190
+ let plan;
191
+ try {
192
+ plan = init({
193
+ cwd: process.cwd(),
194
+ dir: positionals[0],
195
+ role: values.host === true ? 'host' : values.child === true ? 'child' : undefined,
196
+ dryRun: values['dry-run'] === true,
197
+ name: text('name'),
198
+ displayName: text('display-name'),
199
+ templateDir: text('template'),
200
+ roots: Array.isArray(values['template-root']) ? values['template-root'].map(String) : [],
201
+ offline: values.offline === true,
202
+ });
203
+ } catch (error) {
204
+ throw error instanceof InitUsageError ? new UsageError(error.message) : error;
205
+ }
206
+ return { code: plan.manual.length ? 1 : 0, data: plan, text: formatInit(plan) };
207
+ },
208
+ },
209
+ upgrade: {
210
+ summary: 'Upgrade @sixbell-telco/sdk with its ng update migrations, then check the app',
211
+ usage: 'sdk-tools upgrade [--to <version|file.tgz>] [options]',
212
+ help: [
213
+ 'Pre-checks (clean git tree, Angular stays on 19.2, peer floors, the target exists, and in a host',
214
+ "every remote found locally on the target), plans the SDK's ng update migrations in dry-run mode,",
215
+ "installs the target, applies them, formats the changed files with the app's Prettier, runs check and",
216
+ 'reports what was applied, what is manual and what still fails. Exit 3 when a pre-check blocks.',
217
+ '',
218
+ 'Options:',
219
+ ' --to <v> target version, dist-tag or packed .tgz (default: latest)',
220
+ ' --dry-run plan only: list the edits and manual items, change nothing',
221
+ ' --no-check skip sdk-tools check after the migrations',
222
+ " --root <dir> where to find the federation's other checkouts (repeatable;",
223
+ ' default SDK_TOOLS_FLEET_ROOT, else the folders above the app)',
224
+ ' --json one JSON envelope on stdout',
225
+ '',
226
+ 'Examples:',
227
+ ' sdk-tools upgrade --dry-run',
228
+ ' sdk-tools upgrade --to 4.6.0',
229
+ ].join('\n'),
230
+ options: {
231
+ json: { type: 'boolean', default: false },
232
+ to: { type: 'string' },
233
+ 'dry-run': { type: 'boolean', default: false },
234
+ 'no-check': { type: 'boolean', default: false },
235
+ root: { type: 'string', multiple: true },
236
+ help: { type: 'boolean', short: 'h', default: false },
237
+ },
238
+ async run(values) {
239
+ const { upgrade, formatUpgrade } = await import('./upgrade/upgrade.mjs');
240
+ const { progress } = await import('./format.mjs');
241
+ const report = values.json === true ? () => {} : progress();
242
+ try {
243
+ const { code, data } = await upgrade({
244
+ cwd: process.cwd(),
245
+ to: typeof values.to === 'string' ? values.to : undefined,
246
+ dryRun: values['dry-run'] === true,
247
+ check: values['no-check'] !== true,
248
+ roots: Array.isArray(values.root) ? values.root.map(String) : [],
249
+ onProgress: report,
250
+ });
251
+ return { code, data, text: formatUpgrade(data) };
252
+ } finally {
253
+ report('');
254
+ }
255
+ },
256
+ },
257
+ add: {
258
+ summary: 'Add a composition recipe (crud-list, form-dialog, detail-page) as local app-* code',
259
+ usage: 'sdk-tools add [recipe] [name] [options]',
260
+ help: [
261
+ 'Writes a recipe from the UI composition standard into src/app/features/<name>/ (standalone',
262
+ 'components with signals, st-* components only, a Jest spec each) and merges its i18n keys into',
263
+ 'src/assets/i18n/<lang>.json under <app>.<name>. These are the files and steps the MCP',
264
+ 'get_recipe tool returns. With no recipe, lists them. <name> is kebab-case (default: item).',
265
+ '',
266
+ 'Never overwrites: a file that exists with other content is reported and nothing is written',
267
+ '(exit 1). Files shared between recipes (the model, the store, the form dialog) keep an existing',
268
+ 'copy, and existing i18n values are never changed.',
269
+ '',
270
+ 'Options:',
271
+ ' --dry-run print the plan and write nothing',
272
+ ' --force overwrite the recipe files that are in the way',
273
+ ' --json one JSON envelope on stdout, for agents and scripts',
274
+ '',
275
+ 'Examples:',
276
+ ' sdk-tools add',
277
+ ' sdk-tools add crud-list product',
278
+ ' sdk-tools add detail-page product --dry-run',
279
+ ].join('\n'),
280
+ options: {
281
+ json: { type: 'boolean', default: false },
282
+ 'dry-run': { type: 'boolean', default: false },
283
+ force: { type: 'boolean', default: false },
284
+ help: { type: 'boolean', short: 'h', default: false },
285
+ },
286
+ async run(values, positionals) {
287
+ if (positionals.length > 2) throw new UsageError('add takes a recipe and a name');
288
+ const { add, formatAdd, listRecipes, AddUsageError } = await import('./add/add.mjs');
289
+ if (!positionals.length) {
290
+ const data = listRecipes();
291
+ const text = ['Recipes:', ...data.recipes.map((r) => ` ${r.id.padEnd(12)} ${r.summary}`), '', 'Run sdk-tools add <recipe> <name>.'].join(
292
+ '\n',
293
+ );
294
+ return { code: 0, data, text };
295
+ }
296
+ let plan;
297
+ try {
298
+ plan = add({
299
+ cwd: process.cwd(),
300
+ recipe: positionals[0],
301
+ name: positionals[1],
302
+ dryRun: values['dry-run'] === true,
303
+ force: values.force === true,
304
+ });
305
+ } catch (error) {
306
+ throw error instanceof AddUsageError ? new UsageError(error.message) : error;
307
+ }
308
+ return { code: plan.blocked ? 1 : 0, data: plan, text: formatAdd(plan) };
309
+ },
310
+ },
311
+ info: {
312
+ summary: 'Print the project context for agents and skills: kit version, entry points, theme, layout, role',
313
+ usage: 'sdk-tools info [--json]',
314
+ help: [
315
+ 'Reads the app in the current folder, files only (no lint, no type check, no npm): the installed',
316
+ '@sixbell-telco/sdk and the entry points src imports, Angular, the themes, the layout block of',
317
+ 'mfe-foundation.config.json, the MFE role (host, child or none) with its federation name, exposes',
318
+ 'and remotes, and whether DESIGN.md and AGENTS.md exist. Skills load it at start with',
319
+ '`npx @sixbell-telco/sdk-tools info --json`; the data has a schemaVersion and fields are only ever added.',
320
+ 'In a folder that is not an app it still answers (role none) and exits 0.',
321
+ '',
322
+ 'Options:',
323
+ ' --json one JSON envelope on stdout, for agents and scripts',
324
+ ].join('\n'),
325
+ options: {
326
+ json: { type: 'boolean', default: false },
327
+ help: { type: 'boolean', short: 'h', default: false },
328
+ },
329
+ async run() {
330
+ const { info, formatInfo } = await import('./info/info.mjs');
331
+ const data = info({ cwd: process.cwd() });
332
+ return { code: 0, data, text: formatInfo(data) };
333
+ },
334
+ },
335
+ doctor: {
336
+ summary: 'Report the environment and drift: Node and npm, DESIGN.md, AGENTS.md, template files',
337
+ usage: 'sdk-tools doctor [options]',
338
+ help: [
339
+ 'Checks what check does not: Node and npm against package.json engines, DESIGN.md and AGENTS.md,',
340
+ 'mfe-foundation.config.json and its layout block, agent tooling tracked in git, a starter feature',
341
+ 'left next to real ones, the child error interceptor, and the template files the app lacks.',
342
+ 'Template drift is judged against a local checkout of the role template, found the way init',
343
+ 'finds it; nothing is fetched. Findings keep their mfe-tools ids (MFE_DOC_002, MFE_JEST_001, ...)',
344
+ 'and each says its fix. Errors exit 1; warnings alone exit 0.',
345
+ '',
346
+ 'Options:',
347
+ ' --json one JSON envelope on stdout, for agents and scripts',
348
+ ' --template <dir> judge drift against this template checkout',
349
+ ' --template-root <dir> search here for a template checkout (repeatable)',
350
+ '',
351
+ 'Examples:',
352
+ ' sdk-tools doctor',
353
+ ' sdk-tools doctor --template-root ~/src/starters --json',
354
+ ].join('\n'),
355
+ options: {
356
+ json: { type: 'boolean', default: false },
357
+ template: { type: 'string' },
358
+ 'template-root': { type: 'string', multiple: true },
359
+ help: { type: 'boolean', short: 'h', default: false },
360
+ },
361
+ async run(values) {
362
+ const { doctor, formatDoctor } = await import('./doctor/doctor.mjs');
363
+ const data = doctor({
364
+ cwd: process.cwd(),
365
+ templateDir: typeof values.template === 'string' ? values.template : undefined,
366
+ roots: Array.isArray(values['template-root']) ? values['template-root'].map(String) : [],
367
+ });
368
+ return { code: data.counts.errors > 0 ? 1 : 0, data, text: formatDoctor(data) };
369
+ },
370
+ },
371
+ docs: {
372
+ summary: "Print a component's API and example, or a recipe, from the installed SDK",
373
+ usage: 'sdk-tools docs [selector|recipe] [options]',
374
+ help: [
375
+ "Prints a component's inputs (types, allowed values, defaults), outputs, slots, import line and",
376
+ 'example from the manifest of the installed @sixbell-telco/sdk, or a recipe: the same answers as',
377
+ 'the MCP get_component and get_recipe tools. With no name, lists the components and recipes.',
378
+ 'An unknown name prints the nearest matches and exits 1.',
379
+ '',
380
+ 'Options:',
381
+ ' --json one JSON envelope on stdout, for agents and scripts',
382
+ ' --manifest <file> answer from this manifest instead of the installed SDK',
383
+ '',
384
+ 'Examples:',
385
+ ' sdk-tools docs st-button',
386
+ ' sdk-tools docs crud-list',
387
+ ' sdk-tools docs',
388
+ ].join('\n'),
389
+ options: {
390
+ json: { type: 'boolean', default: false },
391
+ manifest: { type: 'string' },
392
+ help: { type: 'boolean', short: 'h', default: false },
393
+ },
394
+ async run(values, positionals) {
395
+ if (positionals.length > 1) throw new UsageError('docs takes one selector or recipe');
396
+ const { docs, formatDocs } = await import('./docs/docs.mjs');
397
+ const data = docs({
398
+ cwd: process.cwd(),
399
+ query: positionals[0],
400
+ manifestPath: typeof values.manifest === 'string' ? values.manifest : undefined,
401
+ });
402
+ return { code: data.kind === 'not-found' ? 1 : 0, data, text: formatDocs(data) };
403
+ },
404
+ },
405
+ };
406
+
407
+ class UsageError extends Error {}
408
+
409
+ function help() {
410
+ return [
411
+ 'sdk-tools: tools for apps built with @sixbell-telco/sdk',
412
+ '',
413
+ 'Usage: sdk-tools <command> [options]',
414
+ '',
415
+ 'Commands:',
416
+ ...Object.entries(VERBS).map(([name, verb]) => ` ${name.padEnd(8)} ${verb.summary}`),
417
+ '',
418
+ 'Run sdk-tools <command> --help for its options. Add --json to any command for machine output,',
419
+ '--version for the version.',
420
+ 'Exit codes: 0 ok, 1 problems found or failure, 2 usage error, 3 blocked by a pre-check.',
421
+ ].join('\n');
422
+ }
423
+
424
+ /**
425
+ * The Tailwind compile behind the design rules prints plugin banners (`/*! 🌼 daisyUI 5 *\/`) on
426
+ * stdout, sometimes after the lint has returned. Drop those lines for the whole run so stdout
427
+ * carries only this tool's output (and --json stays parseable). SDK 4.6.0 and later set
428
+ * `logs: false`, so this only matters for apps on an older SDK.
429
+ */
430
+ export function divertBanners() {
431
+ const write = process.stdout.write.bind(process.stdout);
432
+ const banner = /^\/\*! .*\*\/\s*$/;
433
+ /** @type {(chunk: string | Uint8Array, ...rest: any[]) => boolean} */
434
+ const filtered = (chunk, ...rest) => {
435
+ // The daisyUI log comes from a worker thread, forwarded to stdout as a Buffer.
436
+ const text = typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8');
437
+ return banner.test(text) ? true : write(chunk, ...rest);
438
+ };
439
+ process.stdout.write = /** @type {typeof process.stdout.write} */ (filtered);
440
+ }
441
+
442
+ /**
443
+ * The closest candidate within `max` edits, for "did you mean" hints.
444
+ * @param {string} input
445
+ * @param {string[]} candidates
446
+ * @returns {string | null}
447
+ */
448
+ function suggest(input, candidates, max = 2) {
449
+ /**
450
+ * @param {string} a
451
+ * @param {string} b
452
+ */
453
+ const distance = (a, b) => {
454
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i);
455
+ for (let i = 1; i <= a.length; i++) {
456
+ let previous = row[0];
457
+ row[0] = i;
458
+ for (let j = 1; j <= b.length; j++) {
459
+ const current = row[j];
460
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1));
461
+ previous = current;
462
+ }
463
+ }
464
+ return row[b.length];
465
+ };
466
+ /** @type {[string, number][]} */
467
+ const scored = candidates.map((c) => [c, distance(input, c)]);
468
+ const best = scored.sort((x, y) => x[1] - y[1])[0];
469
+ return best && best[1] <= max ? best[0] : null;
470
+ }
471
+
472
+ /** @returns {string} */
473
+ function version() {
474
+ return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
475
+ }
476
+
477
+ /**
478
+ * Runs the CLI. Normal output goes to `out`; human-readable errors go to `err`. With --json every
479
+ * result, error included, is one envelope on `out`, so agents only parse stdout.
480
+ */
481
+ /**
482
+ * @param {string[]} [argv]
483
+ * @param {Sink} [out]
484
+ * @param {Sink} [err]
485
+ * @returns {Promise<0 | 1 | 2 | 3>}
486
+ */
487
+ export async function main(argv = process.argv.slice(2), out = process.stdout, err = process.stderr) {
488
+ const json = argv.includes('--json');
489
+ const args = argv.filter((a) => a !== '--json');
490
+ const [verbName, ...rest] = args;
491
+ /**
492
+ * @param {Envelope} envelope
493
+ * @param {string} text
494
+ * @param {Sink} [stream]
495
+ */
496
+ const emit = (envelope, text, stream = out) => (json ? out : stream).write(`${json ? JSON.stringify(envelope) : text}\n`);
497
+ /**
498
+ * @param {1 | 2} code
499
+ * @param {string} error
500
+ * @param {string} text
501
+ * @returns {1 | 2}
502
+ */
503
+ const fail = (code, error, text) => {
504
+ emit({ ok: false, code, data: null, error }, text, err);
505
+ return code;
506
+ };
507
+
508
+ if (verbName === '--version' || verbName === '-v') {
509
+ emit({ ok: true, code: 0, data: { version: version() } }, version());
510
+ return 0;
511
+ }
512
+ if (!verbName || verbName === '--help' || verbName === '-h' || verbName === 'help') {
513
+ emit({ ok: true, code: 0, data: { commands: Object.keys(VERBS), version: version() } }, help());
514
+ return 0;
515
+ }
516
+ const verb = Object.hasOwn(VERBS, verbName) ? VERBS[verbName] : undefined;
517
+ if (!verb) {
518
+ const hint = suggest(verbName, Object.keys(VERBS));
519
+ const error = `unknown command "${verbName}"${hint ? `; did you mean "${hint}"?` : ''}`;
520
+ return fail(2, error, `sdk-tools: ${error}\nRun sdk-tools --help for the commands.`);
521
+ }
522
+ const parsedArgs = [...rest, ...(json && 'json' in verb.options ? ['--json'] : [])];
523
+ let parsed;
524
+ try {
525
+ parsed = parseArgs({ args: parsedArgs, options: verb.options, allowPositionals: true });
526
+ } catch (thrown) {
527
+ const error = thrown instanceof Error ? thrown : new Error(String(thrown));
528
+ const unknown = /Unknown option '(--?[\w-]+)'/.exec(error.message)?.[1];
529
+ const names = Object.keys(verb.options).map((name) => `--${name}`);
530
+ const hint = unknown ? suggest(unknown, names) : null;
531
+ const message = `${error.message.split('. ')[0]}${hint ? `; did you mean "${hint}"?` : ''}`;
532
+ return fail(2, message, `sdk-tools ${verbName}: ${message}\nUsage: ${verb.usage}\nRun sdk-tools ${verbName} --help for the options.`);
533
+ }
534
+ if (parsed.values.help) {
535
+ emit({ ok: true, code: 0, data: { usage: verb.usage, help: verb.help } }, `Usage: ${verb.usage}\n\n${verb.help}`);
536
+ return 0;
537
+ }
538
+ try {
539
+ const { code, data, text } = await verb.run(parsed.values, parsed.positionals);
540
+ emit({ ok: code === 0, code, data }, text);
541
+ return code;
542
+ } catch (thrown) {
543
+ const message = thrown instanceof Error ? thrown.message : String(thrown);
544
+ return fail(thrown instanceof UsageError ? 2 : 1, message, `sdk-tools ${verbName}: ${message}`);
545
+ }
546
+ }
547
+
548
+ if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith('/sdk-tools')) {
549
+ divertBanners();
550
+ process.exitCode = await main();
551
+ }