@bitakit/cli 0.3.0 → 0.3.2
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 +34 -12
- package/README.md +37 -2
- package/package.json +3 -3
- package/skills/bitakit-app-development/README.md +4 -3
- package/skills/bitakit-app-development/SKILL.md +12 -7
- package/skills/bitakit-app-development/references/best-practices.md +2 -1
- package/skills/bitakit-app-development/references/data-and-api.md +118 -103
- package/skills/bitakit-app-development/references/layouts-and-screens.md +26 -0
- package/skills/bitakit-app-development/references/plugin-guides.md +1 -1
- package/skills/bitakit-app-development/references/server.md +383 -0
- package/src/add.mjs +188 -2
- package/src/agent-rules.mjs +7 -6
- package/src/cli.mjs +129 -5
- package/src/doctor.mjs +171 -2
- package/src/index.mjs +13 -2
- package/src/inventory.mjs +23 -12
- package/src/project.mjs +12 -0
- package/src/routes.mjs +115 -0
- package/src/server-boundary.mjs +550 -0
- package/src/shell.mjs +177 -0
- package/src/templates.mjs +136 -0
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
|
+
}
|
package/src/templates.mjs
CHANGED
|
@@ -524,6 +524,142 @@ export default defineInterceptor({
|
|
|
524
524
|
`;
|
|
525
525
|
}
|
|
526
526
|
|
|
527
|
+
/** `remote.todos.add` or `remote["user-notes"].archive` for an operation ID. */
|
|
528
|
+
const remotePath = (id) => `remote${id.split('.').map(member).join('')}`;
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* The operation `<plugin>.<name>` (`bitakit add action … --server`): a server Action in
|
|
532
|
+
* `server/actions/<name>.ts` that only organization members may call, exposed to the browser.
|
|
533
|
+
* `button` is the plugin's file that declares the button, relative to the plugin folder, when it
|
|
534
|
+
* already exists (`actions.ts`, `actions.add.ts`); by default `actions/<name>.ts`.
|
|
535
|
+
*/
|
|
536
|
+
export function serverActionFile(name, plugin, { button = `actions/${name}.ts` } = {}) {
|
|
537
|
+
const segments = name.split('/');
|
|
538
|
+
const id = `${plugin}.${segments.join('.')}`;
|
|
539
|
+
// A record file such as actions.ts declares the button under a key: "the button add in actions.ts".
|
|
540
|
+
const spelled = button
|
|
541
|
+
.replace(/\.[cm]?[jt]sx?$/, '')
|
|
542
|
+
.split(/[\\/.]/)
|
|
543
|
+
.slice(1);
|
|
544
|
+
const key = segments.slice(spelled.length);
|
|
545
|
+
const where =
|
|
546
|
+
spelled.join('.') === segments.join('.')
|
|
547
|
+
? `the button in ${button}`
|
|
548
|
+
: `the button ${key.join('.')} in ${button}`;
|
|
549
|
+
return `// The operation ${id}. It runs only on the server; ${where} calls it
|
|
550
|
+
// with ${remotePath(id)}(input). Tests: tests/${id}.server.test.ts.
|
|
551
|
+
import { defineAction } from '@bitakit/core/server';
|
|
552
|
+
import { z } from 'zod';
|
|
553
|
+
|
|
554
|
+
export default defineAction({
|
|
555
|
+
// Who may call it: 'public', 'user', 'organization' or { permission: { <resource>: ['<operation>'] } }.
|
|
556
|
+
access: 'organization',
|
|
557
|
+
// The browser may call it over HTTP; without expose it is callable on the server only.
|
|
558
|
+
expose: true,
|
|
559
|
+
input: z.object({ title: z.string().min(1) }),
|
|
560
|
+
// The caller receives exactly this shape; other keys are left out.
|
|
561
|
+
output: z.object({ title: z.string(), organizationId: z.string() }),
|
|
562
|
+
execute: ({ input, ctx }) => {
|
|
563
|
+
// Read and change data here, always scoped to ctx.organization.id.
|
|
564
|
+
return { title: input.title, organizationId: ctx.organization.id };
|
|
565
|
+
},
|
|
566
|
+
});
|
|
567
|
+
`;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/** The button for a server operation: a client Action that calls it through `remote`. */
|
|
571
|
+
export function remoteActionFile(name, plugin) {
|
|
572
|
+
const segments = name.split('/');
|
|
573
|
+
const id = `${plugin}.${segments.join('.')}`;
|
|
574
|
+
return `import { defineAction } from '@bitakit/core';
|
|
575
|
+
|
|
576
|
+
// The button. The operation runs on the server (server/actions/${name}.ts); remote calls it over HTTP.
|
|
577
|
+
export default defineAction<{ title: string }>({
|
|
578
|
+
title: '${titleOf(segments.at(-1))}',
|
|
579
|
+
execute: ({ input, remote }) => ${remotePath(id)}(input),
|
|
580
|
+
});
|
|
581
|
+
`;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/** A server service (`bitakit add service … --server`): logic shared by the plugin's operations. */
|
|
585
|
+
export function serverServiceFile(name, plugin) {
|
|
586
|
+
const id = `${plugin}.${name.split('/').join('.')}`;
|
|
587
|
+
return `import { defineService } from '@bitakit/core/server';
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* Server logic for this plugin's operations: services.${id} in server Actions, interceptors and
|
|
591
|
+
* other server services. One instance serves every request, so keep data per organization or
|
|
592
|
+
* user (ctx.organization.id), never in one shared field.
|
|
593
|
+
*/
|
|
594
|
+
export default defineService(() => {
|
|
595
|
+
const counts = new Map<string, number>();
|
|
596
|
+
return {
|
|
597
|
+
increment(organizationId: string) {
|
|
598
|
+
const next = (counts.get(organizationId) ?? 0) + 1;
|
|
599
|
+
counts.set(organizationId, next);
|
|
600
|
+
return next;
|
|
601
|
+
},
|
|
602
|
+
};
|
|
603
|
+
});
|
|
604
|
+
`;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/** A server interceptor (`bitakit add interceptor … --server`): runs around the plugin's operations. */
|
|
608
|
+
export function serverInterceptorFile(plugin, name) {
|
|
609
|
+
return `import { defineInterceptor } from '@bitakit/core/server';
|
|
610
|
+
|
|
611
|
+
// Runs around this plugin's server operations after the access and input checks, with the
|
|
612
|
+
// caller's ctx. Returning false refuses the call; after and onError only observe.
|
|
613
|
+
export default defineInterceptor({
|
|
614
|
+
action: '${plugin}.*',
|
|
615
|
+
before: ({ id, ctx }) => {
|
|
616
|
+
console.debug('[${plugin}] ${name}', id, ctx.user?.id ?? 'anonymous');
|
|
617
|
+
},
|
|
618
|
+
});
|
|
619
|
+
`;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* The test of one server operation (`bitakit add action … --server`), run from the app root with
|
|
624
|
+
* `node --test`: a member of the organization, a member of another one and a signed-out caller.
|
|
625
|
+
* `directory` is the plugin folder relative to that root; `id` is only needed when the folder is
|
|
626
|
+
* not under a `plugins` directory.
|
|
627
|
+
*/
|
|
628
|
+
export function serverTestFile(name, plugin, { directory, id }) {
|
|
629
|
+
const operation = `${plugin}.${name.split('/').join('.')}`;
|
|
630
|
+
const call = (caller) => `${caller}${operation.split('.').map(member).join('')}`;
|
|
631
|
+
return `import assert from 'node:assert/strict';
|
|
632
|
+
import { after, test } from 'node:test';
|
|
633
|
+
import { identity, mountServer } from '@bitakit/core/testing';
|
|
634
|
+
|
|
635
|
+
// The server half of ${plugin}, booted once; as() calls it as different people.
|
|
636
|
+
const server = await mountServer('${directory}'${id ? `, { id: '${id}' }` : ''});
|
|
637
|
+
after(() => server.stop());
|
|
638
|
+
|
|
639
|
+
test('a member of the organization can call ${operation}', async () => {
|
|
640
|
+
const member = server.as(identity({ organization: 'org-1' }));
|
|
641
|
+
assert.deepEqual(await ${call('member')}({ title: 'First' }), {
|
|
642
|
+
title: 'First',
|
|
643
|
+
organizationId: 'org-1',
|
|
644
|
+
});
|
|
645
|
+
});
|
|
646
|
+
|
|
647
|
+
test('a member of another organization works in that organization only', async () => {
|
|
648
|
+
const other = server.as(identity({ user: 'user-2', organization: 'org-2' }));
|
|
649
|
+
assert.equal((await ${call('other')}({ title: 'Theirs' })).organizationId, 'org-2');
|
|
650
|
+
// A page loaded for org-1 cannot write once the session has moved to org-2.
|
|
651
|
+
await assert.rejects(${call('other')}({ title: 'Stale' }, { organizationId: 'org-1' }), {
|
|
652
|
+
code: 'CONFLICT',
|
|
653
|
+
});
|
|
654
|
+
});
|
|
655
|
+
|
|
656
|
+
test('a signed-out caller is refused', async () => {
|
|
657
|
+
const anonymous = server.as(identity({ user: null }));
|
|
658
|
+
await assert.rejects(${call('anonymous')}({ title: 'Nope' }), { code: 'UNAUTHORIZED' });
|
|
659
|
+
});
|
|
660
|
+
`;
|
|
661
|
+
}
|
|
662
|
+
|
|
527
663
|
/**
|
|
528
664
|
* A headless test of one app plugin (`bitakit add test`), run from the app root with `node --test`.
|
|
529
665
|
* `directory` is the plugin folder relative to that root; `id` is only needed when the folder is
|