@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/LICENSE +21 -0
- package/README.md +153 -2
- package/package.json +44 -4
- package/src/add.mjs +190 -0
- package/src/agent-rules.mjs +52 -0
- package/src/build.mjs +203 -0
- package/src/cli.mjs +266 -0
- package/src/doctor.mjs +908 -0
- package/src/index.mjs +30 -0
- package/src/init.mjs +254 -0
- package/src/inventory.mjs +126 -0
- package/src/project.mjs +97 -0
- package/src/routes.mjs +124 -0
- package/src/templates.mjs +530 -0
package/src/index.mjs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** Programmatic API shared by the `bitakit` CLI and the project generator. */
|
|
2
|
+
export { addPlugin, addContribution, writeNewFiles, contributionKinds } from './add.mjs';
|
|
3
|
+
export { agentRules, agentRulesBegin, agentRulesEnd, bitakitIdentity } from './agent-rules.mjs';
|
|
4
|
+
export { buildPlugin } from './build.mjs';
|
|
5
|
+
export { doctor } from './doctor.mjs';
|
|
6
|
+
export {
|
|
7
|
+
bitakitConfigFile,
|
|
8
|
+
gitignoreBlock,
|
|
9
|
+
initProject,
|
|
10
|
+
nextConfigFile,
|
|
11
|
+
nextConfigImport,
|
|
12
|
+
viteConfigImport,
|
|
13
|
+
wrapNextConfig,
|
|
14
|
+
} from './init.mjs';
|
|
15
|
+
export { findProject, findProjectRoot, packagePluginId } from './project.mjs';
|
|
16
|
+
export { appRoutes, catchAllRoute } from './routes.mjs';
|
|
17
|
+
export {
|
|
18
|
+
actionFile,
|
|
19
|
+
configFile,
|
|
20
|
+
eventsFile,
|
|
21
|
+
interceptorFile,
|
|
22
|
+
pageFile,
|
|
23
|
+
pluginFiles,
|
|
24
|
+
sampleFiles,
|
|
25
|
+
starterFiles,
|
|
26
|
+
serviceFile,
|
|
27
|
+
titleOf,
|
|
28
|
+
pascalOf,
|
|
29
|
+
validateName,
|
|
30
|
+
} from './templates.mjs';
|
package/src/init.mjs
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import ts from 'typescript';
|
|
4
|
+
import { agentRules, agentRulesBegin } from './agent-rules.mjs';
|
|
5
|
+
import { exists, findProject } from './project.mjs';
|
|
6
|
+
import { appRoutes, catchAllRoute, rootLayouts, shellGroup } from './routes.mjs';
|
|
7
|
+
|
|
8
|
+
// Wiring text shared with `create-bitakit-app`, which imports it from this package.
|
|
9
|
+
export const nextConfigImport = "import { withBitaKit } from '@bitakit/next/config';";
|
|
10
|
+
export const nextConfigFile = `${nextConfigImport}\n\nexport default withBitaKit({});\n`;
|
|
11
|
+
export const viteConfigImport = "import { bitakit } from '@bitakit/tanstack/config';";
|
|
12
|
+
export const bitakitConfigFile =
|
|
13
|
+
"import { defineBitaKit } from '@bitakit/discovery';\n\nexport default defineBitaKit({});\n";
|
|
14
|
+
export const gitignoreBlock = '# Generated by BitaKit discovery\nsrc/bitakit.gen.*\n';
|
|
15
|
+
|
|
16
|
+
const parse = (source, fileName) =>
|
|
17
|
+
ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true);
|
|
18
|
+
/** Applies `{ start, end?, insert }` edits from the end of the file, so earlier offsets stay valid. */
|
|
19
|
+
const apply = (source, edits) =>
|
|
20
|
+
[...edits]
|
|
21
|
+
.sort((a, b) => b.start - a.start)
|
|
22
|
+
.reduce(
|
|
23
|
+
(result, { start, end = start, insert }) =>
|
|
24
|
+
result.slice(0, start) + insert + result.slice(end),
|
|
25
|
+
source,
|
|
26
|
+
);
|
|
27
|
+
/** Adds an import after the last import (or directive) of a file. */
|
|
28
|
+
function importEdit(file, line) {
|
|
29
|
+
const last = file.statements
|
|
30
|
+
.filter(
|
|
31
|
+
(item) =>
|
|
32
|
+
ts.isImportDeclaration(item) ||
|
|
33
|
+
(ts.isExpressionStatement(item) && ts.isStringLiteral(item.expression)),
|
|
34
|
+
)
|
|
35
|
+
.at(-1);
|
|
36
|
+
return last ? { start: last.end, insert: `\n${line}` } : { start: 0, insert: `${line}\n` };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* `export default config;` becomes `export default withBitaKit(config);` with its import, keeping
|
|
41
|
+
* everything the framework scaffold configured (for example Tailwind's Turbopack loader rule).
|
|
42
|
+
* Returns undefined for shapes it cannot edit safely.
|
|
43
|
+
*/
|
|
44
|
+
export function wrapNextConfig(source, fileName) {
|
|
45
|
+
const file = parse(source, fileName);
|
|
46
|
+
const exported = file.statements.find(
|
|
47
|
+
(item) => ts.isExportAssignment(item) && !item.isExportEquals,
|
|
48
|
+
);
|
|
49
|
+
if (!exported) return undefined;
|
|
50
|
+
const { expression } = exported;
|
|
51
|
+
return apply(source, [
|
|
52
|
+
{
|
|
53
|
+
start: expression.getStart(file),
|
|
54
|
+
end: expression.end,
|
|
55
|
+
insert: `withBitaKit(${expression.getText(file)})`,
|
|
56
|
+
},
|
|
57
|
+
importEdit(file, nextConfigImport),
|
|
58
|
+
]);
|
|
59
|
+
}
|
|
60
|
+
/** Puts `bitakit()` first in the Vite `plugins` array. */
|
|
61
|
+
function addVitePlugin(source, fileName) {
|
|
62
|
+
const file = parse(source, fileName);
|
|
63
|
+
let array;
|
|
64
|
+
const visit = (node) => {
|
|
65
|
+
if (array) return;
|
|
66
|
+
if (
|
|
67
|
+
ts.isPropertyAssignment(node) &&
|
|
68
|
+
node.name.getText(file) === 'plugins' &&
|
|
69
|
+
ts.isArrayLiteralExpression(node.initializer)
|
|
70
|
+
)
|
|
71
|
+
array = node.initializer;
|
|
72
|
+
else ts.forEachChild(node, visit);
|
|
73
|
+
};
|
|
74
|
+
visit(file);
|
|
75
|
+
if (!array) return undefined;
|
|
76
|
+
const [first] = array.elements;
|
|
77
|
+
const start = first ? first.getStart(file) : array.getStart(file) + 1;
|
|
78
|
+
const lead = first ? source.slice(array.getStart(file) + 1, start) : '';
|
|
79
|
+
return apply(source, [
|
|
80
|
+
{ start, insert: first ? `bitakit(),${lead.includes('\n') ? lead : ' '}` : 'bitakit()' },
|
|
81
|
+
importEdit(file, viteConfigImport),
|
|
82
|
+
]);
|
|
83
|
+
}
|
|
84
|
+
/** Wraps `{children}` (or, in TanStack, `<Outlet />`) of the root layout in `<BitaKitProvider>`. */
|
|
85
|
+
function wrapLayout(source, fileName, specifier, framework) {
|
|
86
|
+
const file = parse(source, fileName);
|
|
87
|
+
const find = (matches) => {
|
|
88
|
+
let found;
|
|
89
|
+
const visit = (node) => {
|
|
90
|
+
if (found) return;
|
|
91
|
+
if (matches(node)) found = node;
|
|
92
|
+
else ts.forEachChild(node, visit);
|
|
93
|
+
};
|
|
94
|
+
visit(file);
|
|
95
|
+
return found;
|
|
96
|
+
};
|
|
97
|
+
const target =
|
|
98
|
+
find(
|
|
99
|
+
(node) =>
|
|
100
|
+
ts.isJsxExpression(node) &&
|
|
101
|
+
node.expression &&
|
|
102
|
+
ts.isIdentifier(node.expression) &&
|
|
103
|
+
node.expression.text === 'children',
|
|
104
|
+
) ??
|
|
105
|
+
(framework === 'tanstack'
|
|
106
|
+
? find((node) => ts.isJsxSelfClosingElement(node) && node.tagName.getText(file) === 'Outlet')
|
|
107
|
+
: undefined);
|
|
108
|
+
if (!target) return undefined;
|
|
109
|
+
return apply(source, [
|
|
110
|
+
{
|
|
111
|
+
start: target.getStart(file),
|
|
112
|
+
end: target.end,
|
|
113
|
+
insert: `<BitaKitProvider>${target.getText(file)}</BitaKitProvider>`,
|
|
114
|
+
},
|
|
115
|
+
importEdit(file, `import { BitaKitProvider } from '${specifier}';`),
|
|
116
|
+
]);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Wires an existing Next.js or TanStack Start app: `bitakit.config.ts`, the config wrapper or
|
|
121
|
+
* Vite plugin, the provider in the root layout, the catch-all route for plugin pages, the
|
|
122
|
+
* `.gitignore` entry and the agent rules in `AGENTS.md` (the same block create-app writes).
|
|
123
|
+
* Files that already carry the wiring are never touched.
|
|
124
|
+
* Returns `written` (absolute paths; `created` is false for an edited file), `skipped` with the
|
|
125
|
+
* reason for each, and the BitaKit packages the app still has to install.
|
|
126
|
+
*/
|
|
127
|
+
export async function initProject({ cwd } = {}) {
|
|
128
|
+
const project = await findProject(cwd);
|
|
129
|
+
if (project.kind !== 'app') throw new Error('Run "bitakit init" inside an app.');
|
|
130
|
+
if (!project.framework)
|
|
131
|
+
throw new Error(
|
|
132
|
+
'"bitakit init" wires Next.js and TanStack Start apps. Add next or @tanstack/react-start first.',
|
|
133
|
+
);
|
|
134
|
+
const written = [];
|
|
135
|
+
const skipped = [];
|
|
136
|
+
const at = (file) => path.join(project.root, file);
|
|
137
|
+
const read = (file) => readFile(file, 'utf8').catch(() => undefined);
|
|
138
|
+
const first = async (files) => {
|
|
139
|
+
for (const file of files) if (await exists(file)) return file;
|
|
140
|
+
};
|
|
141
|
+
const put = async (file, content, created = false) => {
|
|
142
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
143
|
+
await writeFile(file, content);
|
|
144
|
+
written.push({ file, created });
|
|
145
|
+
};
|
|
146
|
+
const skip = (file, reason) => skipped.push({ file, reason });
|
|
147
|
+
|
|
148
|
+
const configFile = at('bitakit.config.ts');
|
|
149
|
+
if (await exists(configFile)) skip(configFile, 'already exists');
|
|
150
|
+
else if (await exists(at('foundation.config.ts')))
|
|
151
|
+
skip(configFile, 'foundation.config.ts is the 0.1 name; run "npx bitakit migrate"');
|
|
152
|
+
else await put(configFile, bitakitConfigFile, true);
|
|
153
|
+
|
|
154
|
+
if (project.framework === 'next') {
|
|
155
|
+
const file =
|
|
156
|
+
(await first(['next.config.ts', 'next.config.mjs', 'next.config.js'].map(at))) ??
|
|
157
|
+
at('next.config.ts');
|
|
158
|
+
const source = await read(file);
|
|
159
|
+
if (source === undefined) await put(file, nextConfigFile, true);
|
|
160
|
+
else if (/withBitaKit/.test(source))
|
|
161
|
+
skip(file, 'already wraps the configuration with withBitaKit');
|
|
162
|
+
else if (/withFoundation/.test(source))
|
|
163
|
+
skip(file, 'uses the removed withFoundation; run "npx bitakit migrate"');
|
|
164
|
+
else {
|
|
165
|
+
const wrapped = wrapNextConfig(source, file);
|
|
166
|
+
if (wrapped) await put(file, wrapped);
|
|
167
|
+
else
|
|
168
|
+
skip(
|
|
169
|
+
file,
|
|
170
|
+
`no "export default" to wrap; use withBitaKit(<config>) from @bitakit/next/config`,
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
} else {
|
|
174
|
+
const file = at('vite.config.ts');
|
|
175
|
+
const source = await read(file);
|
|
176
|
+
if (source === undefined)
|
|
177
|
+
skip(file, 'not found; add bitakit() from @bitakit/tanstack/config to the Vite plugins');
|
|
178
|
+
else if (/\bbitakit\(/.test(source)) skip(file, 'already runs the BitaKit plugin');
|
|
179
|
+
else if (/\bfoundation\(/.test(source))
|
|
180
|
+
skip(file, 'uses the removed foundation() plugin; run "npx bitakit migrate"');
|
|
181
|
+
else {
|
|
182
|
+
const updated = addVitePlugin(source, file);
|
|
183
|
+
if (updated) await put(file, updated);
|
|
184
|
+
else skip(file, 'no plugins array; add bitakit() from @bitakit/tanstack/config to it');
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const layouts = rootLayouts(project).map(at);
|
|
189
|
+
const layout = await first(layouts);
|
|
190
|
+
if (!layout)
|
|
191
|
+
skip(layouts[0], 'not found; mount <BitaKitProvider> from the generated file around your app');
|
|
192
|
+
else {
|
|
193
|
+
const source = (await read(layout)) ?? '';
|
|
194
|
+
if (/bitakit\.gen|BitaKitProvider|BitaKitRuntimeProvider/.test(source))
|
|
195
|
+
skip(layout, 'already mounts the BitaKit provider');
|
|
196
|
+
else {
|
|
197
|
+
const relative = path
|
|
198
|
+
.relative(path.dirname(layout), path.join(project.appDirectory, 'bitakit.gen'))
|
|
199
|
+
.split(path.sep)
|
|
200
|
+
.join('/');
|
|
201
|
+
const specifier = relative.startsWith('.') ? relative : `./${relative}`;
|
|
202
|
+
const updated = wrapLayout(source, layout, specifier, project.framework);
|
|
203
|
+
if (updated) await put(layout, updated);
|
|
204
|
+
else skip(layout, 'no {children} to wrap; mount <BitaKitProvider> around your app');
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const group = await shellGroup(project);
|
|
209
|
+
const shell =
|
|
210
|
+
project.framework === 'next' ? Boolean(group) : await exists(at('src/routes/_app.tsx'));
|
|
211
|
+
const route = catchAllRoute(project, { shell, group });
|
|
212
|
+
const caught = (await appRoutes(project)).find(
|
|
213
|
+
(item) => item.catchAll && item.pattern.test('/bitakit-plugin-page'),
|
|
214
|
+
);
|
|
215
|
+
if (caught) skip(at(route.file), `${caught.file} already catches every path`);
|
|
216
|
+
else if (await exists(at(route.file))) skip(at(route.file), 'already exists');
|
|
217
|
+
else await put(at(route.file), route.content, true);
|
|
218
|
+
|
|
219
|
+
const ignored = await read(at('.gitignore'));
|
|
220
|
+
if (ignored?.includes('bitakit.gen'))
|
|
221
|
+
skip(at('.gitignore'), 'already ignores the generated files');
|
|
222
|
+
else
|
|
223
|
+
await put(
|
|
224
|
+
at('.gitignore'),
|
|
225
|
+
ignored === undefined ? gitignoreBlock : `${ignored.trimEnd()}\n\n${gitignoreBlock}`,
|
|
226
|
+
ignored === undefined,
|
|
227
|
+
);
|
|
228
|
+
|
|
229
|
+
const dependencies = { ...project.manifest.dependencies, ...project.manifest.devDependencies };
|
|
230
|
+
const agents = await read(at('AGENTS.md'));
|
|
231
|
+
if (agents?.includes(agentRulesBegin)) skip(at('AGENTS.md'), 'already has the BitaKit rules');
|
|
232
|
+
else {
|
|
233
|
+
// The framework's own route folder: src/app or app for Next.js, src/routes for TanStack Start.
|
|
234
|
+
const routes =
|
|
235
|
+
project.framework === 'next'
|
|
236
|
+
? (await exists(at('src/app')))
|
|
237
|
+
? 'src/app'
|
|
238
|
+
: 'app'
|
|
239
|
+
: 'src/routes';
|
|
240
|
+
const rules = agentRules({ routes, shell: Boolean(dependencies['@bitakit/shell']) });
|
|
241
|
+
await put(
|
|
242
|
+
at('AGENTS.md'),
|
|
243
|
+
agents === undefined ? rules : `${agents.trimEnd()}\n\n${rules}`,
|
|
244
|
+
agents === undefined,
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
const install = [
|
|
248
|
+
'@bitakit/core',
|
|
249
|
+
'@bitakit/discovery',
|
|
250
|
+
'@bitakit/ui',
|
|
251
|
+
project.framework === 'next' ? '@bitakit/next' : '@bitakit/tanstack',
|
|
252
|
+
].filter((name) => !dependencies[name]);
|
|
253
|
+
return { project, written, skipped, install };
|
|
254
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import ts from 'typescript';
|
|
4
|
+
import { createInventory } from '@bitakit/core';
|
|
5
|
+
import { describeDefinitions } from '@bitakit/discovery';
|
|
6
|
+
|
|
7
|
+
const kinds = {
|
|
8
|
+
services: 'service',
|
|
9
|
+
actions: 'action',
|
|
10
|
+
events: 'event',
|
|
11
|
+
settings: 'setting',
|
|
12
|
+
pages: 'page',
|
|
13
|
+
slots: 'widget',
|
|
14
|
+
slotDefinitions: 'slot',
|
|
15
|
+
providers: 'provider',
|
|
16
|
+
configs: 'config',
|
|
17
|
+
interceptors: 'interceptor',
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** The literal keys of the first object passed to `helper(...)` in the default export. */
|
|
21
|
+
async function recordKeys(file, helper) {
|
|
22
|
+
const tree = ts.createSourceFile(
|
|
23
|
+
file,
|
|
24
|
+
await readFile(file, 'utf8'),
|
|
25
|
+
ts.ScriptTarget.Latest,
|
|
26
|
+
true,
|
|
27
|
+
);
|
|
28
|
+
let keys;
|
|
29
|
+
const visit = (node) => {
|
|
30
|
+
if (keys) return;
|
|
31
|
+
if (
|
|
32
|
+
ts.isCallExpression(node) &&
|
|
33
|
+
ts.isIdentifier(node.expression) &&
|
|
34
|
+
node.expression.text === helper &&
|
|
35
|
+
node.arguments[0] &&
|
|
36
|
+
ts.isObjectLiteralExpression(node.arguments[0])
|
|
37
|
+
) {
|
|
38
|
+
const names = node.arguments[0].properties.map((item) =>
|
|
39
|
+
item.name && !ts.isComputedPropertyName(item.name) ? item.name.text : undefined,
|
|
40
|
+
);
|
|
41
|
+
keys = names.includes(undefined) ? null : names;
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
ts.forEachChild(node, visit);
|
|
45
|
+
};
|
|
46
|
+
visit(tree);
|
|
47
|
+
return keys ?? null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The IDs one contribution file declares, derived statically with the runtime's naming rules:
|
|
52
|
+
* Actions and services by path or record key, page URLs, slot targets, events and setting keys.
|
|
53
|
+
* Returns `null` when the file cannot be read statically; the inventory then keeps the file.
|
|
54
|
+
*/
|
|
55
|
+
async function idsOf(kind, entry, module, { root, app, slotDeclarations }) {
|
|
56
|
+
const file = path.join(root, entry.file);
|
|
57
|
+
const segments = entry.path ? entry.path.split('.') : [];
|
|
58
|
+
const prefix = app ? '' : module.id;
|
|
59
|
+
const join = (...parts) => parts.filter(Boolean).join('.');
|
|
60
|
+
if (kind === 'actions' || kind === 'services') {
|
|
61
|
+
const { definitions, unresolved } = await describeDefinitions([{ ...entry, file }], {
|
|
62
|
+
helper: kind === 'actions' ? 'defineAction' : 'defineService',
|
|
63
|
+
moduleId: prefix,
|
|
64
|
+
});
|
|
65
|
+
return unresolved.length || !definitions.length ? null : definitions.map((item) => item.id);
|
|
66
|
+
}
|
|
67
|
+
if (kind === 'pages')
|
|
68
|
+
return [`${app ? '' : `/${module.id}`}/${segments.join('/')}`.replace(/(.)\/$/, '$1')];
|
|
69
|
+
if (kind === 'slots') return [segments.join('.')];
|
|
70
|
+
if (kind === 'configs') return [module.id];
|
|
71
|
+
if (kind === 'slotDefinitions')
|
|
72
|
+
return slotDeclarations.filter((slot) => slot.file === entry.file).map((slot) => slot.id);
|
|
73
|
+
if (kind === 'events') {
|
|
74
|
+
const keys = await recordKeys(file, 'defineEvents');
|
|
75
|
+
return keys && keys.map((key) => join(module.id, key));
|
|
76
|
+
}
|
|
77
|
+
if (kind === 'settings') {
|
|
78
|
+
const keys = await recordKeys(file, 'defineSettings');
|
|
79
|
+
return keys && keys.map((key) => join(prefix, key));
|
|
80
|
+
}
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Static source evidence only: IDs a file declares are resolved where they can be read without
|
|
86
|
+
* running it; package plugins and dynamic files stay explicitly unresolved.
|
|
87
|
+
*/
|
|
88
|
+
export async function inspectionFromDescription(description) {
|
|
89
|
+
const plugins = [];
|
|
90
|
+
for (const module of [description.app, ...description.plugins]) {
|
|
91
|
+
const app = module === description.app;
|
|
92
|
+
const declarations = [];
|
|
93
|
+
for (const [key, kind] of Object.entries(kinds))
|
|
94
|
+
for (const entry of module[key] ?? []) {
|
|
95
|
+
const ids = await idsOf(key, entry, module, {
|
|
96
|
+
root: description.root,
|
|
97
|
+
app,
|
|
98
|
+
slotDeclarations: description.slotDeclarations,
|
|
99
|
+
}).catch(() => null);
|
|
100
|
+
if (ids?.length)
|
|
101
|
+
for (const id of ids)
|
|
102
|
+
declarations.push({ kind, id, source: entry.file, resolution: 'resolved' });
|
|
103
|
+
else declarations.push({ kind, id: null, source: entry.file, resolution: 'file' });
|
|
104
|
+
}
|
|
105
|
+
plugins.push({
|
|
106
|
+
id: module.id,
|
|
107
|
+
pluginId: module.id,
|
|
108
|
+
enabled: module.enabled ?? true,
|
|
109
|
+
source: { kind: 'file', path: module.directory },
|
|
110
|
+
metadata: {},
|
|
111
|
+
dependencies: module.dependencies ?? [],
|
|
112
|
+
declarations,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
for (const specifier of description.packages)
|
|
116
|
+
plugins.push({
|
|
117
|
+
id: specifier,
|
|
118
|
+
pluginId: null,
|
|
119
|
+
enabled: description.catalogPackages?.includes(specifier) ? null : true,
|
|
120
|
+
source: { kind: 'package', path: specifier },
|
|
121
|
+
metadata: {},
|
|
122
|
+
dependencies: null,
|
|
123
|
+
declarations: null,
|
|
124
|
+
});
|
|
125
|
+
return createInventory(plugins);
|
|
126
|
+
}
|
package/src/project.mjs
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { access, readFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { loadDiscoveryConfig } from '@bitakit/discovery';
|
|
4
|
+
|
|
5
|
+
/** The nearest package.json above `cwd`: the project root and its manifest, without reading any configuration. */
|
|
6
|
+
export async function findProjectRoot(cwd = process.cwd()) {
|
|
7
|
+
let directory = path.resolve(cwd);
|
|
8
|
+
for (;;) {
|
|
9
|
+
const file = path.join(directory, 'package.json');
|
|
10
|
+
const manifest = await readFile(file, 'utf8').then(JSON.parse, (error) => {
|
|
11
|
+
if (error.code === 'ENOENT') return undefined;
|
|
12
|
+
throw error;
|
|
13
|
+
});
|
|
14
|
+
if (manifest) return { root: directory, manifest };
|
|
15
|
+
const parent = path.dirname(directory);
|
|
16
|
+
if (parent === directory)
|
|
17
|
+
throw new Error('No package.json found. Run this command inside a BitaKit app or plugin.');
|
|
18
|
+
directory = parent;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The project around a working directory: an application (plugins live in its plugin
|
|
24
|
+
* directory) or a standalone plugin package (contributions live in `src`).
|
|
25
|
+
*/
|
|
26
|
+
export async function findProject(cwd = process.cwd()) {
|
|
27
|
+
const { root, manifest } = await findProjectRoot(cwd);
|
|
28
|
+
return describeProject(root, manifest);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function describeProject(root, manifest) {
|
|
32
|
+
const dependencies = { ...manifest.dependencies, ...manifest.devDependencies };
|
|
33
|
+
const framework = dependencies.next
|
|
34
|
+
? 'next'
|
|
35
|
+
: dependencies['@tanstack/react-start'] || dependencies['@tanstack/react-router']
|
|
36
|
+
? 'tanstack'
|
|
37
|
+
: undefined;
|
|
38
|
+
const metadata = manifest.bitakit ?? manifest.foundation;
|
|
39
|
+
// A package that publishes a plugin entry is itself the plugin.
|
|
40
|
+
if (metadata?.plugin && !framework)
|
|
41
|
+
return {
|
|
42
|
+
kind: 'plugin',
|
|
43
|
+
root,
|
|
44
|
+
manifest,
|
|
45
|
+
metadata,
|
|
46
|
+
pluginId: metadata.id ?? packagePluginId(manifest.name),
|
|
47
|
+
moduleRoot: path.join(root, 'src'),
|
|
48
|
+
};
|
|
49
|
+
// A configuration that cannot be evaluated (for example a 0.1 file importing a removed export)
|
|
50
|
+
// still describes a project: commands that need it rethrow `configError`, doctor reports it.
|
|
51
|
+
let loaded;
|
|
52
|
+
let configError;
|
|
53
|
+
try {
|
|
54
|
+
// The CLI still reads the 0.1 file so doctor and migrate can report what it needs.
|
|
55
|
+
loaded = await loadDiscoveryConfig(root, undefined, ['bitakit.config.ts', 'foundation.config.ts']);
|
|
56
|
+
} catch (error) {
|
|
57
|
+
configError = error;
|
|
58
|
+
const legacy =
|
|
59
|
+
(await exists(path.join(root, 'foundation.config.ts'))) &&
|
|
60
|
+
!(await exists(path.join(root, 'bitakit.config.ts')));
|
|
61
|
+
loaded = {
|
|
62
|
+
config: {},
|
|
63
|
+
file: path.join(root, legacy ? 'foundation.config.ts' : 'bitakit.config.ts'),
|
|
64
|
+
legacy,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
const { config, file, legacy } = loaded;
|
|
68
|
+
return {
|
|
69
|
+
kind: 'app',
|
|
70
|
+
root,
|
|
71
|
+
manifest,
|
|
72
|
+
framework,
|
|
73
|
+
configFile: file,
|
|
74
|
+
legacyConfig: legacy,
|
|
75
|
+
configError,
|
|
76
|
+
pluginsDirectory: path.resolve(root, config.plugins?.directory ?? './src/plugins'),
|
|
77
|
+
appDirectory: path.resolve(root, config.directory ?? './src'),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** `@acme/bitakit-notes` → `notes`; the package manifest may set `bitakit.id` explicitly. */
|
|
82
|
+
export function packagePluginId(name = '') {
|
|
83
|
+
return (
|
|
84
|
+
name
|
|
85
|
+
.replace(/^@[^/]+\//, '')
|
|
86
|
+
.replace(/^bitakit-(plugin-)?/, '')
|
|
87
|
+
.replace(/-plugin$/, '')
|
|
88
|
+
.replace(/[^a-z0-9-]/g, '-') || 'plugin'
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function exists(file) {
|
|
93
|
+
return access(file).then(
|
|
94
|
+
() => true,
|
|
95
|
+
() => false,
|
|
96
|
+
);
|
|
97
|
+
}
|
package/src/routes.mjs
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { readdir, readFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { exists } from './project.mjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* URL patterns of the routes the app's framework owns, approximated from file-based routing.
|
|
7
|
+
* Each route: `{ file, pattern, catchAll }`. Used for diagnostics only.
|
|
8
|
+
*/
|
|
9
|
+
export async function appRoutes(project) {
|
|
10
|
+
if (project.framework === 'next') return nextRoutes(project.root);
|
|
11
|
+
if (project.framework === 'tanstack') return tanstackRoutes(project.root);
|
|
12
|
+
return [];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function walk(directory) {
|
|
16
|
+
const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
|
|
17
|
+
const result = [];
|
|
18
|
+
for (const entry of entries) {
|
|
19
|
+
const file = path.join(directory, entry.name);
|
|
20
|
+
if (entry.isDirectory()) {
|
|
21
|
+
if (entry.name !== 'node_modules') result.push(...(await walk(file)));
|
|
22
|
+
} else result.push(file);
|
|
23
|
+
}
|
|
24
|
+
return result;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const toPattern = (parts, catchAll) =>
|
|
28
|
+
new RegExp(
|
|
29
|
+
`^${parts.length ? parts.map((part) => `/${part}`).join('') : catchAll ? '' : '/'}${catchAll ? '(?:/.*)?' : '/?'}$`,
|
|
30
|
+
);
|
|
31
|
+
const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
32
|
+
|
|
33
|
+
async function nextRoutes(root) {
|
|
34
|
+
const appDirectory = (await exists(path.join(root, 'src/app')))
|
|
35
|
+
? path.join(root, 'src/app')
|
|
36
|
+
: path.join(root, 'app');
|
|
37
|
+
const routes = [];
|
|
38
|
+
for (const file of await walk(appDirectory)) {
|
|
39
|
+
if (!/^(page|route)\.(tsx|ts|jsx|js|mdx)$/.test(path.basename(file))) continue;
|
|
40
|
+
const segments = path
|
|
41
|
+
.relative(appDirectory, path.dirname(file))
|
|
42
|
+
.split(path.sep)
|
|
43
|
+
.filter(Boolean);
|
|
44
|
+
// Parallel slots and intercepting routes mirror other routes.
|
|
45
|
+
if (segments.some((segment) => segment.startsWith('@') || /^\(\.+\)/.test(segment))) continue;
|
|
46
|
+
const parts = [];
|
|
47
|
+
let catchAll = false;
|
|
48
|
+
for (const segment of segments) {
|
|
49
|
+
if (/^\(.+\)$/.test(segment)) continue;
|
|
50
|
+
if (/^\[\[?\.\.\..+\]\]?$/.test(segment)) {
|
|
51
|
+
catchAll = true;
|
|
52
|
+
break;
|
|
53
|
+
}
|
|
54
|
+
parts.push(/^\[.+\]$/.test(segment) ? '[^/]+' : escape(segment));
|
|
55
|
+
}
|
|
56
|
+
routes.push({ file: path.relative(root, file), pattern: toPattern(parts, catchAll), catchAll });
|
|
57
|
+
}
|
|
58
|
+
return routes;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function tanstackRoutes(root) {
|
|
62
|
+
const directory = path.join(root, 'src/routes');
|
|
63
|
+
const routes = [];
|
|
64
|
+
for (const file of await walk(directory)) {
|
|
65
|
+
if (!/\.(tsx|ts|jsx|js)$/.test(file) || /\.d\.ts$/.test(file)) continue;
|
|
66
|
+
const relative = path.relative(directory, file).replace(/\.(tsx|ts|jsx|js)$/, '');
|
|
67
|
+
const tokens = relative.split(/[\\/.]/).filter(Boolean);
|
|
68
|
+
if (tokens[0] === '__root' || tokens.some((token) => token.startsWith('-'))) continue;
|
|
69
|
+
const parts = [];
|
|
70
|
+
let catchAll = false;
|
|
71
|
+
for (const token of tokens) {
|
|
72
|
+
if (token === 'index' || token === 'route' || token.startsWith('_') || /^\(.+\)$/.test(token))
|
|
73
|
+
continue;
|
|
74
|
+
if (token === '$') {
|
|
75
|
+
catchAll = true;
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
parts.push(token.startsWith('$') ? '[^/]+' : escape(token.replace(/^\[(.*)\]$/, '$1')));
|
|
79
|
+
}
|
|
80
|
+
routes.push({ file: path.relative(root, file), pattern: toPattern(parts, catchAll), catchAll });
|
|
81
|
+
}
|
|
82
|
+
return routes;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The route file a framework adapter needs so plugin pages render, with its content. */
|
|
86
|
+
export function catchAllRoute(project, { shell, group = '(app)' }) {
|
|
87
|
+
if (project.framework === 'tanstack')
|
|
88
|
+
return {
|
|
89
|
+
file: shell ? 'src/routes/_app/$.tsx' : 'src/routes/$.tsx',
|
|
90
|
+
content: `import { createFileRoute } from '@tanstack/react-router';
|
|
91
|
+
import { PluginPage } from '@bitakit/ui';
|
|
92
|
+
|
|
93
|
+
export const Route = createFileRoute('${shell ? '/_app/$' : '/$'}')({ component: () => <PluginPage /> });
|
|
94
|
+
`,
|
|
95
|
+
};
|
|
96
|
+
return {
|
|
97
|
+
file: shell ? `src/app/${group}/[...path]/page.tsx` : 'src/app/[...path]/page.tsx',
|
|
98
|
+
content: `'use client';
|
|
99
|
+
import { PluginPage } from '@bitakit/ui';
|
|
100
|
+
|
|
101
|
+
export default function Page() {
|
|
102
|
+
return <PluginPage />;
|
|
103
|
+
}
|
|
104
|
+
`,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The root layout files that mount the provider, per framework. */
|
|
109
|
+
export const rootLayouts = (project) =>
|
|
110
|
+
project.framework === 'tanstack'
|
|
111
|
+
? ['src/routes/__root.tsx']
|
|
112
|
+
: ['src/app/layout.tsx', 'app/layout.tsx'];
|
|
113
|
+
|
|
114
|
+
/** The Next route group whose layout renders `AppShell`, such as `(app)`; plugin pages belong in it. */
|
|
115
|
+
export async function shellGroup(project) {
|
|
116
|
+
if (project.framework !== 'next') return undefined;
|
|
117
|
+
const app = path.join(project.root, 'src/app');
|
|
118
|
+
for (const entry of await readdir(app, { withFileTypes: true }).catch(() => [])) {
|
|
119
|
+
if (!entry.isDirectory() || !/^\(.+\)$/.test(entry.name)) continue;
|
|
120
|
+
const layout = await readFile(path.join(app, entry.name, 'layout.tsx'), 'utf8').catch(() => '');
|
|
121
|
+
if (layout.includes('AppShell')) return entry.name;
|
|
122
|
+
}
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|