@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/src/cli.mjs CHANGED
@@ -4,7 +4,7 @@ import path from 'node:path';
4
4
  import { styleText } from 'node:util';
5
5
  import { Command } from 'commander';
6
6
  import { describeBitaKit, generateBitaKit, migrateProject, watchBitaKit } from '@bitakit/discovery';
7
- import { addContribution, addPlugin, contributionKinds } from './add.mjs';
7
+ import { addContribution, addPlugin, contributionKinds, serverKinds } from './add.mjs';
8
8
  import { inspectionFromDescription } from './inventory.mjs';
9
9
  import { buildPlugin } from './build.mjs';
10
10
  import { CheckPageSetupError, checkPage, formatPageReport } from './check-page.mjs';
@@ -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) || '.';
@@ -58,6 +65,13 @@ for (const kind of contributionKinds) {
58
65
  '--plugin <id>',
59
66
  "write the layout into an app plugin's ui/layouts instead of src/layouts",
60
67
  );
68
+ if (serverKinds.includes(kind))
69
+ command.option(
70
+ '--server',
71
+ kind === 'action'
72
+ ? 'write the operation into server/actions/ (runs only on the server), with its test, a button that calls it through remote, and the RPC route when the app has none'
73
+ : `write the ${kind} into the plugin's server/ folder (runs only on the server)`,
74
+ );
61
75
  command
62
76
  .argument(
63
77
  kind === 'events' || kind === 'settings' || kind === 'settings-page'
@@ -89,16 +103,44 @@ for (const kind of contributionKinds) {
89
103
  : `Create ${/^[aeiou]/.test(kind) ? 'an' : 'a'} ${kind} file. Its ID comes from the file path.`,
90
104
  )
91
105
  .action(async (target, options) => {
92
- const result = await addContribution(kind, target, { plugin: options?.plugin });
106
+ const result = await addContribution(kind, target, {
107
+ plugin: options?.plugin,
108
+ server: options?.server,
109
+ });
93
110
  if (result.createdPlugin) console.log(`\nCreated plugin "${result.plugin}".`);
94
111
  console.log(
95
112
  kind === 'slot'
96
113
  ? `\nCreated a component of plugin "${result.plugin}" for slot "${result.id}":`
97
114
  : kind === 'test'
98
115
  ? `\nCreated a test for plugin "${result.plugin}":`
99
- : `\nCreated ${kind} ${kind === 'page' ? result.path : `"${result.id}"`}:`,
116
+ : result.server
117
+ ? `\nCreated server ${kind} "server:${result.id}":`
118
+ : `\nCreated ${kind} ${kind === 'page' ? result.path : `"${result.id}"`}:`,
100
119
  );
101
120
  created(result.created);
121
+ for (const file of result.kept ?? [])
122
+ console.log(
123
+ `\nKept the existing button ${relative(file)}; call ${result.remote}(input) from its execute.`,
124
+ );
125
+ if (result.route && !result.route.created)
126
+ console.log(
127
+ `\n${relative(path.join(result.project.root, result.route.file))} already answers ${result.project.serverEndpoint}/<operation id>.`,
128
+ );
129
+ if (result.noHost)
130
+ console.log(`\nThis app's framework has no server route BitaKit writes. ${result.noHost}`);
131
+ if (result.remote)
132
+ console.log(
133
+ `\nThe operation runs only on the server; the browser calls it with ${result.remote}(input).\nRun npx bitakit generate (the dev server does it on save) so remote knows it.`,
134
+ );
135
+ if (result.needsProvider) {
136
+ const file = path.join(
137
+ path.relative(result.project.root, result.project.appDirectory),
138
+ 'server/services/request-context.ts',
139
+ );
140
+ console.log(
141
+ `\nBefore the browser can call it: add ${file.split(path.sep).join('/')} with defineService(() => ({ resolve: (request) => ({ user, organization }) }), { provides: requestContext }) from '@bitakit/core/server', reading your auth session. Until then the server refuses to start (npx bitakit doctor shows it). The test passes without it because mountServer brings its own.`,
142
+ );
143
+ }
102
144
  if (result.setup?.length)
103
145
  console.log(
104
146
  `\nBefore the first run:\n${result.setup.map((line) => ` ${line}`).join('\n')}`,
@@ -162,7 +204,7 @@ program
162
204
  }
163
205
  const result = await generateBitaKit(project.root);
164
206
  console.log(
165
- `\nGenerated ${relative(result.generated)} (${result.framework === 'none' ? 'no framework provider' : result.framework}).${result.warnings.length ? ` ${result.warnings.length} warning${result.warnings.length === 1 ? '' : 's'} above.` : ''}\n`,
207
+ `\nGenerated ${relative(result.generated)}${result.server ? ` and ${relative(result.server)}` : ''} (${result.framework === 'none' ? 'no framework provider' : result.framework}).${result.warnings.length ? ` ${result.warnings.length} warning${result.warnings.length === 1 ? '' : 's'} above.` : ''}\n`,
166
208
  );
167
209
  });
168
210
 
@@ -370,7 +412,14 @@ program
370
412
  console.log(
371
413
  ` ${kind}: ${plugin.declarations
372
414
  .filter((entry) => entry.kind === kind)
373
- .map((entry) => entry.id ?? entry.source)
415
+ // Server declarations print as server:<id>, apart from the client's.
416
+ .map((entry) =>
417
+ entry.id === null
418
+ ? entry.source
419
+ : kind.startsWith('server-')
420
+ ? `server:${entry.id}`
421
+ : entry.id,
422
+ )
374
423
  .join(', ')}`,
375
424
  );
376
425
  }
