@duct-sdk/sdk 0.1.6

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.
Files changed (70) hide show
  1. package/README.md +92 -0
  2. package/dist/adapters/next/index.d.ts +4 -0
  3. package/dist/adapters/next/index.js +5 -0
  4. package/dist/adapters/next/receiver.d.ts +44 -0
  5. package/dist/adapters/next/receiver.js +162 -0
  6. package/dist/adapters/next/shell.d.ts +88 -0
  7. package/dist/adapters/next/shell.js +255 -0
  8. package/dist/adapters/react/index.d.ts +2 -0
  9. package/dist/adapters/react/index.js +4 -0
  10. package/dist/adapters/react/shell.d.ts +88 -0
  11. package/dist/adapters/react/shell.js +255 -0
  12. package/dist/adapters/remix/index.d.ts +2 -0
  13. package/dist/adapters/remix/index.js +4 -0
  14. package/dist/adapters/remix/receiver.d.ts +44 -0
  15. package/dist/adapters/remix/receiver.js +153 -0
  16. package/dist/adapters/sveltekit/index.d.ts +2 -0
  17. package/dist/adapters/sveltekit/index.js +4 -0
  18. package/dist/adapters/sveltekit/receiver.d.ts +56 -0
  19. package/dist/adapters/sveltekit/receiver.js +154 -0
  20. package/dist/adapters/vite/index.d.ts +2 -0
  21. package/dist/adapters/vite/index.js +4 -0
  22. package/dist/adapters/vite/receiver.d.ts +82 -0
  23. package/dist/adapters/vite/receiver.js +164 -0
  24. package/dist/assets/logo.d.ts +1 -0
  25. package/dist/assets/logo.js +1 -0
  26. package/dist/cli/agents/api-agent.d.ts +14 -0
  27. package/dist/cli/agents/api-agent.js +656 -0
  28. package/dist/cli/agents/auth-agent.d.ts +6 -0
  29. package/dist/cli/agents/auth-agent.js +198 -0
  30. package/dist/cli/agents/deeplink-agent.d.ts +6 -0
  31. package/dist/cli/agents/deeplink-agent.js +263 -0
  32. package/dist/cli/agents/llm.d.ts +33 -0
  33. package/dist/cli/agents/llm.js +276 -0
  34. package/dist/cli/agents/pipeline.d.ts +51 -0
  35. package/dist/cli/agents/pipeline.js +236 -0
  36. package/dist/cli/agents/reviewer-agent.d.ts +11 -0
  37. package/dist/cli/agents/reviewer-agent.js +442 -0
  38. package/dist/cli/agents/route-agent.d.ts +13 -0
  39. package/dist/cli/agents/route-agent.js +346 -0
  40. package/dist/cli/detectors/auth.d.ts +18 -0
  41. package/dist/cli/detectors/auth.js +273 -0
  42. package/dist/cli/detectors/framework.d.ts +22 -0
  43. package/dist/cli/detectors/framework.js +242 -0
  44. package/dist/cli/drift.d.ts +39 -0
  45. package/dist/cli/drift.js +247 -0
  46. package/dist/cli/fs/sandbox.d.ts +77 -0
  47. package/dist/cli/fs/sandbox.js +295 -0
  48. package/dist/cli/generators/config.d.ts +7 -0
  49. package/dist/cli/generators/config.js +255 -0
  50. package/dist/cli/generators/receiver.d.ts +12 -0
  51. package/dist/cli/generators/receiver.js +683 -0
  52. package/dist/cli/generators/shell.d.ts +18 -0
  53. package/dist/cli/generators/shell.js +672 -0
  54. package/dist/cli/index.d.ts +2 -0
  55. package/dist/cli/index.js +603 -0
  56. package/dist/cli/init.d.ts +26 -0
  57. package/dist/cli/init.js +835 -0
  58. package/dist/core/action.d.ts +37 -0
  59. package/dist/core/action.js +140 -0
  60. package/dist/core/config.d.ts +514 -0
  61. package/dist/core/config.js +221 -0
  62. package/dist/core/endpoints.d.ts +17 -0
  63. package/dist/core/endpoints.js +128 -0
  64. package/dist/core/token.d.ts +70 -0
  65. package/dist/core/token.js +174 -0
  66. package/dist/core/types.d.ts +450 -0
  67. package/dist/core/types.js +11 -0
  68. package/dist/index.d.ts +7 -0
  69. package/dist/index.js +9 -0
  70. package/package.json +84 -0
