@bitakit/cli 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -18,6 +18,7 @@ checks a project. It also ships the `bitakit-app-development` skill, which `crea
18
18
  | `npx bitakit add test <plugin>` | A headless test, plus the setup commands it still needs |
19
19
  | `npx bitakit info --json` | Plugins, services, Actions, events, settings, pages |
20
20
  | `npx bitakit slots [--json]` | Every slot, its owner, contributions and, for replaceable parts, what renders |
21
+ | `npx bitakit shell [use <name>\|reset] [--part <id>]` | The app's frame (`layout.app`): candidates, what renders; `use` and `reset` write `choose` |
21
22
  | `npx bitakit doctor [--json]` | Wiring, versions, routes, links, slots, replaceable parts, agent files |
22
23
  | `npx bitakit check-page /<path> --json` | Opens the page headlessly and reports headings and errors (Playwright) |
23
24
  | `npx bitakit init --update-agent-files` | Refreshes AGENTS.md's BitaKit block and unedited skill copies |
package/README.md CHANGED
@@ -150,6 +150,8 @@ npx bitakit doctor # human-readable report, exit code 1 on problems
150
150
  npx bitakit doctor --json # for CI
151
151
  npx bitakit info [--json] # the plugins, services, actions, events and pages discovery finds
152
152
  npx bitakit slots [--json] # every slot you can fill: owner, accepts and this app's contributions
153
+ npx bitakit shell # the app's frame: what renders, the candidates, the choice
154
+ npx bitakit shell use <name> # pick a frame: writes choose in bitakit.config.ts (reset removes it)
153
155
  ```
154
156
 
155
157
  ### Explicit update checks
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bitakit/cli",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "BitaKit project commands: add plugins and contributions, check a project with doctor.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -105,6 +105,32 @@ widget of another plugin keeps working as long as the frame renders its slot (`T
105
105
  `shell.header.end` and `shell.toolbar`); check the pages that use header slots after replacing
106
106
  the frame.
107
107
 
108
+ ## Offer a frame as a shell, and switch shells
109
+
110
+ A shell is a plugin whose only job is the frame. Put the frame into the plugin instead of the app:
111
+ `src/plugins/<shell>/ui/layouts/app.tsx` is the candidate `<shell>:default`, and
112
+ `ui/layouts/app/<variant>.tsx` is `<shell>:<variant>`. A shell may offer the sign-in frame too
113
+ (`ui/layouts/auth.tsx`). A plugin package ships the same folders, so a shell can be installed.
114
+
115
+ - Render the common places, so every feature works in every shell: the navigation
116
+ (`shell.navigation`), the toolbar (`shell.toolbar`), the header regions (`shell.header.start`,
117
+ `.center`, `.end`), the brand (`shell.brand`) and the regions around the page
118
+ (`shell.content.before`, `.after`, `shell.footer`). Shell's parts render them for you.
119
+ - Features never name a shell: they put Actions and components into those places.
120
+
121
+ Look at the frames an app has and pick one:
122
+
123
+ ```sh
124
+ npx bitakit shell # what renders, the candidates, the choice
125
+ npx bitakit shell use <name> # "plugin:variant", a plugin or a variant
126
+ npx bitakit shell reset # back to the default
127
+ npx bitakit shell --part layout.auth # the same for another replaceable part
128
+ ```
129
+
130
+ `shell use` writes `choose: { 'layout.app': '<name>' }` into `bitakit.config.ts` and generates the
131
+ wiring again. Without a choice the app's own `src/layouts/app.tsx` wins; with several plugin
132
+ candidates and no choice the default renders and Doctor asks for one.
133
+
108
134
  ## Replace a screen
109
135
 
110
136
  ```tsx
package/src/cli.mjs CHANGED
@@ -12,6 +12,13 @@ import { doctor } from './doctor.mjs';
12
12
  import { initProject } from './init.mjs';
13
13
  import { findProject, findProjectRoot } from './project.mjs';
14
14
  import { describeSlots, formatSlots } from './slots.mjs';
15
+ import {
16
+ chooseCandidate,
17
+ describeShell,
18
+ formatShell,
19
+ framePart,
20
+ resolveCandidate,
21
+ } from './shell.mjs';
15
22
 
16
23
  const manifest = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
17
24
  const relative = (file) => path.relative(process.cwd(), file) || '.';
@@ -407,6 +414,81 @@ program
407
414
  console.log('');
408
415
  });
