@bitakit/cli 0.0.0-stage → 0.2.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.
package/src/cli.mjs ADDED
@@ -0,0 +1,266 @@
1
+ #!/usr/bin/env node
2
+ import { readFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { styleText } from 'node:util';
5
+ import { Command } from 'commander';
6
+ import {
7
+ describeBitaKit,
8
+ generateBitaKit,
9
+ migrateProject,
10
+ watchBitaKit,
11
+ } from '@bitakit/discovery';
12
+ import { addContribution, addPlugin, contributionKinds } from './add.mjs';
13
+ import { inspectionFromDescription } from './inventory.mjs';
14
+ import { buildPlugin } from './build.mjs';
15
+ import { doctor } from './doctor.mjs';
16
+ import { initProject } from './init.mjs';
17
+ import { findProject, findProjectRoot } from './project.mjs';
18
+
19
+ const manifest = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
20
+ const relative = (file) => path.relative(process.cwd(), file) || '.';
21
+ const created = (files) =>
22
+ files.forEach((file) => console.log(` ${styleText('green', '+')} ${relative(file)}`));
23
+
24
+ const program = new Command()
25
+ .name('bitakit')
26
+ .description(
27
+ 'Wire an app, add plugins and contributions, generate the wiring, and check a project for problems.',
28
+ )
29
+ .version(manifest.version);
30
+
31
+ const add = program
32
+ .command('add')
33
+ .description('Create a plugin or a contribution from a template.');
34
+ add
35
+ .command('plugin')
36
+ .argument('<name>', 'plugin name, for example "notes"')
37
+ .option('--example', 'a complete example feature: a service, events, actions and a list page')
38
+ .option(
39
+ '--minimal',
40
+ 'only a service, its events and one action, without a page or navigation link',
41
+ )
42
+ .description(
43
+ 'Create src/plugins/<name> with one page and, when the app has Shell, its navigation link.',
44
+ )
45
+ .action(async (name, options) => {
46
+ const result = await addPlugin(name, { minimal: options.minimal, example: options.example });
47
+ console.log(`\nCreated plugin "${name}":`);
48
+ created(result.created);
49
+ console.log(
50
+ result.navigation
51
+ ? `\n"${result.title}" now appears in the navigation and opens ${result.path}.\nThe dev server picks it up automatically; no registration needed.\nNext: npx bitakit add service ${name}/items, then npx bitakit add action ${name}/<name>.\n`
52
+ : result.path
53
+ ? `\n"${result.title}" opens ${result.path}.\nThe dev server picks it up automatically; no registration needed.\n`
54
+ : `\nThe dev server picks it up automatically; no registration needed.\n`,
55
+ );
56
+ });
57
+ for (const kind of contributionKinds)
58
+ add
59
+ .command(kind)
60
+ .argument(
61
+ kind === 'events' || kind === 'settings' || kind === 'settings-page'
62
+ ? '[plugin]'
63
+ : kind === 'layout'
64
+ ? '<name>'
65
+ : '<target>',
66
+ kind === 'events' || kind === 'settings' || kind === 'settings-page'
67
+ ? `the plugin that owns the ${kind}; omit it inside a plugin package`
68
+ : kind === 'layout'
69
+ ? 'the layout name; pages choose it with export const layout'
70
+ : kind === 'slot'
71
+ ? '"<plugin>/<slot path>": "activity/projects/sidebar" adds a component of plugin "activity" to slot "projects.sidebar"'
72
+ : `"<plugin>/<name>" in an app (nested names allowed), or "<name>" inside a plugin package`,
73
+ )
74
+ .description(
75
+ kind === 'events' || kind === 'settings'
76
+ ? `Create the ${kind}.ts of a plugin.`
77
+ : kind === 'settings-page'
78
+ ? "Create ui/settings/page.tsx, which replaces the plugin's generated settings page."
79
+ : kind === 'layout'
80
+ ? 'Create src/layouts/<name>.tsx of the app.'
81
+ : `Create ${/^[aeiou]/.test(kind) ? 'an' : 'a'} ${kind} file. Its ID comes from the file path.`,
82
+ )
83
+ .action(async (target) => {
84
+ const result = await addContribution(kind, target);
85
+ if (result.createdPlugin) console.log(`\nCreated plugin "${result.plugin}".`);
86
+ console.log(
87
+ kind === 'slot'
88
+ ? `\nCreated a component of plugin "${result.plugin}" for slot "${result.id}":`
89
+ : `\nCreated ${kind} ${kind === 'page' ? result.path : `"${result.id}"`}:`,
90
+ );
91
+ created(result.created);
92
+ console.log('');
93
+ });
94
+
95
+ program
96
+ .command('init')
97
+ .description(
98
+ 'Wire an existing Next.js or TanStack Start app: bitakit.config.ts, the config wrapper or Vite plugin, the provider, the catch-all route and .gitignore.',
99
+ )
100
+ .action(async () => {
101
+ const { written, skipped, install } = await initProject();
102
+ if (written.length) {
103
+ console.log('\nWritten:');
104
+ for (const { file, created } of written)
105
+ console.log(` ${styleText('green', created ? '+' : '~')} ${relative(file)}`);
106
+ }
107
+ if (skipped.length) {
108
+ console.log('\nSkipped:');
109
+ for (const { file, reason } of skipped)
110
+ console.log(
111
+ ` ${styleText('yellow', '-')} ${relative(file)} ${styleText('dim', `(${reason})`)}`,
112
+ );
113
+ }
114
+ if (!written.length) console.log('\nNothing to write: the app is already wired.');
115
+ if (install.length)
116
+ console.log(`\nInstall the packages the wiring imports:\n npm install ${install.join(' ')}`);
117
+ console.log('\nThen run "npx bitakit generate" and "npx bitakit doctor".\n');
118
+ });
119
+
120
+ program
121
+ .command('generate')
122
+ .option('--watch', 'keep regenerating while files change')
123
+ .description('Write src/bitakit.gen.* from the plugin folders and installed packages.')
124
+ .action(async (options) => {
125
+ const project = await findProject();
126
+ if (project.kind !== 'app') throw new Error('Run "bitakit generate" inside an app.');
127
+ if (options.watch) {
128
+ watchBitaKit(project.root, (error) =>
129
+ console.error(styleText('red', String(error?.message ?? error))),
130
+ );
131
+ console.log(`Watching ${relative(project.root)} for changes…`);
132
+ await new Promise(() => {});
133
+ }
134
+ const result = await generateBitaKit(project.root);
135
+ console.log(
136
+ `\nGenerated ${relative(result.generated)} (${result.framework === 'none' ? 'no framework provider' : result.framework}).${result.warnings.length ? ` ${result.warnings.length} warning${result.warnings.length === 1 ? '' : 's'} above.` : ''}\n`,
137
+ );
138
+ });
139
+
140
+ program
141
+ .command('migrate')
142
+ .option('--navigation-slot <name>', 'explicit target for legacy navigation group Actions')
143
+ .option('--dry-run', 'only list the changes')
144
+ .description(
145
+ 'Rewrite a 0.1 project to the current layout: bitakit.config.ts, folder-only files, ui/ folders, generated imports.',
146
+ )
147
+ .action(async (options) => {
148
+ // Only the root is needed: a 0.1 configuration may not even load before it is migrated.
149
+ const { root } = await findProjectRoot();
150
+ const { changes } = await migrateProject(root, {
151
+ dryRun: options.dryRun,
152
+ navigationSlot: options.navigationSlot,
153
+ });
154
+ if (!changes.length) {
155
+ console.log('\nNothing to migrate.\n');
156
+ return;
157
+ }
158
+ console.log(options.dryRun ? '\nWould change:' : '\nChanged:');
159
+ for (const change of changes)
160
+ console.log(
161
+ ` ${styleText(change.kind === 'skip' ? 'yellow' : 'green', change.kind.padEnd(7))} ${change.from}${change.to ? ` → ${change.to}` : ''}${change.detail ? styleText('dim', ` (${change.detail})`) : ''}`,
162
+ );
163
+ console.log(
164
+ options.dryRun
165
+ ? '\nRun without --dry-run to apply.\n'
166
+ : '\nReview the diff, then run "bitakit generate" and "bitakit doctor".\n',
167
+ );
168
+ });
169
+
170
+ program
171
+ .command('build')
172
+ .option('--check', 'only generate types and type-check, without writing dist')
173
+ .description('Build a plugin package: types, compiled sources and the dist/plugin.js entry.')
174
+ .action(async (options) => {
175
+ const result = await buildPlugin({ check: options.check });
176
+ const count = ['services', 'actions', 'pages']
177
+ .map((kind) => `${result.module[kind].length} ${kind}`)
178
+ .join(', ');
179
+ console.log(
180
+ options.check
181
+ ? `\nPlugin "${result.id}" type-checks (${count}).\n`
182
+ : `\nBuilt plugin "${result.id}" (${count}) into ${relative(result.dist)}.\nPublish it with npm publish; apps that install it discover it automatically.\n`,
183
+ );
184
+ });
185
+
186
+ program
187
+ .command('doctor')
188
+ .option('--json', 'machine-readable output')
189
+ .description(
190
+ 'Check versions, wiring, routes, links, service names, styles and deprecated layouts.',
191
+ )
192
+ .action(async (options) => {
193
+ const { project, results } = await doctor();
194
+ const errors = results.filter((result) => result.status === 'error').length;
195
+ const warnings = results.filter((result) => result.status === 'warn').length;
196
+ if (options.json) {
197
+ console.log(
198
+ JSON.stringify({ project: project.manifest.name, results, errors, warnings }, null, 2),
199
+ );
200
+ if (errors) process.exitCode = 1;
201
+ return;
202
+ }
203
+ console.log(`\nBitaKit doctor · ${project.manifest.name ?? relative(project.root)}\n`);
204
+ const symbols = {
205
+ ok: styleText('green', '✔'),
206
+ warn: styleText('yellow', '⚠'),
207
+ error: styleText('red', '✖'),
208
+ };
209
+ for (const result of results) {
210
+ console.log(`${symbols[result.status]} ${result.title}`);
211
+ for (const detail of result.details ?? []) console.log(` ${detail}`);
212
+ if (result.fix)
213
+ console.log(` ${styleText('cyan', 'Fix:')} ${result.fix.replaceAll('\n', '\n ')}`);
214
+ }
215
+ console.log(
216
+ `\n${errors ? `${errors} problem${errors === 1 ? '' : 's'}` : 'No problems'}${warnings ? `, ${warnings} warning${warnings === 1 ? '' : 's'}` : ''}.\n`,
217
+ );
218
+ if (errors) process.exitCode = 1;
219
+ });
220
+
221
+ program
222
+ .command('info')
223
+ .option('--json', 'machine-readable output')
224
+ .description('List the plugins, services, actions, events and pages discovery finds.')
225
+ .action(async (options) => {
226
+ const project = await findProject();
227
+ if (project.kind !== 'app') throw new Error('Run "bitakit info" inside an app.');
228
+ const description = await describeBitaKit(project.root);
229
+ const inventory = await inspectionFromDescription(description);
230
+ if (options.json) {
231
+ console.log(JSON.stringify(inventory, null, 2));
232
+ return;
233
+ }
234
+ for (const plugin of inventory.static.plugins) {
235
+ const title =
236
+ plugin.source.kind === 'package' ? `Package "${plugin.id}"` : `Plugin "${plugin.id}"`;
237
+ console.log(
238
+ `\n${styleText('bold', title)}${plugin.enabled === false ? ' (disabled)' : ''} ${styleText('dim', plugin.source.path ?? '')}`,
239
+ );
240
+ if (plugin.declarations === null)
241
+ console.log(' declarations: unavailable (static package entry)');
242
+ else
243
+ for (const kind of new Set(plugin.declarations.map((entry) => entry.kind)))
244
+ console.log(
245
+ ` ${kind}: ${plugin.declarations
246
+ .filter((entry) => entry.kind === kind)
247
+ .map((entry) => entry.id ?? entry.source)
248
+ .join(', ')}`,
249
+ );
250
+ }
251
+ console.log('\nLive state: unavailable (static discovery).');
252
+ if (description.warnings.length) {
253
+ console.log(
254
+ `\n${styleText('yellow', `${description.warnings.length} warning${description.warnings.length === 1 ? '' : 's'}`)}`,
255
+ );
256
+ for (const warning of description.warnings) console.log(` ${warning}`);
257
+ }
258
+ console.log('');
259
+ });
260
+
261
+ try {
262
+ await program.parseAsync();
263
+ } catch (error) {
264
+ console.error(styleText('red', error.message));
265
+ process.exitCode = 1;
266
+ }