@@ -407,6 +456,81 @@ program
407
456
  console.log('');
408
457
  });
409
458
 
459
+ // The app's frame is the replaceable part `layout.app`; a shell is a candidate for it.
460
+ const shell = program
461
+ .command('shell')
462
+ .description(
463
+ "The app's frame (the replaceable part layout.app): see the shells this app can use and pick one.",
464
+ );
465
+ const partOption = ['--part <id>', 'another replaceable part, for example layout.auth', framePart];
466
+ const shellState = async (part) => {
467
+ const project = await findProject();
468
+ if (project.kind !== 'app') throw new Error('Run "bitakit shell" inside an app.');
469
+ const slots = await describeSlots(await describeBitaKit(project.root));
470
+ return { project, state: describeShell(slots, part) };
471
+ };
472
+ /** The generated wiring follows the choice at once; a failure there leaves the written choice in place. */
473
+ const regenerate = async (root) => {
474
+ try {
475
+ await generateBitaKit(root);
476
+ console.log('Generated the wiring again. A running dev server may need a restart.\n');
477
+ } catch (error) {
478
+ console.log(`The choice is written, but generating failed: ${error.message}\n`);
479
+ }
480
+ };
481
+
482
+ shell
483
+ .command('list', { isDefault: true })
484
+ .description('Show the frame that renders, the candidates and the choice in bitakit.config.ts.')
485
+ .option(...partOption)
486
+ .option('--json', 'machine-readable output')
487
+ .action(async (options) => {
488
+ const { state } = await shellState(options.part);
489
+ if (options.json) {
490
+ console.log(JSON.stringify(state, null, 2));
491
+ return;
492
+ }
493
+ console.log('');
494
+ for (const line of formatShell(state)) console.log(line);
495
+ console.log('');
496
+ });
497
+
498
+ shell
499
+ .command('use')
500
+ .argument('<name>', 'a candidate: "plugin:variant", a plugin or a variant')
501
+ .description(
502
+ "Choose the frame: writes choose: { 'layout.app': '<name>' } into bitakit.config.ts.",
503
+ )
504
+ .option(...partOption)
505
+ .action(async (name, options) => {
506
+ const { project, state } = await shellState(options.part);
507
+ if (!state.exists) throw new Error(formatShell(state).join(' '));
508
+ const candidate = resolveCandidate(state.candidates, name);
509
+ const { changed } = await chooseCandidate(project.root, options.part, candidate);
510
+ console.log(
511
+ changed
512
+ ? `\n${options.part} now uses ${candidate} (bitakit.config.ts).`
513
+ : `\n${options.part} already uses ${candidate}.\n`,
514
+ );
515
+ if (changed) await regenerate(project.root);
516
+ });
517
+
518
+ shell
519
+ .command('reset')
520
+ .description('Remove the choice, so the default frame (or the only candidate) renders again.')
521
+ .option(...partOption)
522
+ .action(async (options) => {
523
+ const project = await findProject();
524
+ if (project.kind !== 'app') throw new Error('Run "bitakit shell" inside an app.');
525
+ const { changed } = await chooseCandidate(project.root, options.part, undefined);
526
+ console.log(
527
+ changed
528
+ ? `\n${options.part} has no choice any more (bitakit.config.ts).`
529
+ : `\n${options.part} had no choice.\n`,
530
+ );
531
+ if (changed) await regenerate(project.root);
532
+ });
533
+
410
534
  try {
411
535
  await program.parseAsync();
412
536
  } catch (error) {
package/src/doctor.mjs CHANGED
@@ -10,7 +10,17 @@ import {
10
10
  } from '@bitakit/discovery';
11
11
  import { checkAgentFiles } from './doctor-agent-files.mjs';
12
12
  import { exists, findProject } from './project.mjs';
13
- import { appRoutes, catchAllRoute, rootLayouts, shellGroup } from './routes.mjs';
13
+ import {
14
+ appRoutes,
15
+ catchAllRoute,
16
+ hostsServerRoute,
17
+ rootLayouts,
18
+ routesCatching,
19
+ serverHostNote,
20
+ serverRoute,
21
+ shellGroup,
22
+ } from './routes.mjs';
23
+ import { checkServerBoundary, generatedServerImporters } from './server-boundary.mjs';
14
24
  import { describeSlots } from './slots.mjs';
15
25
  import { identityConflictsFromDescription } from './inventory.mjs';
16
26
 
@@ -124,6 +134,16 @@ export async function doctor({ cwd } = {}) {
124
134
  results.push(...(await checkTailwind(project, description)));
125
135
  results.push(checkIgnored(description), checkDeprecated(description), checkSlots(description));
126
136
  results.push(await checkParts(description));
137
+ try {
138
+ results.push(...(await checkServerBoundary(project, description)));
139
+ } catch (error) {
140
+ results.push({
141
+ status: 'error',
142
+ title: 'The server boundary could not be checked',
143
+ details: [error.message],
144
+ });
145
+ }
146
+ results.push(...(await checkServerWiring(project, description)));
127
147
  if (shell) {
128
148
  const missing = [];
129
149
  for (const module of modules)
@@ -471,9 +491,10 @@ const coreKeys = new Map([
471
491
  ['authService', 'auth'],
472
492
  ['translationService', 'i18n'],
473
493
  ['settingsStorage', 'settings.storage'],
494
+ ['requestContext', 'requestContext'],
474
495
  ]);
475
496
  /** Contract names that services register with `provides`; `unresolved` when a key's name cannot be read. */
476
- async function providedKeys(root, entries) {
497
+ export async function providedKeys(root, entries) {
477
498
  const names = [];
478
499
  let unresolved = false;
479
500
  for (const entry of entries) {
@@ -713,6 +734,154 @@ async function checkRequirements(project, description, scanned) {
713
734
  : `All ${count} service requirements can be satisfied`,
714
735
  };
715
736
  }
737
+ /** A module folder's `server/` holds Actions, services or interceptors (any spelling). */
738
+ async function hasServerKinds(folder) {
739
+ const entries = await readdir(path.join(folder, 'server')).catch(() => []);
740
+ return entries.some((name) => /^(?:actions|services|interceptors)(?:\.|$)/.test(name));
741
+ }
742
+
743
+ /**
744
+ * Wiring of the server half, read statically (best effort): exposed server Actions need an app
745
+ * route that hands `<endpoint>/x` to BitaKit (a broader API catch-all that answers on its own
746
+ * does not count), and operations that are not public need a server service with
747
+ * `provides: requestContext`, or the server refuses to start. In a framework without a server
748
+ * host for that route, a file that calls `fetchHandler` with the generated server counts.
749
+ * Definitions that cannot be read statically are not counted. Without any server half, code
750
+ * that imports the generated server file is an error: discovery removes that file. A discovery
751
+ * that does not read `server/` folders (before 0.3.1) is reported when such folders exist.
752
+ */
753
+ async function checkServerWiring(project, description) {
754
+ const root = description.root;
755
+ const modules = [
756
+ { ...description.app, isApp: true },
757
+ ...description.plugins.filter((plugin) => plugin.enabled),
758
+ ];
759
+ const generated = `${description.appDirectory ?? description.app.directory}/bitakit.gen.server.ts`;
760
+ if (description.app.server === undefined) {
761
+ const folders = [];
762
+ for (const module of modules)
763
+ if (await hasServerKinds(path.join(root, module.directory)))
764
+ folders.push(`${module.directory}/server`);
765
+ return folders.length
766
+ ? [
767
+ {
768
+ status: 'warn',
769
+ title: 'This @bitakit/discovery does not read server/ folders',
770
+ details: [
771
+ `${folders.join(', ')} hold${folders.length === 1 ? 's' : ''} server Actions, services or interceptors, but the installed @bitakit/discovery predates server halves: it generates no ${generated} and checks nothing on the server side.`,
772
+ ],
773
+ fix: 'npm install @bitakit/discovery@latest (0.3.1 or newer), then npx bitakit generate.',
774
+ },
775
+ ]
776
+ : [];
777
+ }
778
+ const operations = [];
779
+ let unresolved = false;
780
+ let provided = false;
781
+ let content = false;
782
+ for (const module of modules) {
783
+ const server = module.server;
784
+ content ||=
785
+ server.actions.length > 0 ||
786
+ server.services.length > 0 ||
787
+ server.interceptors.length > 0 ||
788
+ Object.values(server.contributions ?? {}).some((entries) => entries.length > 0);
789
+ const found = await describeDefinitions(
790
+ server.actions.map((entry) => ({ ...entry, file: path.join(root, entry.file) })),
791
+ {
792
+ helper: 'defineAction',
793
+ moduleId: module.isApp ? '' : module.id,
794
+ inspect: (fields, { unwrap, literal, ts: syntax }) => ({
795
+ exposed: unwrap(fields.get('expose'))?.kind === syntax.SyntaxKind.TrueKeyword,
796
+ access: fields.has('access') ? (literal(fields.get('access')) ?? 'rule') : undefined,
797
+ }),
798
+ },
799
+ );
800
+ operations.push(...found.definitions);
801
+ const keys = await providedKeys(root, server.services);
802
+ provided ||= keys.names.includes('requestContext');
803
+ unresolved ||= keys.unresolved;
804
+ }
805
+ if (!content) {
806
+ const importers = await generatedServerImporters(root);
807
+ return importers.length
808
+ ? [
809
+ {
810
+ status: 'error',
811
+ title: 'Code imports the generated server file, but no module has a server half',
812
+ details: importers.map(
813
+ ({ file }) =>
814
+ `${file} imports ${generated}, which discovery writes only while a server half exists.`,
815
+ ),
816
+ fix: 'Delete the route (or the import), or add a server Action: npx bitakit add action <plugin>/<name> --server.',
817
+ },
818
+ ]
819
+ : [];
820
+ }
821
+ if (!operations.length) return [];
822
+ const results = [];
823
+ const exposed = operations.filter((operation) => operation.exposed);
824
+ if (exposed.length) {
825
+ const endpoint = project.serverEndpoint ?? '/api/rpc';
826
+ const caught = await routesCatching(project, endpoint);
827
+ const route = caught.find((item) => item.bitakit);
828
+ const listed = `${exposed.map((operation) => `server:${operation.id}`).join(', ')} ${exposed.length === 1 ? 'is' : 'are'} exposed`;
829
+ if (route)
830
+ results.push({ status: 'ok', title: `${route.file} answers ${endpoint}/<operation id>` });
831
+ else if (!hostsServerRoute(project)) {
832
+ const host = (await generatedServerImporters(root)).find(({ code }) =>
833
+ /\bfetchHandler\b/.test(code),
834
+ );
835
+ results.push(
836
+ host
837
+ ? {
838
+ status: 'ok',
839
+ title: `${host.file} serves ${endpoint}/<operation id> with fetchHandler`,
840
+ }
841
+ : {
842
+ status: 'warn',
843
+ title: 'No server answers the exposed server Actions',
844
+ details: [
845
+ `${listed}, but this app's framework has no server route BitaKit writes, and no file calls fetchHandler with the generated server, so remote calls fail.`,
846
+ ],
847
+ fix: serverHostNote(endpoint, generated),
848
+ },
849
+ );
850
+ } else {
851
+ const file = await serverRoute(project, { endpoint });
852
+ results.push({
853
+ status: 'warn',
854
+ title: 'No route answers the exposed server Actions',
855
+ details: [
856
+ `${listed}, but no app route hands POST ${endpoint}/<operation id> to BitaKit, so remote calls fail.`,
857
+ ...caught.map(
858
+ (item) =>
859
+ `${item.file} catches ${endpoint}/<operation id> but does not call fetchHandler; the more specific route below takes precedence over it.`,
860
+ ),
861
+ ],
862
+ fix: `Create ${file.file}:\n\n${file.content}`,
863
+ });
864
+ }
865
+ }
866
+ const guarded = operations.filter((operation) => operation.access !== 'public');
867
+ if (guarded.length && !provided && !unresolved)
868
+ results.push({
869
+ status: 'warn',
870
+ title: 'No service provides requestContext',
871
+ details: [
872
+ `${guarded
873
+ .slice(0, 3)
874
+ .map((operation) => `server:${operation.id}`)
875
+ .join(
876
+ ', ',
877
+ )}${guarded.length > 3 ? ` and ${guarded.length - 3} more` : ''} need${guarded.length === 1 ? 's' : ''} a signed-in caller, so the server refuses to start without a provider.`,
878
+ ],
879
+ fix: "Add src/server/services/request-context.ts: defineService(() => ({ resolve: (request) => ({ user, organization, member, can }) }), { provides: requestContext }) from '@bitakit/core/server', reading the session of your auth provider. The organization only for an active, verified membership.",
880
+ });
881
+ else if (guarded.length && provided)
882
+ results.push({ status: 'ok', title: 'A server service provides requestContext' });
883
+ return results;
884
+ }
716
885
  /** Plugin `dependencies` must not form a cycle, and the plugins they name must be enabled. */
717
886
  function checkGraph(description) {
718
887
  const dependenciesOf = (plugin) =>
package/src/index.mjs CHANGED
@@ -1,5 +1,11 @@
1
1
  /** Programmatic API shared by the `bitakit` CLI and the project generator. */
2
- export { addPlugin, addContribution, writeNewFiles, contributionKinds } from './add.mjs';
2
+ export {
3
+ addPlugin,
4
+ addContribution,
5
+ writeNewFiles,
6
+ contributionKinds,
7
+ serverKinds,
8
+ } from './add.mjs';
3
9
  export {
4
10
  agentRules,
5
11
  agentRulesBegin,
@@ -27,7 +33,7 @@ export {
27
33
  wrapNextConfig,
28
34
  } from './init.mjs';
29
35
  export { findProject, findProjectRoot, packagePluginId } from './project.mjs';
30
- export { appRoutes, catchAllRoute } from './routes.mjs';
36
+ export { appRoutes, catchAllRoute, serverRoute, serverRouteFor } from './routes.mjs';
31
37
  export { describeSlots, formatSlots } from './slots.mjs';
32
38
  export {
33
39
  actionFile,
@@ -36,7 +42,12 @@ export {
36
42
  interceptorFile,
37
43
  pageFile,
38
44
  pluginFiles,
45
+ remoteActionFile,
39
46
  sampleFiles,
47
+ serverActionFile,
48
+ serverInterceptorFile,
49
+ serverServiceFile,
50
+ serverTestFile,
40
51
  starterFiles,
41
52
  serviceFile,
42
53
  titleOf,
package/src/inventory.mjs CHANGED
@@ -40,6 +40,12 @@ const kinds = {
40
40
  configs: 'config',
41
41
  interceptors: 'interceptor',
42
42
  };
43
+ /** A module's `server/` half (`description.<module>.server`), as Core's server inventory kinds. */
44
+ const serverKinds = {
45
+ actions: 'server-action',
46
+ services: 'server-service',
47
+ interceptors: 'server-interceptor',
48
+ };
43
49
 
44
50
  /** The literal keys of the first object passed to `helper(...)` in the default export. */
45
51
  async function recordKeys(file, helper) {
@@ -114,18 +120,23 @@ export async function inspectionFromDescription(description) {
114
120
  for (const module of [description.app, ...description.plugins]) {
115
121
  const app = module === description.app;
116
122
  const declarations = [];
117
- for (const [key, kind] of Object.entries(kinds))
118
- for (const entry of module[key] ?? []) {
119
- const ids = await idsOf(key, entry, module, {
120
- root: description.root,
121
- app,
122
- slotDeclarations: description.slotDeclarations,
123
- }).catch(() => null);
124
- if (ids?.length)
125
- for (const id of ids)
126
- declarations.push({ kind, id, source: entry.file, resolution: 'resolved' });
127
- else declarations.push({ kind, id: null, source: entry.file, resolution: 'file' });
128
- }
123
+ // Server Actions and services follow the client's naming rules: unprefixed in the app.
124
+ for (const [side, map] of [
125
+ [module, kinds],
126
+ [module.server ?? {}, serverKinds],
127
+ ])
128
+ for (const [key, kind] of Object.entries(map))
129
+ for (const entry of side[key] ?? []) {
130
+ const ids = await idsOf(key, entry, module, {
131
+ root: description.root,
132
+ app,
133
+ slotDeclarations: description.slotDeclarations,
134
+ }).catch(() => null);
135
+ if (ids?.length)
136
+ for (const id of ids)
137
+ declarations.push({ kind, id, source: entry.file, resolution: 'resolved' });
138
+ else declarations.push({ kind, id: null, source: entry.file, resolution: 'file' });
139
+ }
129
140
  plugins.push({
130
141
  id: module.id,
131
142
  pluginId: module.id,
package/src/project.mjs CHANGED
@@ -74,14 +74,26 @@ async function describeProject(root, manifest) {
74
74
  root,
75
75
  manifest,
76
76
  framework,
77
+ // TanStack Router alone renders in the browser; Start adds the server that runs handlers.
78
+ start: Boolean(dependencies['@tanstack/react-start']),
77
79
  configFile: file,
78
80
  legacyConfig: legacy,
79
81
  configError,
80
82
  pluginsDirectory: path.resolve(root, config.plugins?.directory ?? './src/plugins'),
81
83
  appDirectory: path.resolve(root, config.directory ?? './src'),
84
+ // Where the browser calls server operations (`server.endpoint`); discovery validates it.
85
+ serverEndpoint: serverEndpointOf(config),
82
86
  };
83
87
  }
84
88
 
89
+ /** `server.endpoint` of bitakit.config.ts as a path without a trailing slash; `/api/rpc` by default. */
90
+ function serverEndpointOf(config) {
91
+ const endpoint = config.server?.endpoint;
92
+ return typeof endpoint === 'string' && endpoint.replace(/^\/+|\/+$/g, '')
93
+ ? `/${endpoint.replace(/^\/+|\/+$/g, '')}`
94
+ : '/api/rpc';
95
+ }
96
+
85
97
  export async function exists(file) {
86
98
  return access(file).then(
87
99
  () => true,
package/src/routes.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { readdir, readFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
+ import ts from 'typescript';
3
4
  import { exists } from './project.mjs';
4
5
 
5
6
  /**
@@ -105,6 +106,113 @@ export default function Page() {
105
106
  };
106
107
  }
107
108
 
109
+ /**
110
+ * Whether the app's framework runs the route `serverRoute` writes: Next route handlers, or the
111
+ * server handlers of TanStack Start. TanStack Router alone, Vite and other setups have no server
112
+ * host BitaKit writes a route for.
113
+ */
114
+ export const hostsServerRoute = (project) =>
115
+ project.framework === 'next' || (project.framework === 'tanstack' && Boolean(project.start));
116
+
117
+ /** A route that hands requests to BitaKit: it calls `fetchHandler` or imports the generated server. */
118
+ const callsBitaKit = /\bfetchHandler\b|bitakit\.gen\.server/;
119
+
120
+ /**
121
+ * The app routes that catch POST requests under `endpoint` (`/api/rpc/x`): Next route handlers
122
+ * (`route.ts`, never a page) or TanStack routes with server `handlers` whose path matches. Each
123
+ * `{ file, pattern, catchAll, bitakit }`, where `bitakit` tells whether the route hands the call
124
+ * to BitaKit. A broader API catch-all (Hono's `api/[[...route]]`) catches it too but answers on
125
+ * its own; the more specific RPC route wins over it in both frameworks.
126
+ */
127
+ export async function routesCatching(project, endpoint) {
128
+ const probe = `${endpoint}/x`;
129
+ const found = [];
130
+ for (const route of await appRoutes(project)) {
131
+ if (!route.pattern.test(probe)) continue;
132
+ if (project.framework === 'next' && !/^route\./.test(path.basename(route.file))) continue;
133
+ const source = await readFile(path.join(project.root, route.file), 'utf8').catch(() => '');
134
+ if (project.framework === 'tanstack' && !/\bhandlers\b/.test(source)) continue;
135
+ found.push({ ...route, bitakit: callsBitaKit.test(source) });
136
+ }
137
+ return found;
138
+ }
139
+
140
+ /** The app route that answers POST `<endpoint>/x` with BitaKit's `fetchHandler`, if any. */
141
+ export async function serverRouteFor(project, endpoint) {
142
+ return (await routesCatching(project, endpoint)).find((route) => route.bitakit);
143
+ }
144
+
145
+ /** Whether the app's tsconfig.json maps `@/*` to its `src` folder, as create-next-app writes it. */
146
+ async function aliasesSource(project) {
147
+ const file = path.join(project.root, 'tsconfig.json');
148
+ const text = await readFile(file, 'utf8').catch(() => undefined);
149
+ if (text === undefined) return false;
150
+ const { config } = ts.parseConfigFileTextToJson(file, text);
151
+ const target = config?.compilerOptions?.paths?.['@/*']?.[0];
152
+ return (
153
+ typeof target === 'string' &&
154
+ path.resolve(project.root, target) ===
155
+ path.join(project.appDirectory ?? path.join(project.root, 'src'), '*')
156
+ );
157
+ }
158
+
159
+ /**
160
+ * The RPC route `bitakit add action … --server` writes when no route answers `<endpoint>/x`:
161
+ * every POST under the endpoint goes to the generated server's `fetchHandler`, which takes its
162
+ * prefix from the same `server.endpoint`. `{ file, content }`, the file relative to the root;
163
+ * `undefined` when the framework has no server host for it (see `hostsServerRoute`).
164
+ */
165
+ export async function serverRoute(project, { endpoint = '/api/rpc' } = {}) {
166
+ if (!hostsServerRoute(project)) return undefined;
167
+ const segments = endpoint.split('/').filter(Boolean);
168
+ const generated = path.join(
169
+ project.appDirectory ?? path.join(project.root, 'src'),
170
+ 'bitakit.gen.server',
171
+ );
172
+ const from = (file) => {
173
+ const relative = path
174
+ .relative(path.dirname(path.join(project.root, file)), generated)
175
+ .split(path.sep)
176
+ .join('/');
177
+ return relative.startsWith('.') ? relative : `./${relative}`;
178
+ };
179
+ if (project.framework === 'tanstack') {
180
+ const file = `src/routes/${[...segments.slice(0, -1), `${segments.at(-1)}.$.ts`].join('/')}`;
181
+ return {
182
+ file,
183
+ content: `import { createFileRoute } from '@tanstack/react-router';
184
+ // Types the server option even when tsr generate wrote routeTree.gen.ts without Start's types.
185
+ import type {} from '@tanstack/react-start';
186
+ import { fetchHandler } from '@bitakit/core/server';
187
+ import { server } from '${from(file)}';
188
+
189
+ const handle = fetchHandler(server);
190
+
191
+ // Every BitaKit server operation the browser calls: POST ${endpoint}/<operation id>.
192
+ export const Route = createFileRoute('/${segments.join('/')}/$')({
193
+ server: { handlers: { POST: ({ request }) => handle(request) } },
194
+ });
195
+ `,
196
+ };
197
+ }
198
+ const app = (await exists(path.join(project.root, 'src/app')))
199
+ ? 'src/app'
200
+ : (await exists(path.join(project.root, 'app')))
201
+ ? 'app'
202
+ : 'src/app';
203
+ const file = `${app}/${segments.join('/')}/[...path]/route.ts`;
204
+ const specifier = (await aliasesSource(project)) ? '@/bitakit.gen.server' : from(file);
205
+ return {
206
+ file,
207
+ content: `import { fetchHandler } from '@bitakit/core/server';
208
+ import { server } from '${specifier}';
209
+
210
+ // Every BitaKit server operation the browser calls: POST ${endpoint}/<operation id>.
211
+ export const POST = fetchHandler(server);
212
+ `,
213
+ };
214
+ }
215
+
108
216
  /** The root layout files that mount the provider, per framework. */
109
217
  export const rootLayouts = (project) =>
110
218
  project.framework === 'tanstack'
@@ -122,3 +230,10 @@ export async function shellGroup(project) {
122
230
  }
123
231
  return undefined;
124
232
  }
233
+
234
+ /**
235
+ * What an app whose framework has no server host does instead of the route `serverRoute`
236
+ * writes; `generated` is the generated server file relative to the project root.
237
+ */
238
+ export const serverHostNote = (endpoint, generated) =>
239
+ `Serve POST ${endpoint}/<operation id> in your HTTP server with fetchHandler(server) from '@bitakit/core/server' and server from ${generated}.`;