409
416
 
417
+ // The app's frame is the replaceable part `layout.app`; a shell is a candidate for it.
418
+ const shell = program
419
+ .command('shell')
420
+ .description(
421
+ "The app's frame (the replaceable part layout.app): see the shells this app can use and pick one.",
422
+ );
423
+ const partOption = ['--part <id>', 'another replaceable part, for example layout.auth', framePart];
424
+ const shellState = async (part) => {
425
+ const project = await findProject();
426
+ if (project.kind !== 'app') throw new Error('Run "bitakit shell" inside an app.');
427
+ const slots = await describeSlots(await describeBitaKit(project.root));
428
+ return { project, state: describeShell(slots, part) };
429
+ };
430
+ /** The generated wiring follows the choice at once; a failure there leaves the written choice in place. */
431
+ const regenerate = async (root) => {
432
+ try {
433
+ await generateBitaKit(root);
434
+ console.log('Generated the wiring again. A running dev server may need a restart.\n');
435
+ } catch (error) {
436
+ console.log(`The choice is written, but generating failed: ${error.message}\n`);
437
+ }
438
+ };
439
+
440
+ shell
441
+ .command('list', { isDefault: true })
442
+ .description('Show the frame that renders, the candidates and the choice in bitakit.config.ts.')
443
+ .option(...partOption)
444
+ .option('--json', 'machine-readable output')
445
+ .action(async (options) => {
446
+ const { state } = await shellState(options.part);
447
+ if (options.json) {
448
+ console.log(JSON.stringify(state, null, 2));
449
+ return;
450
+ }
451
+ console.log('');
452
+ for (const line of formatShell(state)) console.log(line);
453
+ console.log('');
454
+ });
455
+
456
+ shell
457
+ .command('use')
458
+ .argument('<name>', 'a candidate: "plugin:variant", a plugin or a variant')
459
+ .description(
460
+ "Choose the frame: writes choose: { 'layout.app': '<name>' } into bitakit.config.ts.",
461
+ )
462
+ .option(...partOption)
463
+ .action(async (name, options) => {
464
+ const { project, state } = await shellState(options.part);
465
+ if (!state.exists) throw new Error(formatShell(state).join(' '));
466
+ const candidate = resolveCandidate(state.candidates, name);
467
+ const { changed } = await chooseCandidate(project.root, options.part, candidate);
468
+ console.log(
469
+ changed
470
+ ? `\n${options.part} now uses ${candidate} (bitakit.config.ts).`
471
+ : `\n${options.part} already uses ${candidate}.\n`,
472
+ );
473
+ if (changed) await regenerate(project.root);
474
+ });
475
+
476
+ shell
477
+ .command('reset')
478
+ .description('Remove the choice, so the default frame (or the only candidate) renders again.')
479
+ .option(...partOption)
480
+ .action(async (options) => {
481
+ const project = await findProject();
482
+ if (project.kind !== 'app') throw new Error('Run "bitakit shell" inside an app.');
483
+ const { changed } = await chooseCandidate(project.root, options.part, undefined);
484
+ console.log(
485
+ changed
486
+ ? `\n${options.part} has no choice any more (bitakit.config.ts).`
487
+ : `\n${options.part} had no choice.\n`,
488
+ );
489
+ if (changed) await regenerate(project.root);
490
+ });
491
+
410
492
  try {
411
493
  await program.parseAsync();
412
494
  } catch (error) {
package/src/shell.mjs ADDED
@@ -0,0 +1,177 @@
1
+ import { readFile, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import ts from 'typescript';
4
+
5
+ /** The replaceable part that frames every normal page: the app's shell. */
6
+ export const framePart = 'layout.app';
7
+
8
+ /**
9
+ * One replaceable part as `describeSlots` reports it: the candidates an app can pick from, what
10
+ * renders now and what `bitakit.config.ts` chooses. `exists` is false when no installed package or
11
+ * plugin declares the part (an app without a frame).
12
+ */
13
+ export function describeShell(slots, part = framePart) {
14
+ const slot = slots.slots.find((entry) => entry.id === part);
15
+ const selection = slot?.selection;
16
+ return {
17
+ part,
18
+ exists: Boolean(slot),
19
+ owner: slot?.owner ?? null,
20
+ candidates: selection?.candidates ?? [],
21
+ renders: selection?.renders ?? null,
22
+ reason: selection?.reason ?? null,
23
+ choice: selection?.choice ?? null,
24
+ };
25
+ }
26
+
27
+ /** The short human listing of one part. */
28
+ export function formatShell(shell) {
29
+ if (!shell.exists)
30
+ return [
31
+ `No "${shell.part}" part exists in this app.`,
32
+ shell.part === framePart
33
+ ? 'Install a shell such as @bitakit/shell, or write src/layouts/app.tsx.'
34
+ : 'npx bitakit slots lists the parts this app has.',
35
+ ];
36
+ const fallback = shell.owner ? `the default of "${shell.owner}"` : 'the default';
37
+ return [
38
+ `${shell.part}`,
39
+ ` renders ${shell.renders ?? fallback}${shell.reason === 'ambiguous' ? ' (several candidates and no choice)' : shell.reason === 'choice-unavailable' ? ' (the choice names no candidate)' : ''}`,
40
+ ` candidates ${shell.candidates.length ? shell.candidates.join(', ') : 'none besides the default'}`,
41
+ ` chosen ${shell.choice ?? 'nothing in bitakit.config.ts'}`,
42
+ '',
43
+ `Use another: npx bitakit shell use <name>${shell.part === framePart ? '' : ` --part ${shell.part}`}`,
44
+ `The default: npx bitakit shell reset${shell.part === framePart ? '' : ` --part ${shell.part}`}`,
45
+ ];
46
+ }
47
+
48
+ /**
49
+ * The candidate a name means: `plugin:variant` exactly, a plugin with one candidate, or a variant
50
+ * that only one plugin offers. Throws with the candidates when the name fits none or several.
51
+ */
52
+ export function resolveCandidate(candidates, name) {
53
+ const matches = candidates.includes(name)
54
+ ? [name]
55
+ : candidates.filter((candidate) => {
56
+ const [plugin, variant] = candidate.split(':');
57
+ return plugin === name || variant === name;
58
+ });
59
+ if (matches.length === 1) return matches[0];
60
+ const list = candidates.length ? candidates.join(', ') : 'none';
61
+ throw new Error(
62
+ matches.length
63
+ ? `"${name}" fits several candidates: ${matches.join(', ')}. Name one exactly.`
64
+ : `No candidate "${name}". Candidates: ${list}.`,
65
+ );
66
+ }
67
+
68
+ const named = (node, name) =>
69
+ ts.isPropertyAssignment(node) &&
70
+ (ts.isIdentifier(node.name) || ts.isStringLiteral(node.name)) &&
71
+ node.name.text === name;
72
+
73
+ /** The object literal of `export default { … }` or `export default defineBitaKit({ … })`. */
74
+ function configObject(file) {
75
+ for (const statement of file.statements) {
76
+ if (!ts.isExportAssignment(statement) || statement.isExportEquals) continue;
77
+ let expression = statement.expression;
78
+ while (
79
+ ts.isParenthesizedExpression(expression) ||
80
+ ts.isAsExpression(expression) ||
81
+ ts.isSatisfiesExpression(expression)
82
+ )
83
+ expression = expression.expression;
84
+ if (ts.isCallExpression(expression) && expression.arguments[0])
85
+ expression = expression.arguments[0];
86
+ if (ts.isObjectLiteralExpression(expression)) return expression;
87
+ }
88
+ return undefined;
89
+ }
90
+
91
+ /** `source` with `text` as the first property of `object`, on its own line when the object spans lines. */
92
+ function withFirstProperty(source, file, object, text) {
93
+ const open = object.getStart(file) + 1;
94
+ const first = object.properties[0];
95
+ if (!first) return `${source.slice(0, open)} ${text} ${source.slice(object.getEnd() - 1)}`;
96
+ const gap = source.slice(open, first.getStart(file));
97
+ const lineBreak = gap.includes('\n');
98
+ const indent = lineBreak ? gap.slice(gap.lastIndexOf('\n') + 1) : '';
99
+ return lineBreak
100
+ ? `${source.slice(0, open)}\n${indent}${text},${source.slice(open)}`
101
+ : `${source.slice(0, open)} ${text},${source.slice(open)}`;
102
+ }
103
+
104
+ /** `source` without `property` of `object`, including the comma that belonged to it. */
105
+ function withoutProperty(source, file, object, property) {
106
+ const index = object.properties.indexOf(property);
107
+ const next = object.properties[index + 1];
108
+ if (next) return source.slice(0, property.getStart(file)) + source.slice(next.getStart(file));
109
+ const previous = object.properties[index - 1];
110
+ const from = previous ? previous.getEnd() : object.getStart(file) + 1;
111
+ // A trailing comma after the last property goes with it.
112
+ const after = source.slice(property.getEnd());
113
+ const comma = /^\s*,/.exec(after)?.[0].length ?? 0;
114
+ const tail = source.slice(property.getEnd() + comma);
115
+ // The only property: the braces close up again.
116
+ return source.slice(0, from) + (previous ? tail : tail.trimStart());
117
+ }
118
+
119
+ /**
120
+ * The text of a `bitakit.config.ts` with `choose[part]` set to `value`, or without it when `value`
121
+ * is undefined (an emptied `choose` is removed too). Everything else stays as written. Returns
122
+ * undefined when the file has no configuration object to edit, or `choose` is not an object
123
+ * literal: then the line has to be written by hand.
124
+ */
125
+ export function withChoice(source, part, value, fileName = 'bitakit.config.ts') {
126
+ const parse = (text) =>
127
+ ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
128
+ const file = parse(source);
129
+ const object = configObject(file);
130
+ if (!object) return undefined;
131
+ const choose = object.properties.find((property) => named(property, 'choose'));
132
+ const entry = `'${part}': '${value}'`;
133
+ if (!choose)
134
+ return value === undefined
135
+ ? source
136
+ : withFirstProperty(source, file, object, `choose: { ${entry} }`);
137
+ if (!ts.isObjectLiteralExpression(choose.initializer)) return undefined;
138
+ const choices = choose.initializer;
139
+ const current = choices.properties.find((property) => named(property, part));
140
+ if (value !== undefined) {
141
+ if (!current) return withFirstProperty(source, file, choices, entry);
142
+ return (
143
+ source.slice(0, current.initializer.getStart(file)) +
144
+ `'${value}'` +
145
+ source.slice(current.initializer.getEnd())
146
+ );
147
+ }
148
+ if (!current) return source;
149
+ if (choices.properties.length > 1) return withoutProperty(source, file, choices, current);
150
+ return withoutProperty(source, file, object, choose);
151
+ }
152
+
153
+ /**
154
+ * Writes the choice into the app's `bitakit.config.ts` (created when missing). Returns the file and
155
+ * whether it changed; throws with the line to add when the file cannot be edited safely.
156
+ */
157
+ export async function chooseCandidate(root, part, value) {
158
+ const file = path.join(root, 'bitakit.config.ts');
159
+ const source = await readFile(file, 'utf8').catch(() => undefined);
160
+ if (source === undefined) {
161
+ if (value === undefined) return { file, changed: false };
162
+ await writeFile(
163
+ file,
164
+ `import { defineBitaKit } from '@bitakit/discovery';\n\nexport default defineBitaKit({ choose: { '${part}': '${value}' } });\n`,
165
+ );
166
+ return { file, changed: true };
167
+ }
168
+ const next = withChoice(source, part, value);
169
+ if (next === undefined)
170
+ throw new Error(
171
+ value === undefined
172
+ ? `bitakit.config.ts could not be edited. Remove '${part}' from its choose entry by hand.`
173
+ : `bitakit.config.ts could not be edited. Add this to its configuration by hand: choose: { '${part}': '${value}' }`,
174
+ );
175
+ if (next !== source) await writeFile(file, next);
176
+ return { file, changed: next !== source };
177
+ }