@@ -0,0 +1,346 @@
1
+ // ============================================================
2
+ // @duct/sdk — Route Agent
3
+ // Analyzes project routes and produces RouteManifest[]
4
+ // ============================================================
5
+ import { callDuctLLM } from "./llm.js";
6
+ // ── Next.js App Router ─────────────────────────────────────
7
+ class NextAppRouterScanner {
8
+ name = "NextAppRouter";
9
+ async detect(fs) {
10
+ return (await fs.exists("app")) || (await fs.exists("src/app"));
11
+ }
12
+ async appendPromptContext(fs, lines) {
13
+ for (const dir of ["app", "src/app"]) {
14
+ if (!(await fs.exists(dir)))
15
+ continue;
16
+ lines.push(`\n## Next.js App Router: ${dir}/`);
17
+ const pageFiles = await fs.findFiles(`${dir}/**/page.{ts,tsx,js,jsx}`);
18
+ lines.push(`Found ${pageFiles.length} page files:`);
19
+ for (const f of pageFiles.slice(0, 50))
20
+ lines.push(` - ${f}`);
21
+ // Layout files — indicate auth wrapping
22
+ const layoutFiles = await fs.findFiles(`${dir}/**/layout.{ts,tsx,js,jsx}`);
23
+ for (const lf of layoutFiles.slice(0, 5)) {
24
+ const content = await fs.readFile(lf);
25
+ if (!content)
26
+ continue;
27
+ lines.push(`\n### ${lf} (layout — check for auth wrappers):`);
28
+ lines.push("```tsx");
29
+ lines.push(content.slice(0, 1500));
30
+ lines.push("```");
31
+ }
32
+ // Sample page files — detect auth calls, component imports, useSearchParams
33
+ for (const pf of pageFiles.slice(0, 8)) {
34
+ const content = await fs.readFile(pf);
35
+ if (!content)
36
+ continue;
37
+ lines.push(`\n### ${pf}:`);
38
+ lines.push("```tsx");
39
+ lines.push(content.slice(0, 1200));
40
+ lines.push("```");
41
+ }
42
+ }
43
+ }
44
+ }
45
+ // ── Next.js Pages Router ────────────────────────────────────
46
+ class NextPagesRouterScanner {
47
+ name = "NextPagesRouter";
48
+ async detect(fs) {
49
+ return (await fs.exists("pages")) || (await fs.exists("src/pages"));
50
+ }
51
+ async appendPromptContext(fs, lines) {
52
+ for (const dir of ["pages", "src/pages"]) {
53
+ if (!(await fs.exists(dir)))
54
+ continue;
55
+ lines.push(`\n## Next.js Pages Router: ${dir}/`);
56
+ const allFiles = await fs.findFiles(`${dir}/**/*.{ts,tsx,js,jsx}`);
57
+ const pageFiles = allFiles.filter((f) => !f.includes("/api/") &&
58
+ !f.includes("_app") &&
59
+ !f.includes("_document") &&
60
+ !f.includes("_error"));
61
+ lines.push(`Found ${pageFiles.length} page files (API routes excluded):`);
62
+ for (const f of pageFiles.slice(0, 50))
63
+ lines.push(` - ${f}`);
64
+ for (const pf of pageFiles.slice(0, 8)) {
65
+ const content = await fs.readFile(pf);
66
+ if (!content)
67
+ continue;
68
+ lines.push(`\n### ${pf}:`);
69
+ lines.push("```tsx");
70
+ lines.push(content.slice(0, 1200));
71
+ lines.push("```");
72
+ }
73
+ }
74
+ }
75
+ }
76
+ // ── Remix ───────────────────────────────────────────────────
77
+ class RemixScanner {
78
+ name = "Remix";
79
+ async detect(fs) {
80
+ return ((await fs.exists("app/routes")) ||
81
+ (await fs.exists("src/routes")) ||
82
+ (await fs.exists("app/root.tsx")) ||
83
+ (await fs.exists("app/root.ts")));
84
+ }
85
+ async appendPromptContext(fs, lines) {
86
+ for (const dir of ["app/routes", "src/routes"]) {
87
+ if (!(await fs.exists(dir)))
88
+ continue;
89
+ lines.push(`\n## Remix v2 Routes: ${dir}/`);
90
+ lines.push("Note: Remix v2 uses flat file naming — dots (.) map to path separators.");
91
+ lines.push(" _layout.route.tsx patterns define layout segments.");
92
+ lines.push(" $param segments are dynamic. (group) segments are layout groups.");
93
+ const files = await fs.findFiles(`${dir}/**/*.{ts,tsx,js,jsx}`);
94
+ lines.push(`Found ${files.length} route files:`);
95
+ for (const f of files.slice(0, 50))
96
+ lines.push(` - ${f}`);
97
+ for (const f of files.slice(0, 6)) {
98
+ const content = await fs.readFile(f);
99
+ if (!content)
100
+ continue;
101
+ lines.push(`\n### ${f}:`);
102
+ lines.push("```tsx");
103
+ lines.push(content.slice(0, 1200));
104
+ lines.push("```");
105
+ }
106
+ }
107
+ }
108
+ }
109
+ // ── SvelteKit ───────────────────────────────────────────────
110
+ class SvelteKitScanner {
111
+ name = "SvelteKit";
112
+ async detect(fs) {
113
+ return ((await fs.exists("src/routes")) &&
114
+ ((await fs.exists("svelte.config.js")) || (await fs.exists("svelte.config.ts"))));
115
+ }
116
+ async appendPromptContext(fs, lines) {
117
+ if (!(await fs.exists("src/routes")))
118
+ return;
119
+ lines.push("\n## SvelteKit Routes: src/routes/");
120
+ lines.push("Note: +page.svelte = page, (group) = layout group, [[optional]] = optional param, [...rest] = catch-all.");
121
+ const files = await fs.findFiles("src/routes/**/*.svelte");
122
+ const pageFiles = files.filter((f) => f.includes("+page.svelte"));
123
+ lines.push(`Found ${pageFiles.length} +page.svelte files:`);
124
+ for (const f of pageFiles.slice(0, 50))
125
+ lines.push(` - ${f}`);
126
+ for (const f of pageFiles.slice(0, 6)) {
127
+ const content = await fs.readFile(f);
128
+ if (!content)
129
+ continue;
130
+ lines.push(`\n### ${f}:`);
131
+ lines.push("```svelte");
132
+ lines.push(content.slice(0, 1200));
133
+ lines.push("```");
134
+ }
135
+ }
136
+ }
137
+ // ── Vite / React Router ─────────────────────────────────────
138
+ class ViteScanner {
139
+ name = "Vite";
140
+ async detect(fs) {
141
+ return ((await fs.exists("vite.config.ts")) ||
142
+ (await fs.exists("vite.config.js")) ||
143
+ (await fs.exists("src/router")) ||
144
+ (await fs.exists("src/routes/index.tsx")) ||
145
+ (await fs.exists("src/routes/index.ts")));
146
+ }
147
+ async appendPromptContext(fs, lines) {
148
+ lines.push("\n## Vite / React Router Routes");
149
+ // Try router config first
150
+ for (const candidate of [
151
+ "src/router/index.tsx",
152
+ "src/router/index.ts",
153
+ "src/router.tsx",
154
+ "src/router.ts",
155
+ "src/routes/index.tsx",
156
+ "src/routes/index.ts",
157
+ "src/App.tsx",
158
+ "src/App.ts",
159
+ ]) {
160
+ const content = await fs.readFile(candidate);
161
+ if (!content)
162
+ continue;
163
+ lines.push(`\n### ${candidate} (router config):`);
164
+ lines.push("```tsx");
165
+ lines.push(content.slice(0, 2000));
166
+ lines.push("```");
167
+ break;
168
+ }
169
+ }
170
+ }
171
+ /** Ordered list of all scanner strategies. Multiple can match. */
172
+ const SCANNER_STRATEGIES = [
173
+ new NextAppRouterScanner(),
174
+ new NextPagesRouterScanner(),
175
+ new RemixScanner(),
176
+ new SvelteKitScanner(),
177
+ new ViteScanner(),
178
+ ];
179
+ /**
180
+ * Detect frontend subdirectory prefixes in monorepo structures.
181
+ * When `duct init` is run from a project root containing both `frontend/` and `backend/`,
182
+ * scanners need to look inside the frontend subdirectory for routes.
183
+ */
184
+ async function detectFrontendRoots(sandboxFs) {
185
+ const frontendCandidates = ["frontend", "web", "client", "app", "apps/web", "packages/web", "packages/frontend"];
186
+ const roots = [];
187
+ for (const dir of frontendCandidates) {
188
+ if (!(await sandboxFs.exists(dir)))
189
+ continue;
190
+ // Check if this subdirectory looks like a frontend project
191
+ const hasFrontendMarkers = (await sandboxFs.exists(`${dir}/package.json`)) &&
192
+ ((await sandboxFs.exists(`${dir}/app`)) ||
193
+ (await sandboxFs.exists(`${dir}/src/app`)) ||
194
+ (await sandboxFs.exists(`${dir}/pages`)) ||
195
+ (await sandboxFs.exists(`${dir}/src/pages`)) ||
196
+ (await sandboxFs.exists(`${dir}/src/routes`)) ||
197
+ (await sandboxFs.exists(`${dir}/src/lib/routes`)));
198
+ if (hasFrontendMarkers)
199
+ roots.push(`${dir}/`);
200
+ }
201
+ // Always include root
202
+ roots.push("");
203
+ return [...new Set(roots)];
204
+ }
205
+ // ----------------------------------------------------------------
206
+ // Output schema description for the LLM
207
+ // ----------------------------------------------------------------
208
+ const ROUTE_MANIFEST_SCHEMA = `
209
+ Array of RouteManifest objects:
210
+ [
211
+ {
212
+ "path": "/dashboard", // Route path with Next.js brackets e.g. /orders/[id]
213
+ "name": "Dashboard", // Human-readable name
214
+ "description": "...", // What this page shows/does
215
+ "params": [ // Dynamic path params
216
+ {
217
+ "name": "id",
218
+ "type": "uuid", // "string" | "number" | "uuid" | "slug"
219
+ "required": true,
220
+ "description": "Order ID"
221
+ }
222
+ ],
223
+ "queryParams": [ // URL query params
224
+ {
225
+ "name": "page",
226
+ "type": "number",
227
+ "required": false,
228
+ "description": "Page number",
229
+ "defaultValue": 1
230
+ }
231
+ ],
232
+ "uiStateHint": "dashboard", // "form"|"list"|"detail"|"dashboard"|"modal"|"wizard"|"empty"|"error"|"auth"|"checkout"|"profile"|"settings"|"search"
233
+ "requiresAuth": true,
234
+ "deeplinkable": true // Whether Duct can deeplink here with state
235
+ }
236
+ ]
237
+ `.trim();
238
+ // ----------------------------------------------------------------
239
+ // Prompt builder — uses RouteScannerStrategy
240
+ // ----------------------------------------------------------------
241
+ async function buildRoutePrompt(sandboxFs) {
242
+ const lines = [];
243
+ lines.push("Analyze this web project and identify all user-facing navigable routes.\n" +
244
+ "Use the file structure and code snippets below to produce a RouteManifest array.\n");
245
+ // Detect monorepo frontend roots — allows scanning frontend/ or web/ subdirectories
246
+ const frontendRoots = await detectFrontendRoots(sandboxFs);
247
+ if (frontendRoots.some((r) => r !== "")) {
248
+ lines.push(`Detected monorepo structure — frontend roots: ${frontendRoots.filter((r) => r !== "").join(", ")}\n`);
249
+ }
250
+ // Build sub-sandboxes scoped to each frontend root and run all strategies.
251
+ // sandboxFs.scoped() returns a real SandboxFS rooted at the subdirectory.
252
+ // Strip the trailing slash before passing to scoped() so path.join works correctly.
253
+ let anyDetected = false;
254
+ for (const root of frontendRoots) {
255
+ const scopedFs = root === "" ? sandboxFs : sandboxFs.scoped(root.slice(0, -1));
256
+ for (const strategy of SCANNER_STRATEGIES) {
257
+ if (await strategy.detect(scopedFs)) {
258
+ anyDetected = true;
259
+ if (root !== "") {
260
+ lines.push(`\n# Scanning frontend root: ${root}`);
261
+ }
262
+ await strategy.appendPromptContext(scopedFs, lines);
263
+ }
264
+ }
265
+ }
266
+ if (!anyDetected) {
267
+ lines.push("## Warning: No recognised framework detected.");
268
+ lines.push("Scanning for common route patterns in src/ and app/ directories.");
269
+ const fallbackFiles = await sandboxFs.findFiles("**/*.{tsx,ts,jsx,js}");
270
+ const pagelike = fallbackFiles
271
+ .filter((f) => /page|route|view|screen/i.test(f))
272
+ .slice(0, 20);
273
+ for (const f of pagelike)
274
+ lines.push(` - ${f}`);
275
+ }
276
+ // Read middleware / auth guards for auth inference
277
+ const middlewareCandidates = [
278
+ "middleware.ts", "middleware.js",
279
+ "src/middleware.ts", "src/middleware.js",
280
+ "src/hooks.server.ts", // SvelteKit
281
+ ];
282
+ for (const candidate of middlewareCandidates) {
283
+ const content = await sandboxFs.readFile(candidate);
284
+ if (content) {
285
+ lines.push(`\n## ${candidate} (auth/redirect guard):`);
286
+ lines.push("```ts");
287
+ lines.push(content.slice(0, 2000));
288
+ lines.push("```");
289
+ break;
290
+ }
291
+ }
292
+ lines.push(`
293
+ ## Instructions
294
+
295
+ For each user-facing route produce a RouteManifest entry:
296
+ - **path**: Derive from file structure. Next.js: [param] stays as-is. Remix: convert dots to slashes. SvelteKit: +page.svelte filename is the segment.
297
+ - **requiresAuth**: true if: (1) the page/layout calls auth(), getServerSession(), currentUser(), or equivalent; (2) middleware.ts matches the route path; (3) when uncertain, default true (fail-safe).
298
+ - **uiStateHint**: Classify from component imports and page content. Priority: checkout > wizard > modal > form > list > detail > dashboard. Map: <Table>/<DataGrid> → list, <Form>/<Input> → form, <Modal>/<Dialog> → modal, <Wizard>/<Steps> → wizard.
299
+ - **deeplinkable**: true when the route has at least one required path param AND requiresAuth is true (a signed deeplink JWT makes sense for authenticated detail pages).
300
+ - **queryParams**: Extract from useSearchParams().get('...') / $page.url.searchParams.get('...') calls — infer type from usage context.
301
+ - **params**: Typed from file path segment names ([id] → uuid/string, [slug] → slug).
302
+
303
+ DO NOT include API routes (/api/...), auth callback routes, or static asset paths.
304
+ DO NOT include _app, _document, layout-only files that don't produce a page.`);
305
+ return lines.join("\n");
306
+ }
307
+ // ----------------------------------------------------------------
308
+ // runRouteAgent
309
+ // ----------------------------------------------------------------
310
+ /**
311
+ * Run the Route Agent to produce a RouteManifest[] from the project structure.
312
+ */
313
+ export async function runRouteAgent(sandboxFs) {
314
+ const prompt = await buildRoutePrompt(sandboxFs);
315
+ const result = await callDuctLLM({
316
+ agentName: "RouteAgent",
317
+ systemPrompt: "You are an expert at analyzing Next.js, Remix, and React web application codebases. " +
318
+ "You produce structured route manifests that describe every navigable page in an application.",
319
+ userPrompt: prompt,
320
+ outputSchema: ROUTE_MANIFEST_SCHEMA,
321
+ maxTokens: 4096,
322
+ });
323
+ if (!Array.isArray(result.parsed)) {
324
+ throw new Error(`RouteAgent returned unexpected shape: expected array, got ${typeof result.parsed}`);
325
+ }
326
+ // Validate and sanitize the response
327
+ const routes = result.parsed
328
+ .filter((r) => {
329
+ return (typeof r === "object" &&
330
+ r !== null &&
331
+ typeof r.path === "string" &&
332
+ r.path.startsWith("/"));
333
+ })
334
+ .map((r) => ({
335
+ path: r.path,
336
+ name: r.name || r.path,
337
+ description: r.description || "",
338
+ params: Array.isArray(r.params) ? r.params : [],
339
+ queryParams: Array.isArray(r.queryParams) ? r.queryParams : [],
340
+ uiStateHint: r.uiStateHint || "dashboard",
341
+ requiresAuth: r.requiresAuth ?? true,
342
+ deeplinkable: r.deeplinkable ?? false,
343
+ methods: r.methods,
344
+ }));
345
+ return routes;
346
+ }
@@ -0,0 +1,18 @@
1
+ import type { SandboxFS } from "../fs/sandbox.js";
2
+ import type { AuthStrategy } from "../../core/types.js";
3
+ export interface AuthDetectionResult {
4
+ system: AuthStrategy;
5
+ confidence: number;
6
+ sessionFields: string[];
7
+ guestAllowed: boolean;
8
+ middlewarePath?: string;
9
+ configFiles: string[];
10
+ notes: string[];
11
+ }
12
+ /**
13
+ * Detect the authentication system used in a project.
14
+ *
15
+ * Looks at package.json dependencies, middleware files, auth config files,
16
+ * and API route handlers to determine the auth system with confidence scoring.
17
+ */
18
+ export declare function detectAuth(sandboxFs: SandboxFS): Promise<AuthDetectionResult>;
@@ -0,0 +1,273 @@
1
+ // ============================================================
2
+ // @duct/sdk — Auth System Detector
3
+ // ============================================================
4
+ function mergeScore(scores, system, delta, fields = [], configFile, note) {
5
+ let entry = scores.find((s) => s.system === system);
6
+ if (!entry) {
7
+ entry = {
8
+ system,
9
+ score: 0,
10
+ sessionFields: [],
11
+ configFiles: [],
12
+ notes: [],
13
+ };
14
+ scores.push(entry);
15
+ }
16
+ entry.score += delta;
17
+ for (const f of fields) {
18
+ if (!entry.sessionFields.includes(f))
19
+ entry.sessionFields.push(f);
20
+ }
21
+ if (configFile && !entry.configFiles.includes(configFile)) {
22
+ entry.configFiles.push(configFile);
23
+ }
24
+ if (note && !entry.notes.includes(note))
25
+ entry.notes.push(note);
26
+ }
27
+ // ----------------------------------------------------------------
28
+ // Session field extraction helpers
29
+ // ----------------------------------------------------------------
30
+ function extractSessionFields(content) {
31
+ const fields = [];
32
+ const patterns = [
33
+ // session.user.X or session.X
34
+ /session\.user\.(\w+)/g,
35
+ /session\.(\w+)/g,
36
+ // token.X
37
+ /token\.(\w+)/g,
38
+ // user\.X
39
+ /(?:const|let|var)\s+\{\s*([^}]+)\}\s*=\s*(?:session|user)/g,
40
+ // type/interface fields
41
+ /(\w+)\s*[?]?\s*:\s*(?:string|number|boolean)/g,
42
+ ];
43
+ const commonFields = new Set();
44
+ for (const pattern of patterns) {
45
+ let match;
46
+ while ((match = pattern.exec(content)) !== null) {
47
+ const field = match[1].trim();
48
+ if (field &&
49
+ !["then", "catch", "finally", "length", "toString"].includes(field)) {
50
+ commonFields.add(field);
51
+ }
52
+ }
53
+ }
54
+ // Filter to plausible session field names
55
+ const plausibleFields = [
56
+ "id",
57
+ "userId",
58
+ "user_id",
59
+ "email",
60
+ "name",
61
+ "role",
62
+ "orgId",
63
+ "org_id",
64
+ "organizationId",
65
+ "tenantId",
66
+ "sub",
67
+ "picture",
68
+ "avatar",
69
+ "firstName",
70
+ "lastName",
71
+ "username",
72
+ "phone",
73
+ "plan",
74
+ "tier",
75
+ "permissions",
76
+ "scopes",
77
+ "groups",
78
+ "metadata",
79
+ "locale",
80
+ "timezone",
81
+ "createdAt",
82
+ "updatedAt",
83
+ "image",
84
+ "provider",
85
+ "accessToken",
86
+ "refreshToken",
87
+ ];
88
+ for (const field of commonFields) {
89
+ if (plausibleFields.includes(field) ||
90
+ field.startsWith("user") ||
91
+ field.endsWith("Id") ||
92
+ field.endsWith("ID")) {
93
+ fields.push(field);
94
+ }
95
+ }
96
+ return [...new Set(fields)];
97
+ }
98
+ // ----------------------------------------------------------------
99
+ // detectAuth
100
+ // ----------------------------------------------------------------
101
+ /**
102
+ * Detect the authentication system used in a project.
103
+ *
104
+ * Looks at package.json dependencies, middleware files, auth config files,
105
+ * and API route handlers to determine the auth system with confidence scoring.
106
+ */
107
+ export async function detectAuth(sandboxFs) {
108
+ const scores = [];
109
+ // ---- 1. Check package.json ----
110
+ const pkg = await sandboxFs.readJSON("package.json");
111
+ if (pkg) {
112
+ const allDeps = {
113
+ ...(pkg.dependencies ?? {}),
114
+ ...(pkg.devDependencies ?? {}),
115
+ };
116
+ if (allDeps["next-auth"] || allDeps["@auth/core"]) {
117
+ mergeScore(scores, "nextauth", 0.6, [], "package.json", "next-auth dependency found");
118
+ }
119
+ if (allDeps["@clerk/nextjs"] || allDeps["@clerk/clerk-sdk-node"] || allDeps["@clerk/backend"]) {
120
+ mergeScore(scores, "clerk", 0.6, [], "package.json", "Clerk dependency found");
121
+ }
122
+ if (allDeps["@auth0/nextjs-auth0"] || allDeps["auth0"] || allDeps["@auth0/auth0-react"]) {
123
+ mergeScore(scores, "auth0", 0.6, [], "package.json", "Auth0 dependency found");
124
+ }
125
+ if (allDeps["jsonwebtoken"] || allDeps["jose"] || allDeps["jwt-decode"]) {
126
+ mergeScore(scores, "custom-jwt", 0.2, [], "package.json", "JWT library found");
127
+ }
128
+ if (allDeps["iron-session"] || allDeps["cookie-session"] || allDeps["express-session"]) {
129
+ mergeScore(scores, "session-cookie", 0.3, [], "package.json", "Session library found");
130
+ }
131
+ }
132
+ // ---- 2. Check for middleware.ts / middleware.js ----
133
+ const middlewareCandidates = [
134
+ "middleware.ts",
135
+ "middleware.js",
136
+ "src/middleware.ts",
137
+ "src/middleware.js",
138
+ ];
139
+ let middlewarePath;
140
+ let middlewareContent = null;
141
+ for (const candidate of middlewareCandidates) {
142
+ const content = await sandboxFs.readFile(candidate);
143
+ if (content) {
144
+ middlewarePath = candidate;
145
+ middlewareContent = content;
146
+ break;
147
+ }
148
+ }
149
+ if (middlewareContent) {
150
+ if (middlewareContent.includes("next-auth") || middlewareContent.includes("getToken") || middlewareContent.includes("withAuth")) {
151
+ mergeScore(scores, "nextauth", 0.25, [], middlewarePath, "NextAuth found in middleware");
152
+ }
153
+ if (middlewareContent.includes("@clerk") || middlewareContent.includes("clerkMiddleware") || middlewareContent.includes("authMiddleware")) {
154
+ mergeScore(scores, "clerk", 0.25, [], middlewarePath, "Clerk middleware detected");
155
+ }
156
+ if (middlewareContent.includes("auth0") || middlewareContent.includes("Auth0")) {
157
+ mergeScore(scores, "auth0", 0.25, [], middlewarePath, "Auth0 found in middleware");
158
+ }
159
+ if (middlewareContent.includes("jwt.verify") || middlewareContent.includes("jwtVerify") || middlewareContent.includes("verifyToken")) {
160
+ mergeScore(scores, "custom-jwt", 0.25, [], middlewarePath, "Custom JWT verification in middleware");
161
+ }
162
+ if (middlewareContent.includes("session") && !middlewareContent.includes("next-auth")) {
163
+ mergeScore(scores, "session-cookie", 0.15, [], middlewarePath, "Session usage in middleware");
164
+ }
165
+ // Extract session fields from middleware
166
+ const fields = extractSessionFields(middlewareContent);
167
+ const topScore = scores.sort((a, b) => b.score - a.score)[0];
168
+ if (topScore && fields.length > 0) {
169
+ mergeScore(scores, topScore.system, 0, fields);
170
+ }
171
+ }
172
+ // ---- 3. Check for NextAuth config files ----
173
+ const nextauthCandidates = [
174
+ "pages/api/auth/[...nextauth].ts",
175
+ "pages/api/auth/[...nextauth].js",
176
+ "app/api/auth/[...nextauth]/route.ts",
177
+ "src/app/api/auth/[...nextauth]/route.ts",
178
+ "auth.ts",
179
+ "auth.js",
180
+ "auth.config.ts",
181
+ "auth.config.js",
182
+ ];
183
+ for (const candidate of nextauthCandidates) {
184
+ const content = await sandboxFs.readFile(candidate);
185
+ if (content) {
186
+ mergeScore(scores, "nextauth", 0.3, [], candidate, `NextAuth config at ${candidate}`);
187
+ const fields = extractSessionFields(content);
188
+ mergeScore(scores, "nextauth", 0, fields);
189
+ }
190
+ }
191
+ // ---- 4. Check for Clerk config ----
192
+ const clerkCandidates = [
193
+ "clerk.config.ts",
194
+ "clerk.config.js",
195
+ "src/lib/clerk.ts",
196
+ "lib/clerk.ts",
197
+ ];
198
+ for (const candidate of clerkCandidates) {
199
+ const content = await sandboxFs.readFile(candidate);
200
+ if (content) {
201
+ mergeScore(scores, "clerk", 0.2, [], candidate, `Clerk config at ${candidate}`);
202
+ }
203
+ }
204
+ // ---- 5. Check environment variable names (from .env.example or similar) ----
205
+ const envExampleCandidates = [
206
+ ".env.example",
207
+ ".env.local.example",
208
+ ".env.sample",
209
+ ".env.template",
210
+ ];
211
+ for (const candidate of envExampleCandidates) {
212
+ const content = await sandboxFs.readFile(candidate);
213
+ if (content) {
214
+ if (content.includes("NEXTAUTH") || content.includes("AUTH_SECRET")) {
215
+ mergeScore(scores, "nextauth", 0.15, [], candidate, "NextAuth env vars in example file");
216
+ }
217
+ if (content.includes("CLERK_SECRET") || content.includes("NEXT_PUBLIC_CLERK")) {
218
+ mergeScore(scores, "clerk", 0.15, [], candidate, "Clerk env vars in example file");
219
+ }
220
+ if (content.includes("AUTH0_") || content.includes("NEXT_PUBLIC_AUTH0")) {
221
+ mergeScore(scores, "auth0", 0.15, [], candidate, "Auth0 env vars in example file");
222
+ }
223
+ }
224
+ }
225
+ // ---- 6. Determine guest allowance ----
226
+ let guestAllowed = true;
227
+ if (middlewareContent) {
228
+ // If middleware redirects to login for all routes, guests are not allowed
229
+ if (middlewareContent.includes("matcher") &&
230
+ (middlewareContent.includes("redirect") ||
231
+ middlewareContent.includes("NextResponse.redirect"))) {
232
+ // Heuristic: if middleware protects most routes, guests aren't allowed
233
+ if (middlewareContent.includes('"/login"') ||
234
+ middlewareContent.includes("'/login'") ||
235
+ middlewareContent.includes("/auth/signin") ||
236
+ middlewareContent.includes("signIn")) {
237
+ guestAllowed = false;
238
+ }
239
+ }
240
+ }
241
+ // ---- 7. Determine winner ----
242
+ scores.sort((a, b) => b.score - a.score);
243
+ if (scores.length === 0 || scores[0].score === 0) {
244
+ return {
245
+ system: "unknown",
246
+ confidence: 0,
247
+ sessionFields: ["id", "email"],
248
+ guestAllowed: true,
249
+ middlewarePath,
250
+ configFiles: [],
251
+ notes: ["No auth system detected. You may need to configure this manually."],
252
+ };
253
+ }
254
+ const winner = scores[0];
255
+ const confidence = Math.min(winner.score, 1.0);
256
+ // Ensure basic session fields are always present
257
+ const finalFields = winner.sessionFields.length > 0
258
+ ? winner.sessionFields
259
+ : ["id", "email", "name"];
260
+ // Deduplicate config files across all scores
261
+ const allConfigFiles = [
262
+ ...new Set(scores.flatMap((s) => s.configFiles)),
263
+ ];
264
+ return {
265
+ system: winner.system,
266
+ confidence,
267
+ sessionFields: [...new Set(finalFields)],
268
+ guestAllowed,
269
+ middlewarePath,
270
+ configFiles: allConfigFiles,
271
+ notes: winner.notes,
272
+ };
273
+ }
@@ -0,0 +1,22 @@
1
+ export type FrameworkName = "next-app" | "next-pages" | "remix" | "vite-react" | "sveltekit" | "vue3" | "nuxt" | "unknown";
2
+ export interface FrameworkInfo {
3
+ name: FrameworkName;
4
+ version: string;
5
+ /** Next.js specific: whether App Router is used */
6
+ hasAppRouter: boolean;
7
+ /** Next.js specific: whether Pages Router is used */
8
+ hasPagesRouter: boolean;
9
+ /** Detected package manager */
10
+ packageManager: "npm" | "yarn" | "pnpm" | "bun" | "unknown";
11
+ /** Source directory (src/ or root) */
12
+ srcDir: string;
13
+ /** Config file path if found */
14
+ configFile?: string;
15
+ }
16
+ /**
17
+ * Detect the frontend framework used in a project.
18
+ *
19
+ * @param projectRoot - Absolute path to the project root directory
20
+ * @returns FrameworkInfo object describing the detected framework
21
+ */
22
+ export declare function detectFramework(projectRoot: string): Promise<FrameworkInfo>;