@agentuity/cli 0.0.73 → 0.0.74
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/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +13 -9
- package/dist/auth.js.map +1 -1
- package/dist/banner.js +1 -1
- package/dist/banner.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +2 -2
- package/dist/cli.js.map +1 -1
- package/dist/cmd/ai/prompt/api.d.ts.map +1 -1
- package/dist/cmd/ai/prompt/api.js +5 -4
- package/dist/cmd/ai/prompt/api.js.map +1 -1
- package/dist/cmd/auth/ssh/api.d.ts.map +1 -1
- package/dist/cmd/auth/ssh/api.js.map +1 -1
- package/dist/cmd/build/ast.d.ts.map +1 -1
- package/dist/cmd/build/ast.js +20 -6
- package/dist/cmd/build/ast.js.map +1 -1
- package/dist/cmd/build/bundler.d.ts +3 -1
- package/dist/cmd/build/bundler.d.ts.map +1 -1
- package/dist/cmd/build/bundler.js +19 -9
- package/dist/cmd/build/bundler.js.map +1 -1
- package/dist/cmd/build/plugin.d.ts.map +1 -1
- package/dist/cmd/build/plugin.js +87 -66
- package/dist/cmd/build/plugin.js.map +1 -1
- package/dist/cmd/build/route-discovery.d.ts +50 -0
- package/dist/cmd/build/route-discovery.d.ts.map +1 -0
- package/dist/cmd/build/route-discovery.js +143 -0
- package/dist/cmd/build/route-discovery.js.map +1 -0
- package/dist/cmd/build/route-registry.d.ts.map +1 -1
- package/dist/cmd/build/route-registry.js +25 -10
- package/dist/cmd/build/route-registry.js.map +1 -1
- package/dist/cmd/cloud/deploy.d.ts.map +1 -1
- package/dist/cmd/cloud/deploy.js +8 -6
- package/dist/cmd/cloud/deploy.js.map +1 -1
- package/dist/cmd/dev/agents.d.ts.map +1 -1
- package/dist/cmd/dev/agents.js.map +1 -1
- package/dist/cmd/dev/index.d.ts.map +1 -1
- package/dist/cmd/dev/index.js +21 -0
- package/dist/cmd/dev/index.js.map +1 -1
- package/dist/cmd/dev/sync.d.ts.map +1 -1
- package/dist/cmd/dev/sync.js.map +1 -1
- package/dist/cmd/project/download.d.ts.map +1 -1
- package/dist/cmd/project/download.js +16 -2
- package/dist/cmd/project/download.js.map +1 -1
- package/dist/cmd/project/list.d.ts.map +1 -1
- package/dist/cmd/project/list.js +2 -10
- package/dist/cmd/project/list.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/steps.d.ts +20 -30
- package/dist/steps.d.ts.map +1 -1
- package/dist/steps.js +339 -184
- package/dist/steps.js.map +1 -1
- package/dist/tui/box.d.ts.map +1 -1
- package/dist/tui/box.js +8 -4
- package/dist/tui/box.js.map +1 -1
- package/dist/tui/prompt.d.ts.map +1 -1
- package/dist/tui/prompt.js +7 -2
- package/dist/tui/prompt.js.map +1 -1
- package/dist/tui.d.ts.map +1 -1
- package/dist/tui.js +5 -4
- package/dist/tui.js.map +1 -1
- package/package.json +3 -3
- package/src/auth.ts +13 -10
- package/src/banner.ts +1 -1
- package/src/cli.ts +4 -2
- package/src/cmd/ai/prompt/api.ts +5 -4
- package/src/cmd/auth/ssh/api.ts +1 -4
- package/src/cmd/build/ast.ts +21 -6
- package/src/cmd/build/bundler.ts +30 -11
- package/src/cmd/build/plugin.ts +108 -82
- package/src/cmd/build/route-discovery.ts +197 -0
- package/src/cmd/build/route-registry.ts +26 -10
- package/src/cmd/cloud/deploy.ts +19 -6
- package/src/cmd/dev/agents.ts +2 -8
- package/src/cmd/dev/index.ts +25 -0
- package/src/cmd/dev/sync.ts +2 -10
- package/src/cmd/project/download.ts +16 -2
- package/src/cmd/project/list.ts +2 -9
- package/src/index.ts +2 -2
- package/src/steps.ts +397 -229
- package/src/tui/box.ts +8 -4
- package/src/tui/prompt.ts +7 -4
- package/src/tui.ts +6 -4
package/src/cmd/ai/prompt/api.ts
CHANGED
|
@@ -26,13 +26,14 @@ Each API folder must contain:
|
|
|
26
26
|
|
|
27
27
|
Example structure:
|
|
28
28
|
\`\`\`
|
|
29
|
-
src/
|
|
29
|
+
src/api/
|
|
30
|
+
├── index.ts (optional, mounted at /api)
|
|
30
31
|
├── status/
|
|
31
|
-
│ └── route.ts
|
|
32
|
+
│ └── route.ts (mounted at /api/status)
|
|
32
33
|
├── users/
|
|
33
|
-
│ └── route.ts
|
|
34
|
+
│ └── route.ts (mounted at /api/users)
|
|
34
35
|
├── agent-call/
|
|
35
|
-
└── route.ts
|
|
36
|
+
└── route.ts (mounted at /api/agent-call)
|
|
36
37
|
\`\`\`
|
|
37
38
|
|
|
38
39
|
## Creating an API
|
package/src/cmd/auth/ssh/api.ts
CHANGED
|
@@ -78,10 +78,7 @@ export async function addSSHKey(apiClient: APIClient, publicKey: string): Promis
|
|
|
78
78
|
const ListSSHKeysError = StructuredError('ListSSHKeysError');
|
|
79
79
|
|
|
80
80
|
export async function listSSHKeys(apiClient: APIClient): Promise<SSHKey[]> {
|
|
81
|
-
const resp = await apiClient.get(
|
|
82
|
-
'/cli/auth/ssh-keys',
|
|
83
|
-
APIResponseSchema(z.array(SSHKeySchema))
|
|
84
|
-
);
|
|
81
|
+
const resp = await apiClient.get('/cli/auth/ssh-keys', APIResponseSchema(z.array(SSHKeySchema)));
|
|
85
82
|
|
|
86
83
|
if (!resp.success) {
|
|
87
84
|
throw new ListSSHKeysError({ message: resp.message });
|
package/src/cmd/build/ast.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as acornLoose from 'acorn-loose';
|
|
2
|
-
import {
|
|
2
|
+
import { dirname, relative } from 'node:path';
|
|
3
3
|
import { parse as parseCronExpression } from '@datasert/cronjs-parser';
|
|
4
4
|
import { generate } from 'astring';
|
|
5
5
|
import type { BuildMetadata } from '../../types';
|
|
@@ -910,8 +910,11 @@ export async function parseRoute(
|
|
|
910
910
|
projectId: string,
|
|
911
911
|
deploymentId: string
|
|
912
912
|
): Promise<BuildMetadata['routes']> {
|
|
913
|
-
const
|
|
914
|
-
const version = hash(
|
|
913
|
+
const rawContents = await Bun.file(filename).text();
|
|
914
|
+
const version = hash(rawContents);
|
|
915
|
+
// Transpile TypeScript to JavaScript so acorn-loose can parse it properly
|
|
916
|
+
const transpiler = new Bun.Transpiler({ loader: 'ts', target: 'bun' });
|
|
917
|
+
const contents = transpiler.transformSync(rawContents);
|
|
915
918
|
const ast = acornLoose.parse(contents, {
|
|
916
919
|
locations: true,
|
|
917
920
|
ecmaVersion: 'latest',
|
|
@@ -992,12 +995,24 @@ export async function parseRoute(
|
|
|
992
995
|
}
|
|
993
996
|
|
|
994
997
|
const rel = relative(rootDir, filename);
|
|
995
|
-
const dir = dirname(filename);
|
|
996
|
-
const name = basename(dir);
|
|
997
998
|
|
|
998
999
|
// For src/api/index.ts, we don't want to add the folder name since it's the root API router
|
|
999
1000
|
const isRootApi = filename.includes('src/api/index.ts');
|
|
1000
|
-
|
|
1001
|
+
|
|
1002
|
+
// For nested routes, use the full path from src/api/ instead of just the immediate parent
|
|
1003
|
+
// e.g., src/api/v1/users/route.ts -> routeName = "v1/users"
|
|
1004
|
+
// src/api/auth/route.ts -> routeName = "auth"
|
|
1005
|
+
// src/api/test.ts -> routeName = "" (file directly in src/api/)
|
|
1006
|
+
let routeName = '';
|
|
1007
|
+
if (!isRootApi) {
|
|
1008
|
+
const apiMatch = filename.match(/src\/api\/(.+?)\/[^/]+\.ts$/);
|
|
1009
|
+
if (apiMatch) {
|
|
1010
|
+
// File in subdirectory: src/api/auth/route.ts -> "auth"
|
|
1011
|
+
routeName = apiMatch[1];
|
|
1012
|
+
}
|
|
1013
|
+
// For files directly in src/api/ (e.g., test.ts), routeName stays empty
|
|
1014
|
+
// This prevents double /api prefix since these files often define full paths
|
|
1015
|
+
}
|
|
1001
1016
|
|
|
1002
1017
|
const routes: RouteDefinition = [];
|
|
1003
1018
|
const routePrefix = '/api';
|
package/src/cmd/build/bundler.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { cpSync, existsSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
|
|
|
4
4
|
import gitParseUrl from 'git-url-parse';
|
|
5
5
|
import { StructuredError } from '@agentuity/core';
|
|
6
6
|
import * as tui from '../../tui';
|
|
7
|
+
import { pauseStepUI } from '../../steps';
|
|
7
8
|
import AgentuityBundler, { getBuildMetadata } from './plugin';
|
|
8
9
|
import { getFilesRecursively } from './file';
|
|
9
10
|
import { getVersion } from '../../version';
|
|
@@ -16,25 +17,38 @@ import { type DeployOptions } from '../../schemas/deploy';
|
|
|
16
17
|
|
|
17
18
|
const minBunVersion = '>=1.3.3';
|
|
18
19
|
|
|
19
|
-
async function checkBunVersion() {
|
|
20
|
+
async function checkBunVersion(): Promise<string[]> {
|
|
20
21
|
if (semver.satisfies(Bun.version, minBunVersion)) {
|
|
21
|
-
return;
|
|
22
|
+
return []; // Version is OK, no output needed
|
|
22
23
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
24
|
+
|
|
25
|
+
const message = `Bun is using version ${Bun.version}. This project requires Bun version ${minBunVersion} to build.`;
|
|
26
|
+
|
|
27
|
+
if (process.stdin.isTTY && process.stdout.isTTY) {
|
|
28
|
+
// Pause the step UI for interactive prompt
|
|
29
|
+
const resume = pauseStepUI();
|
|
30
|
+
|
|
31
|
+
tui.warning(message);
|
|
32
|
+
const ok = await tui.confirm('Would you like to upgrade now?');
|
|
33
|
+
|
|
34
|
+
// Small delay to ensure console.log('') in confirm completes
|
|
35
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
36
|
+
|
|
37
|
+
resume(); // Resume step UI
|
|
38
|
+
|
|
27
39
|
if (ok) {
|
|
28
40
|
await $`bun upgrade`.quiet();
|
|
29
41
|
const version = (await $`bun -v`.quiet().text()).trim();
|
|
30
|
-
|
|
31
|
-
return;
|
|
42
|
+
// Return success message to show in output box
|
|
43
|
+
return [tui.colorSuccess(`Upgraded Bun to ${version}`)];
|
|
32
44
|
}
|
|
33
45
|
}
|
|
46
|
+
|
|
47
|
+
// Failed to upgrade or user declined
|
|
34
48
|
throw new InvalidBunVersion({
|
|
35
49
|
current: Bun.version,
|
|
36
50
|
required: minBunVersion,
|
|
37
|
-
message
|
|
51
|
+
message,
|
|
38
52
|
});
|
|
39
53
|
}
|
|
40
54
|
|
|
@@ -102,7 +116,9 @@ export async function bundle({
|
|
|
102
116
|
env,
|
|
103
117
|
region,
|
|
104
118
|
logger,
|
|
105
|
-
}: BundleOptions) {
|
|
119
|
+
}: BundleOptions): Promise<{ output: string[] }> {
|
|
120
|
+
const output: string[] = [];
|
|
121
|
+
|
|
106
122
|
const appFile = join(rootDir, 'app.ts');
|
|
107
123
|
if (!existsSync(appFile)) {
|
|
108
124
|
throw new AppFileNotFoundError({
|
|
@@ -110,7 +126,8 @@ export async function bundle({
|
|
|
110
126
|
});
|
|
111
127
|
}
|
|
112
128
|
|
|
113
|
-
await checkBunVersion();
|
|
129
|
+
const versionOutput = await checkBunVersion();
|
|
130
|
+
output.push(...versionOutput);
|
|
114
131
|
|
|
115
132
|
const outDir = customOutDir ?? join(rootDir, '.agentuity');
|
|
116
133
|
const srcDir = join(rootDir, 'src');
|
|
@@ -715,4 +732,6 @@ export async function bundle({
|
|
|
715
732
|
`${outDir}/.routemapping.json`,
|
|
716
733
|
dev ? JSON.stringify(routeMapping, null, 2) : JSON.stringify(routeMapping)
|
|
717
734
|
);
|
|
735
|
+
|
|
736
|
+
return { output };
|
|
718
737
|
}
|
package/src/cmd/build/plugin.ts
CHANGED
|
@@ -16,6 +16,7 @@ import { createLogger } from '@agentuity/server';
|
|
|
16
16
|
import type { LogLevel } from '../../types';
|
|
17
17
|
import { toCamelCase, toPascalCase } from '../../utils/string';
|
|
18
18
|
import { generateRouteRegistry, type RouteInfo } from './route-registry';
|
|
19
|
+
import { discoverRouteFiles } from './route-discovery';
|
|
19
20
|
|
|
20
21
|
/**
|
|
21
22
|
* Setup lifecycle types by analyzing app.ts for setup() function
|
|
@@ -461,96 +462,116 @@ import { readFileSync, existsSync } from 'node:fs';
|
|
|
461
462
|
const apiRoutesMetadata: BuildMetadata['routes'] = [];
|
|
462
463
|
const routeInfoList: RouteInfo[] = [];
|
|
463
464
|
const apiDir = join(srcDir, 'api');
|
|
465
|
+
// Track subdirectory routes for auto-mounting
|
|
466
|
+
const subRouteInserts: string[] = [];
|
|
464
467
|
if (existsSync(apiDir)) {
|
|
465
|
-
|
|
466
|
-
const
|
|
467
|
-
|
|
468
|
-
|
|
468
|
+
// Use recursive route discovery to find all route files in subdirectories
|
|
469
|
+
const discoveredRoutes = discoverRouteFiles(apiDir);
|
|
470
|
+
|
|
471
|
+
// Collect all API files: index.ts and discovered subdirectory routes
|
|
472
|
+
const apiFiles: string[] = [];
|
|
473
|
+
|
|
474
|
+
// Check for root index.ts
|
|
475
|
+
const indexFile = join(apiDir, 'index.ts');
|
|
476
|
+
if (existsSync(indexFile)) {
|
|
477
|
+
apiFiles.push(indexFile);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// Add all discovered route files
|
|
481
|
+
for (const route of discoveredRoutes) {
|
|
482
|
+
apiFiles.push(route.filepath);
|
|
483
|
+
|
|
484
|
+
// Generate auto-mount code for this subdirectory route
|
|
485
|
+
subRouteInserts.push(`await (async() => {
|
|
486
|
+
const { getRouter } = await import('@agentuity/runtime');
|
|
487
|
+
const router = getRouter()!;
|
|
488
|
+
const ${route.variableName} = (await import('${route.importPath}')).default;
|
|
489
|
+
router.route('${route.mountPath}', ${route.variableName});
|
|
490
|
+
})();`);
|
|
491
|
+
}
|
|
469
492
|
|
|
470
493
|
for (const apiFile of apiFiles) {
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
const routes = await parseRoute(rootDir, apiFile, projectId, deploymentId);
|
|
474
|
-
|
|
475
|
-
// Extract schemas from agents for routes that use validators
|
|
476
|
-
for (const route of routes) {
|
|
477
|
-
// Check if route has custom schema overrides from validator({ input, output })
|
|
478
|
-
const hasCustomInput = route.config?.inputSchemaVariable;
|
|
479
|
-
const hasCustomOutput = route.config?.outputSchemaVariable;
|
|
480
|
-
|
|
481
|
-
// If route uses agent.validator(), get schemas from the agent (unless overridden)
|
|
482
|
-
if (
|
|
483
|
-
route.config?.agentImportPath &&
|
|
484
|
-
(!hasCustomInput || !hasCustomOutput)
|
|
485
|
-
) {
|
|
486
|
-
const agentImportPath = route.config.agentImportPath as string;
|
|
487
|
-
// Match by import path: @agent/zod-test -> src/agent/zod-test/agent.ts
|
|
488
|
-
// Normalize import path by removing leading '@' -> agent/zod-test
|
|
489
|
-
const importPattern = agentImportPath.replace(/^@/, '');
|
|
490
|
-
// Escape regex special characters for safe pattern matching
|
|
491
|
-
const escapedPattern = importPattern.replace(
|
|
492
|
-
/[.*+?^${}()|[\]\\]/g,
|
|
493
|
-
'\\$&'
|
|
494
|
-
);
|
|
495
|
-
// Match as complete path segment to avoid false positives (e.g., "agent/hello" matching "agent/hello-world")
|
|
496
|
-
const segmentPattern = new RegExp(`(^|/)${escapedPattern}(/|$)`);
|
|
497
|
-
|
|
498
|
-
for (const [, agentMd] of agentMetadata) {
|
|
499
|
-
const agentFilename = agentMd.get('filename');
|
|
500
|
-
if (agentFilename && segmentPattern.test(agentFilename)) {
|
|
501
|
-
// Use agent schemas unless overridden
|
|
502
|
-
const inputSchemaCode = hasCustomInput
|
|
503
|
-
? undefined
|
|
504
|
-
: agentMd.get('inputSchemaCode');
|
|
505
|
-
const outputSchemaCode = hasCustomOutput
|
|
506
|
-
? undefined
|
|
507
|
-
: agentMd.get('outputSchemaCode');
|
|
508
|
-
|
|
509
|
-
if (inputSchemaCode || outputSchemaCode) {
|
|
510
|
-
route.schema = {
|
|
511
|
-
input: inputSchemaCode,
|
|
512
|
-
output: outputSchemaCode,
|
|
513
|
-
};
|
|
514
|
-
}
|
|
515
|
-
break;
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
}
|
|
494
|
+
try {
|
|
495
|
+
const routes = await parseRoute(rootDir, apiFile, projectId, deploymentId);
|
|
519
496
|
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
}
|
|
497
|
+
// Extract schemas from agents for routes that use validators
|
|
498
|
+
for (const route of routes) {
|
|
499
|
+
// Check if route has custom schema overrides from validator({ input, output })
|
|
500
|
+
const hasCustomInput = route.config?.inputSchemaVariable;
|
|
501
|
+
const hasCustomOutput = route.config?.outputSchemaVariable;
|
|
523
502
|
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
// Collect route info for RouteRegistry generation
|
|
527
|
-
for (const route of routes) {
|
|
528
|
-
routeInfoList.push({
|
|
529
|
-
method: route.method.toUpperCase(),
|
|
530
|
-
path: route.path,
|
|
531
|
-
filename: route.filename,
|
|
532
|
-
hasValidator: route.config?.hasValidator === true,
|
|
533
|
-
routeType: route.type || 'api',
|
|
534
|
-
agentVariable: route.config?.agentVariable as string | undefined,
|
|
535
|
-
agentImportPath: route.config?.agentImportPath as string | undefined,
|
|
536
|
-
inputSchemaVariable: route.config?.inputSchemaVariable as
|
|
537
|
-
| string
|
|
538
|
-
| undefined,
|
|
539
|
-
outputSchemaVariable: route.config?.outputSchemaVariable as
|
|
540
|
-
| string
|
|
541
|
-
| undefined,
|
|
542
|
-
});
|
|
543
|
-
}
|
|
544
|
-
} catch (error) {
|
|
545
|
-
// Skip files that don't have createRouter (they might be utilities)
|
|
503
|
+
// If route uses agent.validator(), get schemas from the agent (unless overridden)
|
|
546
504
|
if (
|
|
547
|
-
|
|
548
|
-
|
|
505
|
+
route.config?.agentImportPath &&
|
|
506
|
+
(!hasCustomInput || !hasCustomOutput)
|
|
549
507
|
) {
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
508
|
+
const agentImportPath = route.config.agentImportPath as string;
|
|
509
|
+
// Match by import path: @agent/zod-test -> src/agent/zod-test/agent.ts
|
|
510
|
+
// Normalize import path by removing leading '@' -> agent/zod-test
|
|
511
|
+
const importPattern = agentImportPath.replace(/^@/, '');
|
|
512
|
+
// Escape regex special characters for safe pattern matching
|
|
513
|
+
const escapedPattern = importPattern.replace(
|
|
514
|
+
/[.*+?^${}()|[\]\\]/g,
|
|
515
|
+
'\\$&'
|
|
516
|
+
);
|
|
517
|
+
// Match as complete path segment to avoid false positives (e.g., "agent/hello" matching "agent/hello-world")
|
|
518
|
+
const segmentPattern = new RegExp(`(^|/)${escapedPattern}(/|$)`);
|
|
519
|
+
|
|
520
|
+
for (const [, agentMd] of agentMetadata) {
|
|
521
|
+
const agentFilename = agentMd.get('filename');
|
|
522
|
+
if (agentFilename && segmentPattern.test(agentFilename)) {
|
|
523
|
+
// Use agent schemas unless overridden
|
|
524
|
+
const inputSchemaCode = hasCustomInput
|
|
525
|
+
? undefined
|
|
526
|
+
: agentMd.get('inputSchemaCode');
|
|
527
|
+
const outputSchemaCode = hasCustomOutput
|
|
528
|
+
? undefined
|
|
529
|
+
: agentMd.get('outputSchemaCode');
|
|
530
|
+
|
|
531
|
+
if (inputSchemaCode || outputSchemaCode) {
|
|
532
|
+
route.schema = {
|
|
533
|
+
input: inputSchemaCode,
|
|
534
|
+
output: outputSchemaCode,
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
break;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
553
540
|
}
|
|
541
|
+
|
|
542
|
+
// TODO: Extract inline schema code from custom validator({ input: z.string(), output: ... })
|
|
543
|
+
// For now, custom schema overrides with inline code are not extracted (would require parsing the validator call's object expression)
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
apiRoutesMetadata.push(...routes);
|
|
547
|
+
|
|
548
|
+
// Collect route info for RouteRegistry generation
|
|
549
|
+
for (const route of routes) {
|
|
550
|
+
routeInfoList.push({
|
|
551
|
+
method: route.method.toUpperCase(),
|
|
552
|
+
path: route.path,
|
|
553
|
+
filename: route.filename,
|
|
554
|
+
hasValidator: route.config?.hasValidator === true,
|
|
555
|
+
routeType: route.type || 'api',
|
|
556
|
+
agentVariable: route.config?.agentVariable as string | undefined,
|
|
557
|
+
agentImportPath: route.config?.agentImportPath as string | undefined,
|
|
558
|
+
inputSchemaVariable: route.config?.inputSchemaVariable as
|
|
559
|
+
| string
|
|
560
|
+
| undefined,
|
|
561
|
+
outputSchemaVariable: route.config?.outputSchemaVariable as
|
|
562
|
+
| string
|
|
563
|
+
| undefined,
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
} catch (error) {
|
|
567
|
+
// Skip files that don't have createRouter (they might be utilities)
|
|
568
|
+
if (
|
|
569
|
+
error instanceof Error &&
|
|
570
|
+
error.message.includes('could not find an proper createRouter')
|
|
571
|
+
) {
|
|
572
|
+
logger.trace(`Skipping ${apiFile}: no createRouter found`);
|
|
573
|
+
} else {
|
|
574
|
+
throw error;
|
|
554
575
|
}
|
|
555
576
|
}
|
|
556
577
|
}
|
|
@@ -573,6 +594,11 @@ import { readFileSync, existsSync } from 'node:fs';
|
|
|
573
594
|
})();`);
|
|
574
595
|
}
|
|
575
596
|
|
|
597
|
+
// Auto-mount subdirectory routes (src/api/foo/route.ts -> /api/foo)
|
|
598
|
+
for (const subRouteInsert of subRouteInserts) {
|
|
599
|
+
inserts.push(subRouteInsert);
|
|
600
|
+
}
|
|
601
|
+
|
|
576
602
|
// Only create the workbench routes if workbench is actually configured
|
|
577
603
|
if (workbenchConfig) {
|
|
578
604
|
inserts.push(`await (async() => {
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { existsSync, readdirSync, lstatSync } from 'node:fs';
|
|
2
|
+
import { join, relative } from 'node:path';
|
|
3
|
+
import { toCamelCase } from '../../utils/string';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Information about a discovered route file
|
|
7
|
+
*/
|
|
8
|
+
export interface DiscoveredRouteFile {
|
|
9
|
+
/** Full path to the route file */
|
|
10
|
+
filepath: string;
|
|
11
|
+
/** Relative path from apiDir (e.g., 'auth/route.ts', 'v1/users/route.ts') */
|
|
12
|
+
relativePath: string;
|
|
13
|
+
/** Mount path for the route (e.g., '/api/auth', '/api/v1/users') */
|
|
14
|
+
mountPath: string;
|
|
15
|
+
/** Safe variable name for importing (e.g., 'authRoute', 'v1UsersRoute') */
|
|
16
|
+
variableName: string;
|
|
17
|
+
/** Import path relative to build output (e.g., './src/api/auth/route') */
|
|
18
|
+
importPath: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Recursively discover all TypeScript route files in an API directory
|
|
23
|
+
* Supports nested structures like:
|
|
24
|
+
* - src/api/index.ts (root API router)
|
|
25
|
+
* - src/api/auth/route.ts -> mounted at /api/auth
|
|
26
|
+
* - src/api/v1/users/route.ts -> mounted at /api/v1/users
|
|
27
|
+
* - src/api/admin/users/login.ts -> mounted at /api/admin/users (any .ts file works)
|
|
28
|
+
*
|
|
29
|
+
* @param apiDir - Absolute path to the src/api directory
|
|
30
|
+
* @param currentDir - Current directory being scanned (used for recursion)
|
|
31
|
+
* @param results - Accumulated results (used for recursion)
|
|
32
|
+
* @returns Array of discovered route files with mount information
|
|
33
|
+
*/
|
|
34
|
+
export function discoverRouteFiles(
|
|
35
|
+
apiDir: string,
|
|
36
|
+
currentDir: string = apiDir,
|
|
37
|
+
results: DiscoveredRouteFile[] = []
|
|
38
|
+
): DiscoveredRouteFile[] {
|
|
39
|
+
if (!existsSync(currentDir)) {
|
|
40
|
+
return results;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const entries = readdirSync(currentDir);
|
|
44
|
+
|
|
45
|
+
for (const entry of entries) {
|
|
46
|
+
const entryPath = join(currentDir, entry);
|
|
47
|
+
const stat = lstatSync(entryPath);
|
|
48
|
+
|
|
49
|
+
// Skip symlinks to prevent infinite recursion
|
|
50
|
+
if (stat.isSymbolicLink()) {
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (stat.isFile() && entry.endsWith('.ts') && !entry.endsWith('.generated.ts')) {
|
|
55
|
+
// Found a TypeScript file
|
|
56
|
+
const relativePath = relative(apiDir, entryPath);
|
|
57
|
+
const isRootIndex = relativePath === 'index.ts';
|
|
58
|
+
|
|
59
|
+
// Skip root index.ts - it's handled separately
|
|
60
|
+
if (isRootIndex) {
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// For subdirectory files, determine mount path
|
|
65
|
+
// src/api/auth/route.ts -> /api/auth
|
|
66
|
+
// src/api/v1/users/route.ts -> /api/v1/users
|
|
67
|
+
// src/api/admin/login.ts -> /api/admin
|
|
68
|
+
const pathParts = relativePath.split('/');
|
|
69
|
+
pathParts.pop(); // Remove filename
|
|
70
|
+
|
|
71
|
+
// Skip files directly in src/api/ to avoid mount path conflicts with root index.ts
|
|
72
|
+
if (pathParts.length === 0) {
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const mountPath = `/api/${pathParts.join('/')}`;
|
|
77
|
+
|
|
78
|
+
// Generate safe variable name
|
|
79
|
+
// auth/route.ts -> authRoute
|
|
80
|
+
// v1/users/route.ts -> v1UsersRoute
|
|
81
|
+
// admin/login.ts -> adminLoginRoute
|
|
82
|
+
const variableParts = pathParts.map((p, idx) => {
|
|
83
|
+
const camel = toCamelCase(p);
|
|
84
|
+
// Capitalize first letter of all parts except the first
|
|
85
|
+
return idx === 0 ? camel : camel.charAt(0).toUpperCase() + camel.slice(1);
|
|
86
|
+
});
|
|
87
|
+
const baseName = entry.replace('.ts', '');
|
|
88
|
+
if (baseName !== 'route' && baseName !== 'index') {
|
|
89
|
+
const camelBase = toCamelCase(baseName);
|
|
90
|
+
// Always capitalize the base name since it's not the first part
|
|
91
|
+
variableParts.push(camelBase.charAt(0).toUpperCase() + camelBase.slice(1));
|
|
92
|
+
}
|
|
93
|
+
const variableName = variableParts.join('') + 'Route';
|
|
94
|
+
|
|
95
|
+
// Generate import path relative to build output
|
|
96
|
+
// src/api/auth/route.ts -> ./src/api/auth/route
|
|
97
|
+
const importPath = './src/api/' + relativePath.replace('.ts', '');
|
|
98
|
+
|
|
99
|
+
results.push({
|
|
100
|
+
filepath: entryPath,
|
|
101
|
+
relativePath,
|
|
102
|
+
mountPath,
|
|
103
|
+
variableName,
|
|
104
|
+
importPath,
|
|
105
|
+
});
|
|
106
|
+
} else if (stat.isDirectory()) {
|
|
107
|
+
// Recursively scan subdirectories
|
|
108
|
+
discoverRouteFiles(apiDir, entryPath, results);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return results;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Detect potential route path conflicts
|
|
117
|
+
*
|
|
118
|
+
* @param routes - Array of route metadata with method and path
|
|
119
|
+
* @returns Array of conflict descriptions
|
|
120
|
+
*/
|
|
121
|
+
export interface RouteConflict {
|
|
122
|
+
type: 'duplicate' | 'ambiguous-param' | 'wildcard-overlap';
|
|
123
|
+
routes: Array<{ method: string; path: string; filename: string }>;
|
|
124
|
+
message: string;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function detectRouteConflicts(
|
|
128
|
+
routes: Array<{ method: string; path: string; filename: string }>
|
|
129
|
+
): RouteConflict[] {
|
|
130
|
+
const conflicts: RouteConflict[] = [];
|
|
131
|
+
|
|
132
|
+
// Group routes by method+path
|
|
133
|
+
const methodPathMap = new Map<string, Array<{ path: string; filename: string }>>();
|
|
134
|
+
|
|
135
|
+
for (const route of routes) {
|
|
136
|
+
const key = `${route.method.toUpperCase()} ${route.path}`;
|
|
137
|
+
if (!methodPathMap.has(key)) {
|
|
138
|
+
methodPathMap.set(key, []);
|
|
139
|
+
}
|
|
140
|
+
methodPathMap.get(key)!.push({ path: route.path, filename: route.filename });
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Check for exact duplicates
|
|
144
|
+
for (const [methodPath, routeList] of methodPathMap.entries()) {
|
|
145
|
+
if (routeList.length > 1) {
|
|
146
|
+
const [method] = methodPath.split(' ', 2);
|
|
147
|
+
conflicts.push({
|
|
148
|
+
type: 'duplicate',
|
|
149
|
+
routes: routeList.map((r) => ({ method, path: r.path, filename: r.filename })),
|
|
150
|
+
message: `Duplicate route: ${methodPath} defined in ${routeList.length} files`,
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Check for ambiguous parameter routes (same method, different param names)
|
|
156
|
+
// e.g., GET /users/:id and GET /users/:userId
|
|
157
|
+
const methodGroups = new Map<string, Array<{ path: string; filename: string }>>();
|
|
158
|
+
for (const route of routes) {
|
|
159
|
+
const method = route.method.toUpperCase();
|
|
160
|
+
if (!methodGroups.has(method)) {
|
|
161
|
+
methodGroups.set(method, []);
|
|
162
|
+
}
|
|
163
|
+
methodGroups.get(method)!.push({ path: route.path, filename: route.filename });
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
for (const [method, routeList] of methodGroups.entries()) {
|
|
167
|
+
// Normalize params to check for conflicts
|
|
168
|
+
const normalized = routeList.map((r) => ({
|
|
169
|
+
...r,
|
|
170
|
+
normalizedPath: r.path.replace(/:[^/]+/g, ':param'),
|
|
171
|
+
}));
|
|
172
|
+
|
|
173
|
+
const pathMap = new Map<string, Array<{ path: string; filename: string }>>();
|
|
174
|
+
for (const route of normalized) {
|
|
175
|
+
if (!pathMap.has(route.normalizedPath)) {
|
|
176
|
+
pathMap.set(route.normalizedPath, []);
|
|
177
|
+
}
|
|
178
|
+
pathMap.get(route.normalizedPath)!.push({ path: route.path, filename: route.filename });
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
for (const [normalizedPath, paths] of pathMap.entries()) {
|
|
182
|
+
if (paths.length > 1 && normalizedPath.includes(':param')) {
|
|
183
|
+
// Check if the actual param names differ
|
|
184
|
+
const uniquePaths = new Set(paths.map((p) => p.path));
|
|
185
|
+
if (uniquePaths.size > 1) {
|
|
186
|
+
conflicts.push({
|
|
187
|
+
type: 'ambiguous-param',
|
|
188
|
+
routes: paths.map(({ path, filename }) => ({ method, path, filename })),
|
|
189
|
+
message: `Ambiguous param routes: ${method} ${Array.from(uniquePaths).join(', ')}`,
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return conflicts;
|
|
197
|
+
}
|
|
@@ -37,13 +37,13 @@ export interface RouteInfo {
|
|
|
37
37
|
* @param routes - Array of route information
|
|
38
38
|
*/
|
|
39
39
|
export function generateRouteRegistry(srcDir: string, routes: RouteInfo[]): void {
|
|
40
|
-
// Filter routes by type
|
|
41
|
-
const apiRoutes = routes.filter((r) => r.
|
|
42
|
-
const websocketRoutes = routes.filter((r) => r.
|
|
43
|
-
const sseRoutes = routes.filter((r) => r.
|
|
40
|
+
// Filter routes by type (include ALL routes, not just those with validators)
|
|
41
|
+
const apiRoutes = routes.filter((r) => r.routeType === 'api');
|
|
42
|
+
const websocketRoutes = routes.filter((r) => r.routeType === 'websocket');
|
|
43
|
+
const sseRoutes = routes.filter((r) => r.routeType === 'sse');
|
|
44
44
|
|
|
45
45
|
if (apiRoutes.length === 0 && websocketRoutes.length === 0 && sseRoutes.length === 0) {
|
|
46
|
-
// No
|
|
46
|
+
// No routes, skip generation
|
|
47
47
|
return;
|
|
48
48
|
}
|
|
49
49
|
|
|
@@ -52,11 +52,15 @@ export function generateRouteRegistry(srcDir: string, routes: RouteInfo[]): void
|
|
|
52
52
|
const agentImports = new Map<string, string>(); // Maps agent variable to unique import name
|
|
53
53
|
const schemaImports = new Set<string>(); // Track which schema variables we've seen
|
|
54
54
|
|
|
55
|
-
// Combine all
|
|
56
|
-
const
|
|
55
|
+
// Combine all routes for import collection
|
|
56
|
+
const allRoutes = [...apiRoutes, ...websocketRoutes, ...sseRoutes];
|
|
57
57
|
|
|
58
|
-
// First pass: collect all unique agents and schema variables
|
|
59
|
-
|
|
58
|
+
// First pass: collect all unique agents and schema variables (only for routes with validators)
|
|
59
|
+
allRoutes.forEach((route) => {
|
|
60
|
+
// Skip routes without validators - they won't need imports
|
|
61
|
+
if (!route.hasValidator) {
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
60
64
|
// If this route uses an agent, import it directly
|
|
61
65
|
if (route.agentVariable && route.agentImportPath && !agentImports.has(route.agentVariable)) {
|
|
62
66
|
// Resolve the import path (could be @agent/hello, ../shared, etc.)
|
|
@@ -90,7 +94,11 @@ export function generateRouteRegistry(srcDir: string, routes: RouteInfo[]): void
|
|
|
90
94
|
|
|
91
95
|
// Import schema variables from route files
|
|
92
96
|
const routeFileImports = new Map<string, Set<string>>(); // Maps route file to schema variables
|
|
93
|
-
|
|
97
|
+
allRoutes.forEach((route) => {
|
|
98
|
+
// Only import schemas for routes with validators
|
|
99
|
+
if (!route.hasValidator) {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
94
102
|
if (route.inputSchemaVariable || route.outputSchemaVariable) {
|
|
95
103
|
const filename = route.filename.replace(/\\/g, '/');
|
|
96
104
|
const importPath = `../${filename.replace(/\.ts$/, '')}`;
|
|
@@ -120,6 +128,14 @@ export function generateRouteRegistry(srcDir: string, routes: RouteInfo[]): void
|
|
|
120
128
|
const generateRouteEntry = (route: RouteInfo): string => {
|
|
121
129
|
const routeKey = route.path; // Use path only for websocket/sse, or METHOD path for API
|
|
122
130
|
|
|
131
|
+
// If route doesn't have a validator, use never for schemas
|
|
132
|
+
if (!route.hasValidator) {
|
|
133
|
+
return ` '${routeKey}': {
|
|
134
|
+
inputSchema: never;
|
|
135
|
+
outputSchema: never;
|
|
136
|
+
};`;
|
|
137
|
+
}
|
|
138
|
+
|
|
123
139
|
// If we have an agent variable, we can infer types from it
|
|
124
140
|
if (route.agentVariable) {
|
|
125
141
|
const importName = agentImports.get(route.agentVariable)!;
|