@bitakit/cli 0.3.1 → 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.
@@ -0,0 +1,550 @@
1
+ import { readdir, readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import ts from 'typescript';
4
+
5
+ const extensions = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'];
6
+ const sourceFile = /\.[cm]?[jt]sx?$/;
7
+ const declarationFile = /\.d\.[cm]?ts$/;
8
+ const generatedServer = /(?:^|[\\/])bitakit\.gen\.server(?:\.[cm]?[jt]sx?)?$/;
9
+ const serverEntry = /^@bitakit\/core\/server(?:\/|$)/;
10
+ const uiPackages = /^(?:react|react-dom|@bitakit\/ui)(?:\/|$)/;
11
+ /** Folders that hold no app source: dependencies and build output (dot folders are skipped too). */
12
+ const outside = new Set(['node_modules', 'dist', 'build', 'out', 'coverage']);
13
+ /** How many problems a result lists before it summarizes the rest. */
14
+ const shown = 20;
15
+
16
+ async function walk(directory) {
17
+ const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
18
+ const found = [];
19
+ for (const entry of entries) {
20
+ if (entry.name.startsWith('.') || outside.has(entry.name)) continue;
21
+ const file = path.join(directory, entry.name);
22
+ if (entry.isDirectory()) found.push(...(await walk(file)));
23
+ else if (sourceFile.test(entry.name) && !declarationFile.test(entry.name)) found.push(file);
24
+ }
25
+ return found;
26
+ }
27
+
28
+ const parse = (file, code, parents = false) =>
29
+ ts.createSourceFile(
30
+ file,
31
+ code,
32
+ ts.ScriptTarget.Latest,
33
+ parents,
34
+ /x$/.test(file) ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
35
+ );
36
+ const typeOnly = (elements) => elements.length > 0 && elements.every((item) => item.isTypeOnly);
37
+ const typeScriptFile = /\.[cm]?tsx?$/;
38
+
39
+ /** A property's name when it is written as an identifier or a string. */
40
+ const nameOf = (node) =>
41
+ node && (ts.isIdentifier(node) || ts.isStringLiteralLike(node)) ? node.text : undefined;
42
+
43
+ /** The identifier a call chain starts with: `createServerFn` in `createServerFn().handler(fn)`. */
44
+ function chainRoot(expression) {
45
+ let current = expression;
46
+ while (
47
+ ts.isCallExpression(current) ||
48
+ ts.isPropertyAccessExpression(current) ||
49
+ ts.isParenthesizedExpression(current) ||
50
+ ts.isNonNullExpression(current)
51
+ )
52
+ current = current.expression;
53
+ return ts.isIdentifier(current) ? current.text : undefined;
54
+ }
55
+
56
+ /** TanStack route factories whose options' `server` part Start keeps out of the browser. */
57
+ const routeFactories = new Set([
58
+ 'createFileRoute',
59
+ 'createRootRoute',
60
+ 'createRootRouteWithContext',
61
+ 'createRoute',
62
+ ]);
63
+
64
+ /**
65
+ * Whether `node` is code TanStack Start removes from the browser bundle: the `server` part of
66
+ * route options (`createFileRoute('/x')({ server: { handlers } })`), the function of
67
+ * `createServerFn(...).handler(fn)` and `createServerOnlyFn(fn)`, the `.server(fn)` of
68
+ * `createIsomorphicFn()` and `createMiddleware()`, and the handlers of older Start releases'
69
+ * `createServerFileRoute(...).methods(...)`.
70
+ */
71
+ function inServerOnlyCode(node) {
72
+ for (let current = node; current.parent; current = current.parent) {
73
+ const parent = current.parent;
74
+ if (
75
+ ts.isPropertyAssignment(parent) &&
76
+ parent.initializer === current &&
77
+ nameOf(parent.name) === 'server' &&
78
+ ts.isCallExpression(parent.parent.parent) &&
79
+ parent.parent.parent.arguments[0] === parent.parent &&
80
+ routeFactories.has(chainRoot(parent.parent.parent.expression))
81
+ )
82
+ return true;
83
+ if (ts.isCallExpression(parent) && parent.arguments.includes(current)) {
84
+ const callee = parent.expression;
85
+ const method = ts.isPropertyAccessExpression(callee) ? callee.name.text : undefined;
86
+ const root = chainRoot(callee);
87
+ if (
88
+ (ts.isIdentifier(callee) && callee.text === 'createServerOnlyFn') ||
89
+ (method === 'handler' && root === 'createServerFn') ||
90
+ (method === 'methods' && root === 'createServerFileRoute') ||
91
+ (method === 'server' && (root === 'createIsomorphicFn' || root === 'createMiddleware'))
92
+ )
93
+ return true;
94
+ }
95
+ }
96
+ return false;
97
+ }
98
+
99
+ /** Whether an identifier sits in a type: an annotation, `typeof x` in a type, `implements`. */
100
+ function inType(node) {
101
+ for (let current = node; current.parent; current = current.parent) {
102
+ const parent = current.parent;
103
+ if (ts.isExpressionWithTypeArguments(parent)) {
104
+ const clause = parent.parent;
105
+ // `class A extends B` needs B at run time; `implements` and interface `extends` do not.
106
+ return !(
107
+ ts.isHeritageClause(clause) &&
108
+ clause.token === ts.SyntaxKind.ExtendsKeyword &&
109
+ (ts.isClassDeclaration(clause.parent) || ts.isClassExpression(clause.parent))
110
+ );
111
+ }
112
+ if (
113
+ ts.isTypeNode(parent) ||
114
+ ts.isTypeAliasDeclaration(parent) ||
115
+ ts.isInterfaceDeclaration(parent)
116
+ )
117
+ return true;
118
+ }
119
+ return false;
120
+ }
121
+
122
+ /** Whether an identifier refers to a binding, rather than naming a property or declaring one. */
123
+ function isReference(node) {
124
+ const parent = node.parent;
125
+ if (
126
+ ((ts.isPropertyAccessExpression(parent) || ts.isQualifiedName(parent)) &&
127
+ (parent.name ?? parent.right) === node) ||
128
+ ts.isImportSpecifier(parent) ||
129
+ ts.isImportClause(parent) ||
130
+ ts.isNamespaceImport(parent) ||
131
+ ts.isImportEqualsDeclaration(parent) ||
132
+ ts.isLabeledStatement(parent) ||
133
+ ts.isBreakOrContinueStatement(parent) ||
134
+ ts.isMetaProperty(parent) ||
135
+ (ts.isBindingElement(parent) && parent.propertyName === node)
136
+ )
137
+ return false;
138
+ if (ts.isExportSpecifier(parent))
139
+ // `export { a as b }` refers to the local a; `export { a } from 'x'` to nothing here.
140
+ return !parent.parent.parent.moduleSpecifier && (parent.propertyName ?? parent.name) === node;
141
+ return !(
142
+ 'name' in parent &&
143
+ parent.name === node &&
144
+ !ts.isShorthandPropertyAssignment(parent) &&
145
+ !ts.isJsxOpeningLikeElement(parent)
146
+ );
147
+ }
148
+
149
+ /** Whether a top-level statement is exported (`export const`, `export function`). */
150
+ const exported = (statement) =>
151
+ statement.modifiers?.some((item) => item.kind === ts.SyntaxKind.ExportKeyword) ?? false;
152
+
153
+ /**
154
+ * Which local import bindings the browser keeps. A binding counts when an identifier refers to
155
+ * it outside a type position (`elide`: TypeScript, SWC and esbuild drop imports used only as
156
+ * types unless `verbatimModuleSyntax` keeps them) and, with `serverOnly`, outside code TanStack
157
+ * Start removes (see `inServerOnlyCode`); a reference inside a top-level declaration that is not
158
+ * exported counts only while that declaration counts, as Start's dead-code elimination drops
159
+ * declarations nothing else uses. Shadowing is ignored, so a local of the same name counts.
160
+ */
161
+ function usedBindings(tree, names, { elide, serverOnly }) {
162
+ const owners = new Map();
163
+ if (serverOnly)
164
+ for (const statement of tree.statements) {
165
+ if (exported(statement)) continue;
166
+ if (ts.isVariableStatement(statement))
167
+ for (const declaration of statement.declarationList.declarations) {
168
+ if (ts.isIdentifier(declaration.name) && declaration.initializer)
169
+ owners.set(declaration.initializer, declaration.name.text);
170
+ }
171
+ else if (ts.isFunctionDeclaration(statement) && statement.name && statement.body)
172
+ owners.set(statement.body, statement.name.text);
173
+ }
174
+ const local = new Set(owners.values());
175
+ /** Each reference to an import or a local declaration: `{ name, owner }`. */
176
+ const references = [];
177
+ const visit = (node, owner) => {
178
+ owner = owners.get(node) ?? owner;
179
+ if (
180
+ ts.isIdentifier(node) &&
181
+ (names.has(node.text) || local.has(node.text)) &&
182
+ isReference(node) &&
183
+ !(elide && inType(node)) &&
184
+ !(serverOnly && inServerOnlyCode(node))
185
+ )
186
+ references.push({ name: node.text, owner });
187
+ ts.forEachChild(node, (child) => visit(child, owner));
188
+ };
189
+ visit(tree, undefined);
190
+ const used = new Set();
191
+ for (let changed = true; changed; ) {
192
+ changed = false;
193
+ for (const { name, owner } of references)
194
+ if (!used.has(name) && (owner === undefined || used.has(owner))) {
195
+ used.add(name);
196
+ changed = true;
197
+ }
198
+ }
199
+ return used;
200
+ }
201
+
202
+ /**
203
+ * The modules a source file loads at run time: static imports and re-exports, `import x =
204
+ * require()`, `import()` and `require()` with a literal specifier. Type-only imports and exports
205
+ * (`import type`, `import { type A }`) are left out: they disappear from the browser bundle.
206
+ * `elide` (TypeScript files without `verbatimModuleSyntax`) also leaves out a named, default or
207
+ * namespace import none of whose bindings is used as a value, as the compiler drops it;
208
+ * `serverOnly` (TanStack Start) one used only in code Start keeps on the server.
209
+ */
210
+ export function valueImports(file, code, { elide = false, serverOnly = false } = {}) {
211
+ elide &&= typeScriptFile.test(file);
212
+ const tree = parse(file, code, elide || serverOnly);
213
+ const found = [];
214
+ const bindings = [];
215
+ for (const statement of tree.statements) {
216
+ if (ts.isImportDeclaration(statement)) {
217
+ const clause = statement.importClause;
218
+ if (
219
+ clause?.isTypeOnly ||
220
+ (clause &&
221
+ !clause.name &&
222
+ clause.namedBindings &&
223
+ ts.isNamedImports(clause.namedBindings) &&
224
+ typeOnly(clause.namedBindings.elements))
225
+ )
226
+ continue;
227
+ if (!ts.isStringLiteral(statement.moduleSpecifier)) continue;
228
+ const names = !clause
229
+ ? []
230
+ : [
231
+ ...(clause.name ? [clause.name.text] : []),
232
+ ...(clause.namedBindings && ts.isNamespaceImport(clause.namedBindings)
233
+ ? [clause.namedBindings.name.text]
234
+ : (clause.namedBindings?.elements ?? [])
235
+ .filter((item) => !item.isTypeOnly)
236
+ .map((item) => item.name.text)),
237
+ ];
238
+ // A side-effect import (`import './x'`) always loads.
239
+ if ((elide || serverOnly) && names.length)
240
+ bindings.push({ specifier: statement.moduleSpecifier.text, names });
241
+ else found.push(statement.moduleSpecifier.text);
242
+ } else if (ts.isExportDeclaration(statement) && statement.moduleSpecifier) {
243
+ if (
244
+ statement.isTypeOnly ||
245
+ (statement.exportClause &&
246
+ ts.isNamedExports(statement.exportClause) &&
247
+ typeOnly(statement.exportClause.elements))
248
+ )
249
+ continue;
250
+ if (ts.isStringLiteral(statement.moduleSpecifier)) found.push(statement.moduleSpecifier.text);
251
+ } else if (
252
+ ts.isImportEqualsDeclaration(statement) &&
253
+ !statement.isTypeOnly &&
254
+ ts.isExternalModuleReference(statement.moduleReference) &&
255
+ ts.isStringLiteral(statement.moduleReference.expression)
256
+ )
257
+ found.push(statement.moduleReference.expression.text);
258
+ }
259
+ if (bindings.length) {
260
+ const used = usedBindings(tree, new Set(bindings.flatMap((item) => item.names)), {
261
+ elide,
262
+ serverOnly,
263
+ });
264
+ for (const { specifier, names } of bindings)
265
+ if (names.some((name) => used.has(name))) found.push(specifier);
266
+ }
267
+ if (/\b(?:import|require)\s*\(/.test(code)) {
268
+ const visit = (node) => {
269
+ if (
270
+ ts.isCallExpression(node) &&
271
+ (node.expression.kind === ts.SyntaxKind.ImportKeyword ||
272
+ (ts.isIdentifier(node.expression) && node.expression.text === 'require')) &&
273
+ node.arguments[0] &&
274
+ ts.isStringLiteralLike(node.arguments[0]) &&
275
+ !(serverOnly && inServerOnlyCode(node))
276
+ )
277
+ found.push(node.arguments[0].text);
278
+ ts.forEachChild(node, visit);
279
+ };
280
+ visit(tree);
281
+ }
282
+ return found;
283
+ }
284
+
285
+ /** Whether a file starts with a directive such as `'use client'` or `'use server'`. */
286
+ function startsWith(directive, file, code) {
287
+ if (!code.includes(directive)) return false;
288
+ for (const statement of parse(file, code).statements) {
289
+ if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression))
290
+ return false;
291
+ if (statement.expression.text === directive) return true;
292
+ }
293
+ return false;
294
+ }
295
+
296
+ /**
297
+ * Resolves a specifier to a project file the way the app's compiler does: TypeScript's module
298
+ * resolution with the app's tsconfig.json (relative paths, `paths` aliases, index files), then
299
+ * `@/` → the app folder and relative paths as Doctor's provider check does. Packages and
300
+ * declaration files resolve to undefined: they are not app code. `elide` tells whether the
301
+ * compiler drops imports used only as types (no `verbatimModuleSyntax`).
302
+ */
303
+ function createResolver(project) {
304
+ const configFile = path.join(project.root, 'tsconfig.json');
305
+ let options = {};
306
+ if (ts.sys.fileExists(configFile)) {
307
+ const { config } = ts.readConfigFile(configFile, ts.sys.readFile);
308
+ options = ts.parseJsonConfigFileContent(config ?? {}, ts.sys, project.root).options;
309
+ }
310
+ options = {
311
+ ...options,
312
+ allowJs: true,
313
+ moduleResolution: options.moduleResolution ?? ts.ModuleResolutionKind.Bundler,
314
+ module: options.module ?? ts.ModuleKind.ESNext,
315
+ };
316
+ // TypeScript, SWC and esbuild drop imports used only as types unless the app keeps them.
317
+ const elide = !(
318
+ options.verbatimModuleSyntax ||
319
+ options.preserveValueImports ||
320
+ options.importsNotUsedAsValues === ts.ImportsNotUsedAsValues.Preserve ||
321
+ options.importsNotUsedAsValues === ts.ImportsNotUsedAsValues.Error
322
+ );
323
+ const cache = ts.createModuleResolutionCache(project.root, (name) => name, options);
324
+ const probe = (base) =>
325
+ [
326
+ base,
327
+ ...extensions.map((extension) => `${base}${extension}`),
328
+ ...extensions.map((extension) => path.join(base, `index${extension}`)),
329
+ ].find((candidate) => ts.sys.fileExists(candidate));
330
+ // Real paths, so a file reached through a symlinked folder (macOS /var) matches server/ folders.
331
+ const real = (file) => file && (ts.sys.realpath?.(path.resolve(file)) ?? path.resolve(file));
332
+ const resolve = (specifier, from) => {
333
+ const resolved = ts.resolveModuleName(specifier, from, options, ts.sys, cache).resolvedModule;
334
+ if (resolved)
335
+ return resolved.isExternalLibraryImport || declarationFile.test(resolved.resolvedFileName)
336
+ ? undefined
337
+ : real(resolved.resolvedFileName);
338
+ const base = specifier.startsWith('@/')
339
+ ? path.join(project.appDirectory, specifier.slice(2))
340
+ : specifier.startsWith('.')
341
+ ? path.resolve(path.dirname(from), specifier)
342
+ : undefined;
343
+ return real(base && probe(base));
344
+ };
345
+ return { resolve, elide };
346
+ }
347
+
348
+ /**
349
+ * Doctor's server boundary, two rules:
350
+ *
351
+ * 1. Browser code never reaches server code. The walk starts at every file the generated client
352
+ * files import (`bitakit.gen.tsx`, `bitakit.gen.config.ts`; before the first generation, the
353
+ * client files discovery would import), every file with a `'use client'` directive and, in
354
+ * TanStack apps (no directive), every route file under `src/routes`. It follows value imports
355
+ * transitively (relative, `@/` and tsconfig `paths`), as the bundler would: type-only imports
356
+ * and, unless `verbatimModuleSyntax` keeps them, imports used only as types are skipped; in
357
+ * TanStack, so are imports used only in code Start keeps on the server (route `server`
358
+ * handlers, `createServerFn(...).handler`); in Next, a `'use server'` module is not followed,
359
+ * because the browser gets references to its functions, never its code. Reaching a file under
360
+ * any module's `server/` folder, `bitakit.gen.server` or `@bitakit/core/server` is an error.
361
+ * Files no client root reaches, such as route handlers, server components or a contribution
362
+ * only server code imports, are not checked.
363
+ * 2. Server code renders nothing: a file under `server/` importing `react`, `react-dom`,
364
+ * `@bitakit/ui` or its own module's `ui/` folder is an error. Another module's `ui/` is not
365
+ * checked: it may hold plain helpers (KnightCMS keeps some there).
366
+ */
367
+ export async function checkServerBoundary(project, description) {
368
+ const root = description.root;
369
+ const relative = (file) => path.relative(root, file).split(path.sep).join('/');
370
+ const appRoot = path.resolve(root, description.app.directory);
371
+ const moduleRoots = [
372
+ appRoot,
373
+ ...description.plugins.map((plugin) => path.resolve(root, plugin.directory)),
374
+ ];
375
+ const serverFolders = moduleRoots.map((module) => path.join(module, 'server') + path.sep);
376
+ const isServer = (file) => serverFolders.some((folder) => file.startsWith(folder));
377
+ /** The `ui/` folder of the module whose `server/` holds `file` (the innermost, for child plugins). */
378
+ const ownUi = (file) => {
379
+ const module = moduleRoots
380
+ .filter((item) => file.startsWith(path.join(item, 'server') + path.sep))
381
+ .sort((a, b) => b.length - a.length)[0];
382
+ return path.join(module, 'ui') + path.sep;
383
+ };
384
+ const framework = description.framework ?? project.framework;
385
+ const { resolve, elide } = createResolver({ root, appDirectory: appRoot });
386
+ // Only Start strips server code from routes; with TanStack Router alone, all of it is bundled.
387
+ const imports = { elide, serverOnly: framework === 'tanstack' && Boolean(project.start) };
388
+ const sources = new Map();
389
+ const read = async (file) => {
390
+ if (!sources.has(file)) sources.set(file, await readFile(file, 'utf8').catch(() => undefined));
391
+ return sources.get(file);
392
+ };
393
+
394
+ const roots = new Set();
395
+ for (const name of ['bitakit.gen.tsx', 'bitakit.gen.ts', 'bitakit.gen.config.ts']) {
396
+ const file = path.join(appRoot, name);
397
+ if (ts.sys.fileExists(file)) roots.add(file);
398
+ }
399
+ const clientKinds = [
400
+ 'actions',
401
+ 'services',
402
+ 'pages',
403
+ 'slots',
404
+ 'slotDefinitions',
405
+ 'providers',
406
+ 'configs',
407
+ 'interceptors',
408
+ 'events',
409
+ 'settings',
410
+ 'layouts',
411
+ ];
412
+ for (const module of [description.app, ...description.plugins.filter((item) => item.enabled)]) {
413
+ for (const kind of clientKinds)
414
+ for (const entry of module[kind] ?? []) roots.add(path.resolve(root, entry.file));
415
+ if (module.settingsPage) roots.add(path.resolve(root, module.settingsPage));
416
+ }
417
+ const projectFiles = await walk(root);
418
+ for (const file of projectFiles) {
419
+ const code = await read(file);
420
+ if (code !== undefined && startsWith('use client', file, code)) roots.add(file);
421
+ }
422
+ // TanStack has no directive: every route is browser code, except what Start strips from it.
423
+ if (framework === 'tanstack') {
424
+ const routes = path.join(root, 'src', 'routes');
425
+ for (const file of projectFiles) {
426
+ const route = path.relative(routes, file);
427
+ // Files and folders starting with "-" are not routes (TanStack's ignore prefix).
428
+ if (
429
+ !route.startsWith('..') &&
430
+ !path.isAbsolute(route) &&
431
+ !route
432
+ .replace(sourceFile, '')
433
+ .split(/[\\/.]/)
434
+ .some((token) => token.startsWith('-'))
435
+ )
436
+ roots.add(file);
437
+ }
438
+ }
439
+ // Next gives the browser references to a 'use server' module's functions, never its code.
440
+ const serverFunctionFiles = new Map();
441
+ const serverFunctions = async (file) => {
442
+ if (framework !== 'next' || !sourceFile.test(file)) return false;
443
+ if (!serverFunctionFiles.has(file)) {
444
+ const code = await read(file);
445
+ serverFunctionFiles.set(file, code !== undefined && startsWith('use server', file, code));
446
+ }
447
+ return serverFunctionFiles.get(file);
448
+ };
449
+
450
+ const importer = new Map();
451
+ const chain = (file) => {
452
+ const files = [file];
453
+ while (importer.has(files[0])) files.unshift(importer.get(files[0]));
454
+ return files.map(relative).join(' → ');
455
+ };
456
+ const leaks = new Set();
457
+ const queue = [...roots];
458
+ const seen = new Set(queue);
459
+ for (const file of queue) {
460
+ if (isServer(file)) {
461
+ leaks.add(`${chain(file)} is browser code inside a server/ folder.`);
462
+ continue;
463
+ }
464
+ const code = await read(file);
465
+ if (code === undefined || (await serverFunctions(file))) continue;
466
+ for (const specifier of valueImports(file, code, imports)) {
467
+ if (serverEntry.test(specifier)) {
468
+ leaks.add(`${chain(file)} imports ${specifier}.`);
469
+ continue;
470
+ }
471
+ const target = resolve(specifier, file);
472
+ if (generatedServer.test(target ?? specifier)) {
473
+ leaks.add(`${chain(file)} imports the generated server file (${specifier}).`);
474
+ continue;
475
+ }
476
+ if (!target || seen.has(target) || (await serverFunctions(target))) continue;
477
+ if (isServer(target)) {
478
+ leaks.add(`${chain(file)} → ${relative(target)}`);
479
+ continue;
480
+ }
481
+ if (!sourceFile.test(target)) continue;
482
+ seen.add(target);
483
+ importer.set(target, file);
484
+ queue.push(target);
485
+ }
486
+ }
487
+
488
+ const results = [
489
+ leaks.size
490
+ ? {
491
+ status: 'error',
492
+ title: 'Browser code imports server code',
493
+ details: summarize([...leaks]),
494
+ fix: 'Files under server/ (and @bitakit/core/server) never reach the browser. Move code both sides need out of server/, or keep it on the server and call it from the button with remote.<plugin>.<name>(). Type-only imports (import type) are fine.',
495
+ }
496
+ : {
497
+ status: 'ok',
498
+ title: `Browser code never imports server code (${seen.size} client file${seen.size === 1 ? '' : 's'} checked)`,
499
+ },
500
+ ];
501
+
502
+ const serverFiles = projectFiles.filter(isServer);
503
+ if (!serverFiles.length) return results;
504
+ const rendering = new Set();
505
+ for (const file of serverFiles) {
506
+ const code = await read(file);
507
+ if (code === undefined) continue;
508
+ for (const specifier of valueImports(file, code)) {
509
+ if (uiPackages.test(specifier)) {
510
+ rendering.add(`${relative(file)} imports ${specifier}.`);
511
+ continue;
512
+ }
513
+ const target = resolve(specifier, file);
514
+ if (target?.startsWith(ownUi(file)))
515
+ rendering.add(`${relative(file)} imports ${relative(target)}.`);
516
+ }
517
+ }
518
+ results.push(
519
+ rendering.size
520
+ ? {
521
+ status: 'error',
522
+ title: 'Server code imports React or UI code',
523
+ details: summarize([...rendering]),
524
+ fix: 'Server Actions and services return data; the page under ui/ renders it. Move the React code to ui/ and call the operation from there through its button.',
525
+ }
526
+ : { status: 'ok', title: 'Server code imports no React or UI code' },
527
+ );
528
+ return results;
529
+ }
530
+
531
+ const summarize = (lines) =>
532
+ lines.length > shown ? [...lines.slice(0, shown), `… and ${lines.length - shown} more.`] : lines;
533
+
534
+ /**
535
+ * The project's source files that import the generated server file (`bitakit.gen.server`), such
536
+ * as the RPC route: `{ file, code }`, the file relative to the root. Generated files are skipped.
537
+ */
538
+ export async function generatedServerImporters(root) {
539
+ const found = [];
540
+ for (const file of await walk(root)) {
541
+ if (/(?:^|[\\/])bitakit\.gen\./.test(file)) continue;
542
+ const code = await readFile(file, 'utf8').catch(() => undefined);
543
+ if (
544
+ code?.includes('bitakit.gen.server') &&
545
+ valueImports(file, code).some((specifier) => generatedServer.test(specifier))
546
+ )
547
+ found.push({ file: path.relative(root, file).split(path.sep).join('/'), code });
548
+ }
549
+ return found;
550
+ }
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