@fluixi/cli 0.1.0-alpha.82 → 0.1.0-alpha.84

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 (57) hide show
  1. package/README.md +21 -3
  2. package/dist/add.cjs +590 -0
  3. package/dist/add.d.ts +10 -0
  4. package/dist/add.d.ts.map +1 -0
  5. package/dist/add.js +107 -0
  6. package/dist/add.mjs +562 -0
  7. package/dist/check.cjs +102 -0
  8. package/dist/check.d.ts +13 -0
  9. package/dist/check.d.ts.map +1 -0
  10. package/dist/check.js +88 -0
  11. package/dist/check.mjs +76 -0
  12. package/dist/cli.cjs +977 -78
  13. package/dist/cli.js +44 -2
  14. package/dist/cli.mjs +976 -77
  15. package/dist/doctor.cjs +119 -0
  16. package/dist/doctor.d.ts +13 -0
  17. package/dist/doctor.d.ts.map +1 -0
  18. package/dist/doctor.js +114 -0
  19. package/dist/doctor.mjs +92 -0
  20. package/dist/generate.cjs +614 -65
  21. package/dist/generate.d.ts.map +1 -1
  22. package/dist/generate.js +118 -48
  23. package/dist/generate.mjs +619 -64
  24. package/dist/index.cjs +1 -1
  25. package/dist/index.mjs +1 -1
  26. package/dist/report.cjs +54 -0
  27. package/dist/report.d.ts +5 -0
  28. package/dist/report.d.ts.map +1 -0
  29. package/dist/report.js +31 -0
  30. package/dist/report.mjs +28 -0
  31. package/dist/scaffold/auth.cjs +422 -0
  32. package/dist/scaffold/auth.d.ts +39 -0
  33. package/dist/scaffold/auth.d.ts.map +1 -0
  34. package/dist/scaffold/auth.js +137 -0
  35. package/dist/scaffold/auth.mjs +389 -0
  36. package/dist/scaffold/edit.cjs +153 -0
  37. package/dist/scaffold/edit.d.ts +35 -0
  38. package/dist/scaffold/edit.d.ts.map +1 -0
  39. package/dist/scaffold/edit.js +140 -0
  40. package/dist/scaffold/edit.mjs +124 -0
  41. package/dist/scaffold/index.cjs +610 -0
  42. package/dist/scaffold/index.d.ts +10 -0
  43. package/dist/scaffold/index.d.ts.map +1 -0
  44. package/dist/scaffold/index.js +9 -0
  45. package/dist/scaffold/index.mjs +569 -0
  46. package/dist/scaffold/prompt.cjs +108 -0
  47. package/dist/scaffold/prompt.d.ts +9 -0
  48. package/dist/scaffold/prompt.d.ts.map +1 -0
  49. package/dist/scaffold/prompt.js +95 -0
  50. package/dist/scaffold/prompt.mjs +81 -0
  51. package/dist/scaffold/templates.cjs +274 -0
  52. package/dist/scaffold/templates.d.ts +26 -0
  53. package/dist/scaffold/templates.d.ts.map +1 -0
  54. package/dist/scaffold/templates.js +216 -0
  55. package/dist/scaffold/templates.mjs +229 -0
  56. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  57. package/package.json +19 -3
package/dist/cli.mjs CHANGED
@@ -1,22 +1,595 @@
1
1
  #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, { get: all[name], enumerable: true });
6
+ };
2
7
 
3
8
  // src/cli.ts
4
9
  import { loadConfig } from "@fluixi/start/config";
5
- import { dev, build, start } from "@fluixi/start/commands";
6
- import { wordmark, c as c2 } from "@fluixi/start/ui";
10
+ import { dev, build, start, env as env2, envReport, info } from "@fluixi/start/commands";
11
+ import { wordmark, c as c6 } from "@fluixi/start/ui";
7
12
 
8
13
  // src/generate.ts
9
- import { writeFileSync, readFileSync, existsSync, mkdirSync } from "node:fs";
10
- import { resolve, dirname, relative, basename } from "node:path";
11
- import { c } from "@fluixi/start/ui";
12
- var GEN_USAGE = `Usage: fluixi generate <kind> <name>
14
+ import { writeFileSync as writeFileSync3, readFileSync as readFileSync3, existsSync as existsSync3, mkdirSync as mkdirSync3 } from "node:fs";
15
+ import { resolve, dirname as dirname3, relative as relative3, basename } from "node:path";
16
+ import { c as c3 } from "@fluixi/start/ui";
17
+
18
+ // src/scaffold/auth.ts
19
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
20
+ import { dirname as dirname2, join, relative } from "node:path";
21
+
22
+ // src/scaffold/edit.ts
23
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
24
+ import { dirname } from "node:path";
25
+ function closing(text, open) {
26
+ let depth = 0;
27
+ for (let i = open; i < text.length; i++) {
28
+ const ch = text[i];
29
+ if (ch === "/" && text[i + 1] === "/") i = text.indexOf("\n", i) === -1 ? text.length : text.indexOf("\n", i);
30
+ else if (ch === "/" && text[i + 1] === "*") i = text.indexOf("*/", i + 2) + 1;
31
+ else if (ch === "'" || ch === '"' || ch === "`") {
32
+ for (i++; i < text.length && text[i] !== ch; i++) if (text[i] === "\\") i++;
33
+ } else if ("([{".includes(ch)) depth++;
34
+ else if (")]}".includes(ch) && --depth === 0) return i;
35
+ }
36
+ return -1;
37
+ }
38
+ function appendToArray(text, open, items) {
39
+ const close = closing(text, open);
40
+ const inner = text.slice(open + 1, close);
41
+ if (!inner.trim()) return text.slice(0, open + 1) + items.join(", ") + text.slice(close);
42
+ if (inner.includes("\n")) {
43
+ const last = inner.trimEnd();
44
+ const indent = last.slice(last.lastIndexOf("\n") + 1).match(/^\s*/)[0];
45
+ const comma = last.endsWith(",") ? "" : ",";
46
+ const tail = inner.slice(last.length);
47
+ return text.slice(0, open + 1) + last + comma + items.map((i) => `
48
+ ${indent}${i},`).join("") + tail + text.slice(close);
49
+ }
50
+ const body = inner.replace(/,?\s*$/, "");
51
+ const trailing = inner.slice(body.length).replace(/^,/, "");
52
+ return text.slice(0, open + 1) + body + ", " + items.join(", ") + trailing + text.slice(close);
53
+ }
54
+ function addImport(text, line) {
55
+ if (text.includes(line)) return text;
56
+ const imports = [...text.matchAll(/^import[\s\S]*?from\s+['"][^'"]+['"];?[^\n]*\n/gm)];
57
+ const at = imports.length ? imports[imports.length - 1].index + imports[imports.length - 1][0].length : 0;
58
+ return text.slice(0, at) + line + "\n" + text.slice(at);
59
+ }
60
+ function register(log, file, header, r) {
61
+ const imports = [...r.extraImports ?? [], r.importLine];
62
+ if (!existsSync(file)) {
63
+ mkdirSync(dirname(file), { recursive: true });
64
+ writeFileSync(
65
+ file,
66
+ `${header}import { defineApp } from '@fluixi/start/app';
67
+ ${imports.join("\n")}
68
+
69
+ export default defineApp({ imports: [${r.entry}] });
70
+ `
71
+ );
72
+ log.push({ kind: "created", file });
73
+ return true;
74
+ }
75
+ let text = readFileSync(file, "utf8");
76
+ if (text.includes(r.importLine)) {
77
+ log.push({ kind: "listed", file, detail: r.entry });
78
+ return true;
79
+ }
80
+ const m = text.match(/\bimports\s*:\s*\[/);
81
+ if (!m) {
82
+ log.push({ kind: "hint", file, lines: [...imports, `imports: [${r.entry}]`] });
83
+ return false;
84
+ }
85
+ text = appendToArray(text, m.index + m[0].length - 1, [r.entry]);
86
+ for (const line of imports) text = addImport(text, line);
87
+ writeFileSync(file, text);
88
+ log.push({ kind: "updated", file, detail: `imports ${r.entry}` });
89
+ return true;
90
+ }
91
+ function envPublicNames(configFile) {
92
+ if (!existsSync(configFile)) return null;
93
+ const text = readFileSync(configFile, "utf8");
94
+ const m = text.match(/\bpublic\s*:\s*\[/);
95
+ if (!m) return null;
96
+ const open = m.index + m[0].length - 1;
97
+ const list = text.slice(open, closing(text, open) + 1);
98
+ return [...list.matchAll(/['"]([A-Za-z_][A-Za-z0-9_]*)['"]/g)].map((x) => x[1]);
99
+ }
100
+ function addEnvPublic(log, configFile, names) {
101
+ const list = (indent) => `${indent}public: [
102
+ ${names.map((n) => `${indent} '${n}',
103
+ `).join("")}${indent}],
104
+ `;
105
+ const have = envPublicNames(configFile);
106
+ if (have === null) {
107
+ const text2 = existsSync(configFile) ? readFileSync(configFile, "utf8") : "";
108
+ const call = text2.match(/defineConfig\(\{\n/);
109
+ if (call && !/\benv\s*:/.test(text2)) {
110
+ const at = call.index + call[0].length;
111
+ writeFileSync(configFile, text2.slice(0, at) + ` env: {
112
+ ${list(" ")} },
113
+ ` + text2.slice(at));
114
+ log.push({ kind: "updated", file: configFile, detail: `env.public ${names.join(", ")}` });
115
+ return;
116
+ }
117
+ log.push({ kind: "hint", file: configFile, lines: [`env: { public: [${names.map((n) => `'${n}'`).join(", ")}] },`] });
118
+ return;
119
+ }
120
+ const missing = names.filter((n) => !have.includes(n));
121
+ if (!missing.length) return;
122
+ const text = readFileSync(configFile, "utf8");
123
+ const m = text.match(/\bpublic\s*:\s*\[/);
124
+ writeFileSync(configFile, appendToArray(text, m.index + m[0].length - 1, missing.map((n) => `'${n}'`)));
125
+ log.push({ kind: "updated", file: configFile, detail: `env.public + ${missing.join(", ")}` });
126
+ }
127
+ function addEnvExample(log, file, comment, vars) {
128
+ const text = existsSync(file) ? readFileSync(file, "utf8") : "";
129
+ const have = new Set([...text.matchAll(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/gm)].map((m) => m[1]));
130
+ const add2 = Object.entries(vars).filter(([k]) => !have.has(k) && !have.has(`VITE_${k}`));
131
+ if (!add2.length) return;
132
+ const block = `${comment.split("\n").map((l) => `# ${l}`).join("\n")}
133
+ ${add2.map(([k, v]) => `${k}=${v}`).join("\n")}
134
+ `;
135
+ writeFileSync(file, text ? `${text.replace(/\n*$/, "\n")}
136
+ ${block}` : block);
137
+ log.push({ kind: text ? "updated" : "created", file, detail: add2.map(([k]) => k).join(", ") });
138
+ }
139
+
140
+ // src/scaffold/templates.ts
141
+ var templates_exports = {};
142
+ __export(templates_exports, {
143
+ AUTH_READER: () => AUTH_READER,
144
+ PROVIDERS: () => PROVIDERS,
145
+ PROVIDER_VARS: () => PROVIDER_VARS,
146
+ SERVER_ONLY: () => SERVER_ONLY,
147
+ apiRoute: () => apiRoute,
148
+ authEnvConfig: () => authEnvConfig,
149
+ authServerFile: () => authServerFile,
150
+ authServiceFile: () => authServiceFile,
151
+ betterAuthClient: () => betterAuthClient,
152
+ betterAuthConfig: () => betterAuthConfig,
153
+ betterAuthMiddleware: () => betterAuthMiddleware,
154
+ betterAuthRoute: () => betterAuthRoute,
155
+ callbackRoute: () => callbackRoute,
156
+ camel: () => camel,
157
+ envConfig: () => envConfig,
158
+ guardedApiRoute: () => guardedApiRoute,
159
+ loginRoute: () => loginRoute,
160
+ moduleFile: () => moduleFile,
161
+ serverFn: () => serverFn,
162
+ serviceFile: () => serviceFile,
163
+ verifyServer: () => verifyServer
164
+ });
165
+ var camel = (name) => name.toLowerCase().replace(/_+([a-z0-9])/g, (_, ch) => ch.toUpperCase());
166
+ var envConfig = (names) => {
167
+ const fields = names.length ? names.map((n) => ` ${camel(n)}: '${n}',`).join("\n") : ` // apiUrl: 'API_URL',`;
168
+ return `import { pickEnv } from '@fluixi/start/env';
169
+
170
+ // Every missing variable is reported at once, when this module loads. A field that may be
171
+ // unset takes { key, optional: true } or { key, default }; parse: asNumber and friends convert.
172
+ export const config = pickEnv({
173
+ ${fields}
174
+ });
175
+ `;
176
+ };
177
+ var moduleFile = (Name, name) => `import { defineModule } from '@fluixi/start/app';
178
+
179
+ export const ${Name}Module = defineModule({
180
+ name: '${name}',
181
+ imports: [],
182
+ providers: [],
183
+ });
184
+ `;
185
+ var serviceFile = (Name, name, server) => `${server ? `// Server only: the browser build refuses a page that imports this file.
186
+ ` : ""}import { injectionToken } from '@fluixi/start/di';
187
+ import { defineModule } from '@fluixi/start/app';
188
+
189
+ export class ${Name}Service {}
190
+
191
+ export const ${Name}Token = injectionToken<${Name}Service>('${Name}');
192
+
193
+ export const ${Name}Module = defineModule({
194
+ name: '${name}',
195
+ providers: [{ provide: ${Name}Token, useFactory: () => new ${Name}Service() }],
196
+ });
197
+ `;
198
+ var apiRoute = () => `export function GET(request: Request) {
199
+ return Response.json({ path: new URL(request.url).pathname });
200
+ }
201
+ `;
202
+ var guardedApiRoute = (guardImport, role) => `import { guard } from '${guardImport}';
203
+
204
+ export const GET = guard(
205
+ async (request, claims) => {
206
+ return Response.json({ sub: claims.sub });
207
+ },
208
+ { role: '${role}' },
209
+ );
210
+ `;
211
+ var verifyServer = () => `import { createTokenVerifier, createApiGuard } from '@fluixi/oauth2/verify';
212
+ import { auth } from '../config/env.js';
213
+
214
+ // Checks a bearer token's signature, issuer, audience and expiry against the provider.
215
+ export const verify = createTokenVerifier(auth.provider.verifier(auth.clientId));
216
+
217
+ // Answers 401 without a valid token and 403 without the role.
218
+ export const guard = createApiGuard({ verify, roles: auth.provider.roles });
219
+ `;
220
+ var serverFn = (name) => `export async function ${name}(input: { id: string }) {
221
+ 'use server';
222
+ // Runs on the server only. The browser calls it over RPC, so input and result are plain data.
223
+ return { id: input.id };
224
+ }
225
+ `;
226
+ var PROVIDERS = ["oidc", "keycloak", "auth0", "okta", "google", "dex", "oauth2"];
227
+ var SERVER_ONLY = {
228
+ google: "Google answers a token request without a client secret with `client_secret is missing`",
229
+ dex: "Dex sends no CORS headers on discovery or the token endpoint"
230
+ };
231
+ var PROVIDER_VARS = {
232
+ oidc: { AUTH_ISSUER: "https://id.example.com" },
233
+ keycloak: { AUTH_BASE_URL: "http://localhost:8080", AUTH_REALM: "master" },
234
+ auth0: { AUTH_DOMAIN: "example.eu.auth0.com", AUTH_AUDIENCE: "https://api.example.com" },
235
+ okta: { AUTH_DOMAIN: "example.okta.com" },
236
+ google: {},
237
+ dex: { AUTH_BASE_URL: "http://localhost:5556/dex" },
238
+ oauth2: {
239
+ AUTH_ISSUER: "https://id.example.com",
240
+ AUTH_AUTHORIZATION_ENDPOINT: "https://id.example.com/authorize",
241
+ AUTH_TOKEN_ENDPOINT: "https://id.example.com/token"
242
+ }
243
+ };
244
+ var AUTH_READER = `// Provider, issuer, client and token mode from the AUTH_* variables in env.public. Moving to
245
+ // another provider is a change to .env.
246
+ export const auth = authFromEnv(publicEnv(), { clientPrefix: '' });
247
+ `;
248
+ var authEnvConfig = () => `import { publicEnv } from '@fluixi/start/env';
249
+ import { authFromEnv } from '@fluixi/oauth2/env';
250
+
251
+ ${AUTH_READER}`;
252
+ var authServiceFile = (tokens) => `import { createAuthService, authModule } from '@fluixi/oauth2';
253
+ import { env } from '@fluixi/start/env';
254
+ ${tokens === "browser" ? `import { auth as authEnv } from '../config/env.js';
255
+ ` : ""}
256
+ export interface User {
257
+ sub: string;
258
+ email?: string;
259
+ name?: string;
260
+ }
261
+
262
+ const appUrl = env('APP_URL') ?? 'http://localhost:3000';
263
+
264
+ export const auth = createAuthService<User>({
265
+ ${tokens === "browser" ? ` config: {
266
+ ...authEnv.client,
267
+ tokens: 'browser',
268
+ redirectUri: \`\${appUrl}/callback\`,
269
+ postLogoutRedirectUri: \`\${appUrl}/login\`,
270
+ },` : ` // The tokens stay on the server behind an httpOnly cookie. The browser calls the routes
271
+ // auth.server.ts mounts under basePath and never sees a token.
272
+ config: {
273
+ tokens: 'server',
274
+ redirectUri: \`\${appUrl}/auth/callback\`,
275
+ postLogoutRedirectUri: \`\${appUrl}/login\`,
276
+ basePath: '/auth',
277
+ },`}
278
+ });
279
+
280
+ export const AuthModule = authModule(auth);
281
+ export const { protectedRoute, Protect, Can, useUser } = auth;
282
+ `;
283
+ var authServerFile = () => `import { authServerModule } from '@fluixi/oauth2/server';
284
+ import { publicEnv, serverEnv } from '@fluixi/start/env';
285
+ import { auth } from '../config/env.js';
286
+
287
+ // A function: serverEnv with required throws when a secret is unset, and it is only read
288
+ // when app.config.server.ts registers this.
289
+ export function authServer() {
290
+ const appUrl = publicEnv().APP_URL ?? 'http://localhost:3000';
291
+ return authServerModule({
292
+ ...auth.client,
293
+ clientSecret: serverEnv('OIDC_CLIENT_SECRET', { required: true }),
294
+ cookieSecret: serverEnv('SESSION_SECRET', { required: true }),
295
+ redirectUri: \`\${appUrl}/auth/callback\`,
296
+ defaultReturnTo: '/',
297
+ secureCookie: appUrl.startsWith('https://'),
298
+ });
299
+ }
300
+ `;
301
+ var callbackRoute = (html) => html ? `import { html } from '@fluixi/core';
302
+ import { OAuthCallback } from '@fluixi/oauth2/callback';
303
+
304
+ export default OAuthCallback({
305
+ pending: () => html\`<p>Signing you in</p>\`,
306
+ failed: (reason) => html\`<p>\${reason}</p><a href="/login">Try again</a>\`,
307
+ });
308
+ ` : `import { OAuthCallback } from '@fluixi/oauth2/callback';
309
+
310
+ export default OAuthCallback({
311
+ pending: () => <p>Signing you in</p>,
312
+ failed: (reason) => (
313
+ <>
314
+ <p>{reason}</p>
315
+ <a href="/login">Try again</a>
316
+ </>
317
+ ),
318
+ });
319
+ `;
320
+ var loginRoute = (html) => html ? `import { html } from '@fluixi/core';
321
+ import { auth } from '../services/auth.js';
322
+
323
+ export default function Login() {
324
+ return html\`<button @click=\${() => auth.signIn({ returnTo: '/' })}>Sign in</button>\`;
325
+ }
326
+ ` : `import { auth } from '../services/auth.js';
327
+
328
+ export default function Login() {
329
+ return <button onClick={() => auth.signIn({ returnTo: '/' })}>Sign in</button>;
330
+ }
331
+ `;
332
+ var betterAuthConfig = () => `import { betterAuth } from 'better-auth';
333
+ import { defineAuth } from '@fluixi/auth/server';
334
+
335
+ export type AppUser = { id: string; email: string; name?: string; role?: string };
336
+
337
+ // Better Auth owns the audited primitives; defineAuth registers it with @fluixi/auth.
338
+ export const auth = defineAuth<AppUser>(
339
+ betterAuth({
340
+ // database: <your adapter>,
341
+ emailAndPassword: { enabled: true },
342
+ // socialProviders: { google: { … }, github: { … } },
343
+ } as Parameters<typeof betterAuth>[0]),
344
+ );
345
+ `;
346
+ var betterAuthClient = () => `import { createAuthClient } from 'better-auth/client';
347
+ import { createAuthHooks } from '@fluixi/auth/client';
348
+ import type { AppUser } from './auth.config.js';
349
+
350
+ const client = createAuthClient({ baseURL: '/api/auth' });
351
+
352
+ // Or, to reuse an existing reactive session: createAuthHooks({ session: yourSessionStore }).
353
+ export const { useUser, useSession, useAuth, useSignIn, useSignOut, protectedRoute } =
354
+ createAuthHooks<AppUser>({ client, loginPath: '/login' });
355
+ `;
356
+ var betterAuthMiddleware = () => `import { defineMiddleware } from '@fluixi/start';
357
+ import { authMiddleware } from '@fluixi/auth/server';
358
+ import './auth.config.js';
359
+
360
+ export default defineMiddleware([authMiddleware()]);
361
+ `;
362
+ var betterAuthRoute = () => `import { mountAuthRoutes } from '@fluixi/auth/server';
363
+ import '../../auth.config.js';
364
+
365
+ const handler = mountAuthRoutes();
366
+ export const GET = handler;
367
+ export const POST = handler;
368
+ export default handler;
369
+ `;
370
+
371
+ // src/scaffold/auth.ts
372
+ var ScaffoldError = class extends Error {
373
+ };
374
+ function projectFormat(root) {
375
+ try {
376
+ const ts = JSON.parse(readFileSync2(join(root, "tsconfig.json"), "utf8"));
377
+ if (ts?.compilerOptions && !ts.compilerOptions.jsx) return "html";
378
+ } catch {
379
+ }
380
+ return "jsx";
381
+ }
382
+ function importPath(from, to) {
383
+ const p = relative(dirname2(from), to).replace(/\\/g, "/").replace(/\.tsx?$/, ".js");
384
+ return p.startsWith(".") ? p : `./${p}`;
385
+ }
386
+ function writeOnce(log, file, content) {
387
+ if (existsSync2(file)) {
388
+ log.push({ kind: "kept", file });
389
+ return false;
390
+ }
391
+ mkdirSync2(dirname2(file), { recursive: true });
392
+ writeFileSync2(file, content);
393
+ log.push({ kind: "created", file });
394
+ return true;
395
+ }
396
+ var APP_HEADER = "// Registered by @fluixi/start ahead of both entries.\n";
397
+ var APP_SERVER_HEADER = "// Only the server build imports this file, so what it lists never reaches the browser.\n";
398
+ function registerModule(log, root, server, file, name, entry = name) {
399
+ const config = join(root, server ? "src/app.config.server.ts" : "src/app.config.ts");
400
+ register(log, config, server ? APP_SERVER_HEADER : APP_HEADER, {
401
+ importLine: `import { ${name} } from '${importPath(config, file)}';`,
402
+ entry
403
+ });
404
+ }
405
+ function ensureAuthEnv(log, root) {
406
+ const file = join(root, "src/config/env.ts");
407
+ if (writeOnce(log, file, authEnvConfig())) return;
408
+ let text = readFileSync2(file, "utf8");
409
+ if (/export\s+const\s+auth\b/.test(text)) return;
410
+ if (!/\bpublicEnv\b/.test(text)) text = addImport(text, `import { publicEnv } from '@fluixi/start/env';`);
411
+ text = addImport(text, `import { authFromEnv } from '@fluixi/oauth2/env';`);
412
+ writeFileSync2(file, `${text.replace(/\n*$/, "\n")}
413
+ ${AUTH_READER}`);
414
+ log.push({ kind: "updated", file, detail: "auth" });
415
+ }
416
+ function resolveTokens(provider, tokens) {
417
+ const refusal = SERVER_ONLY[provider];
418
+ if (refusal && tokens === "browser") throw new ScaffoldError(`${provider} needs server tokens: ${refusal}`);
419
+ return { tokens: tokens ?? (refusal ? "server" : "browser"), forced: !!refusal && !tokens };
420
+ }
421
+ function setupOAuth2(root, options, dependencySpec = "alpha") {
422
+ const provider = options.provider ?? "oidc";
423
+ if (!PROVIDERS.includes(provider)) throw new ScaffoldError(`unknown provider ${provider}: ${PROVIDERS.join(", ")}`);
424
+ const { tokens, forced } = resolveTokens(provider, options.tokens);
425
+ const html = options.format === "html";
426
+ const ext = html ? "ts" : "tsx";
427
+ const steps = [];
428
+ const at = (rel2) => join(root, rel2);
429
+ ensureAuthEnv(steps, root);
430
+ const service = at("src/services/auth.ts");
431
+ if (writeOnce(steps, service, authServiceFile(tokens))) registerModule(steps, root, false, service, "AuthModule");
432
+ if (tokens === "browser") writeOnce(steps, at(`src/routes/callback.${ext}`), callbackRoute(html));
433
+ writeOnce(steps, at(`src/routes/login.${ext}`), loginRoute(html));
434
+ if (tokens === "server") {
435
+ const server = at("src/services/auth.server.ts");
436
+ if (writeOnce(steps, server, authServerFile())) registerModule(steps, root, true, server, "authServer", "authServer()");
437
+ }
438
+ const vars = {
439
+ AUTH_PROVIDER: provider,
440
+ AUTH_CLIENT_ID: "my-app",
441
+ AUTH_TOKENS: tokens,
442
+ ...PROVIDER_VARS[provider],
443
+ APP_URL: "http://localhost:3000"
444
+ };
445
+ addEnvPublic(steps, at("fluixi.config.ts"), Object.keys(vars));
446
+ addEnvExample(steps, at(".env.example"), `@fluixi/oauth2 (${provider}). Listed in env.public: the browser sees them.`, vars);
447
+ if (tokens === "server") {
448
+ addEnvExample(steps, at(".env.example"), "Server only, never in env.public. SESSION_SECRET: 32 bytes or more.", {
449
+ OIDC_CLIENT_SECRET: "",
450
+ SESSION_SECRET: ""
451
+ });
452
+ }
453
+ const redirect = tokens === "browser" ? "/callback" : "/auth/callback";
454
+ return {
455
+ steps,
456
+ dependencies: { "@fluixi/oauth2": dependencySpec },
457
+ next: ["copy .env.example to .env and fill it in", `register <APP_URL>${redirect} as the redirect URI at the provider`],
458
+ notes: forced ? [`${provider} refuses a public client, so the tokens stay on the server`] : []
459
+ };
460
+ }
461
+ function setupBetterAuth(root, dependencySpec = "alpha") {
462
+ const steps = [];
463
+ const at = (rel2) => join(root, rel2);
464
+ writeOnce(steps, at("src/auth.config.ts"), betterAuthConfig());
465
+ writeOnce(steps, at("src/auth.client.ts"), betterAuthClient());
466
+ if (!writeOnce(steps, at("src/middleware.ts"), betterAuthMiddleware())) {
467
+ steps.push({
468
+ kind: "hint",
469
+ file: at("src/middleware.ts"),
470
+ lines: [`import { authMiddleware } from '@fluixi/auth/server';`, `import './auth.config.js';`, "authMiddleware() in the middleware list"]
471
+ });
472
+ }
473
+ writeOnce(steps, at("src/api/auth/[...all].ts"), betterAuthRoute());
474
+ return {
475
+ steps,
476
+ dependencies: { "@fluixi/auth": dependencySpec, "better-auth": "^1" },
477
+ next: ["set your database adapter in src/auth.config.ts"],
478
+ notes: []
479
+ };
480
+ }
481
+
482
+ // src/scaffold/prompt.ts
483
+ import { createInterface } from "node:readline/promises";
484
+ import { emitKeypressEvents } from "node:readline";
485
+ import { stdin as input, stdout as output, exit, env } from "node:process";
486
+ var COLOR = env.NO_COLOR || env.FORCE_COLOR === "0" ? false : (!!output.isTTY || !!env.FORCE_COLOR) && env.TERM !== "dumb";
487
+ var sgr = (o, x) => (s) => COLOR ? `\x1B[${o}m${s}\x1B[${x}m` : `${s}`;
488
+ var c = { bold: sgr(1, 22), green: sgr(32, 39), cyan: sgr(36, 39), gray: sgr(90, 39) };
489
+ var BAR = c.gray("│");
490
+ function askSelect(label, choices) {
491
+ return new Promise((done) => {
492
+ let idx = 0;
493
+ output.write(`${c.green("◆")} ${c.bold(label)}
494
+ `);
495
+ const draw = (first) => {
496
+ if (!first) output.write(`\x1B[${choices.length}A`);
497
+ for (let i = 0; i < choices.length; i++) {
498
+ const on = i === idx;
499
+ const dot = on ? c.green("●") : c.gray("○");
500
+ const name = on ? c.cyan(c.bold(choices[i].label)) : choices[i].label;
501
+ output.write(`\x1B[2K${BAR} ${dot} ${name} ${c.gray(choices[i].hint)}
502
+ `);
503
+ }
504
+ };
505
+ draw(true);
506
+ emitKeypressEvents(input);
507
+ if (input.isTTY) input.setRawMode(true);
508
+ const onKey = (_s, k) => {
509
+ if (k.name === "up" || k.name === "k") {
510
+ idx = (idx - 1 + choices.length) % choices.length;
511
+ draw(false);
512
+ } else if (k.name === "down" || k.name === "j") {
513
+ idx = (idx + 1) % choices.length;
514
+ draw(false);
515
+ } else if (k.name === "return" || k.name === "enter") {
516
+ finish();
517
+ done(choices[idx].value);
518
+ } else if (k.name === "c" && k.ctrl) {
519
+ finish();
520
+ output.write("\n");
521
+ exit(1);
522
+ }
523
+ };
524
+ const onEnd = () => {
525
+ finish();
526
+ done(choices[idx].value);
527
+ };
528
+ const finish = () => {
529
+ input.off("keypress", onKey);
530
+ input.off("end", onEnd);
531
+ input.off("close", onEnd);
532
+ if (input.isTTY) input.setRawMode(false);
533
+ input.pause();
534
+ output.write(`${BAR}
535
+ `);
536
+ };
537
+ if (input.readableEnded) {
538
+ finish();
539
+ done(choices[idx].value);
540
+ return;
541
+ }
542
+ input.on("keypress", onKey);
543
+ input.on("end", onEnd);
544
+ input.on("close", onEnd);
545
+ input.resume();
546
+ });
547
+ }
548
+
549
+ // src/report.ts
550
+ import { relative as relative2 } from "node:path";
551
+ import { c as c2 } from "@fluixi/start/ui";
552
+ var rel = (file) => relative2(process.cwd(), file) || ".";
553
+ function report(steps) {
554
+ for (const s of steps) {
555
+ if (s.kind === "hint") {
556
+ console.log(` ${c2.yellow("!")} ${c2.gray("add to")} ${c2.cyan(rel(s.file))}${c2.gray(":")}`);
557
+ for (const l of s.lines) console.log(` ${l}`);
558
+ } else if (s.kind === "kept") {
559
+ console.log(` ${c2.gray("-")} ${c2.cyan(rel(s.file))} ${c2.gray("exists, kept")}`);
560
+ } else if (s.kind === "listed") {
561
+ console.log(` ${c2.gray("-")} ${c2.cyan(rel(s.file))} ${c2.gray("already lists it")}`);
562
+ } else {
563
+ console.log(` ${c2.green("✓")} ${c2.gray(s.kind)} ${c2.cyan(rel(s.file))}${s.detail ? c2.gray(`: ${s.detail}`) : ""}`);
564
+ }
565
+ }
566
+ }
567
+ function reportAuth(result, installHint) {
568
+ for (const n of result.notes) console.log(` ${c2.gray(n)}`);
569
+ report(result.steps);
570
+ const next = [...installHint ? [installHint] : [], ...result.next];
571
+ if (next.length) console.log(` ${c2.gray("next:")} ${next.map((n) => c2.gray(n)).join(c2.gray("; "))}`);
572
+ }
573
+
574
+ // src/generate.ts
575
+ var GEN_USAGE = `Usage: fluixi generate <kind> [name] [options]
13
576
 
14
577
  Kinds:
15
- component <Name> a reusable component → src/components/<Name>.{tsx,ts}
16
- route <path> a file-based route page → src/routes/<path>.{tsx,ts}
17
- middleware the request middleware file → src/middleware.ts
18
- auth @fluixi/auth wiring → auth.config + auth.client + middleware + /api/auth route
578
+ component <Name> a reusable component → src/components/<Name>.{tsx,ts}
579
+ route <path> a file-based route page → src/routes/<path>.{tsx,ts}
580
+ middleware the request middleware file → src/middleware.ts
581
+ env typed config from env.public → src/config/env.ts
582
+ module <name> an app module → src/services/<name>/<name>.module.ts
583
+ service <Name> [--server] a service, token and module → src/services/<name>.ts (.server.ts)
584
+ api <path> [--role <role>] an API route, guarded by role → src/api/<path>.ts
585
+ server-fn <name> a "use server" function → src/server/<name>.ts
586
+ auth oauth2 [--provider <p>] [--tokens browser|server]
587
+ @fluixi/oauth2 wiring: env config, service, routes, .env.example
588
+ (fluixi add auth does the same, asks, and installs)
589
+ auth better-auth @fluixi/auth wiring → auth.config + auth.client + middleware + /api/auth
19
590
 
591
+ Modules and services are listed in src/app.config.ts, or app.config.server.ts for --server,
592
+ which is created when missing. Providers: ${templates_exports.PROVIDERS.join(", ")}.
20
593
  Component/route syntax follows the project (JSX → .tsx, html\`\` → .ts); override with --jsx / --html.
21
594
  `;
22
595
  function detectFormat() {
@@ -24,7 +597,7 @@ function detectFormat() {
24
597
  if (args.includes("--html")) return "html";
25
598
  if (args.includes("--jsx")) return "jsx";
26
599
  try {
27
- const ts = JSON.parse(readFileSync(resolve("tsconfig.json"), "utf8"));
600
+ const ts = JSON.parse(readFileSync3(resolve("tsconfig.json"), "utf8"));
28
601
  if (ts?.compilerOptions && !ts.compilerOptions.jsx) return "html";
29
602
  } catch {
30
603
  }
@@ -35,28 +608,46 @@ function pascal(s) {
35
608
  }
36
609
  function resolveHint(Name, ext) {
37
610
  const configs = ["vite.config.ts", "vite.config.js", "fluixi.config.ts", "fluixi.config.js"];
38
- const found = configs.map((f) => resolve(f)).find((f) => existsSync(f));
611
+ const found = configs.map((f) => resolve(f)).find((f) => existsSync3(f));
39
612
  if (!found) return;
40
613
  try {
41
- if (/\bresolve\s*:\s*\[/.test(readFileSync(found, "utf8"))) return;
614
+ if (/\bresolve\s*:\s*\[/.test(readFileSync3(found, "utf8"))) return;
42
615
  } catch {
43
616
  return;
44
617
  }
45
618
  console.log(
46
- ` ${c.gray("to use")} ${c.cyan(`<${Name} />`)} ${c.gray("without importing it, add to")} ${c.cyan(relative(process.cwd(), found))}:`
619
+ ` ${c3.gray("to use")} ${c3.cyan(`<${Name} />`)} ${c3.gray("without importing it, add to")} ${c3.cyan(relative3(process.cwd(), found))}:`
47
620
  );
48
- console.log(` ${c.gray(`resolve: [{ match: /^([A-Z]\\w+)$/, module: '/src/components/$1.${ext}' }]`)}`);
49
- console.log(` ${c.gray("one pattern covers the whole folder. Importing it works too — including with")} ${c.cyan("load:")}`);
621
+ console.log(` ${c3.gray(`resolve: [{ match: /^([A-Z]\\w+)$/, module: '/src/components/$1.${ext}' }]`)}`);
622
+ console.log(` ${c3.gray("one pattern covers the whole folder. Importing it works too — including with")} ${c3.cyan("load:")}`);
623
+ }
624
+ function option(name) {
625
+ const args = process.argv;
626
+ const i = args.indexOf(`--${name}`);
627
+ if (i !== -1 && args[i + 1] && !args[i + 1].startsWith("--")) return args[i + 1];
628
+ return args.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3);
629
+ }
630
+ var kebab = (s) => s.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
631
+ function writeOnce2(file, content) {
632
+ const steps = [];
633
+ const wrote = writeOnce(steps, file, content);
634
+ report(steps);
635
+ return wrote;
636
+ }
637
+ function registerIn(server, file, name, entry = name) {
638
+ const steps = [];
639
+ registerModule(steps, process.cwd(), server, file, name, entry);
640
+ report(steps);
50
641
  }
51
642
  function write(file, content) {
52
- const rel = relative(process.cwd(), file);
53
- if (existsSync(file)) {
54
- console.error(` ${c.red("✗")} ${rel} ${c.gray("already exists")}`);
643
+ const rel2 = relative3(process.cwd(), file);
644
+ if (existsSync3(file)) {
645
+ console.error(` ${c3.red("✗")} ${rel2} ${c3.gray("already exists")}`);
55
646
  process.exit(1);
56
647
  }
57
- mkdirSync(dirname(file), { recursive: true });
58
- writeFileSync(file, content);
59
- console.log(` ${c.green("✓")} ${c.gray("created")} ${c.cyan(rel)}`);
648
+ mkdirSync3(dirname3(file), { recursive: true });
649
+ writeFileSync3(file, content);
650
+ console.log(` ${c3.green("✓")} ${c3.gray("created")} ${c3.cyan(rel2)}`);
60
651
  }
61
652
  var component = (Name) => `import type { Component, ComponentChild } from '@fluixi/core';
62
653
 
@@ -110,44 +701,6 @@ export default defineMiddleware([
110
701
  },
111
702
  ]);
112
703
  `;
113
- var authConfig = () => `import { betterAuth } from 'better-auth';
114
- import { defineAuth } from '@fluixi/auth/server';
115
-
116
- export type AppUser = { id: string; email: string; name?: string; role?: string };
117
-
118
- // Better Auth owns the audited primitives; defineAuth registers it with @fluixi/auth.
119
- export const auth = defineAuth<AppUser>(
120
- betterAuth({
121
- // database: <your adapter>,
122
- emailAndPassword: { enabled: true },
123
- // socialProviders: { google: { … }, github: { … } },
124
- } as Parameters<typeof betterAuth>[0]),
125
- );
126
- `;
127
- var authClient = () => `import { createAuthClient } from 'better-auth/client';
128
- import { createAuthHooks } from '@fluixi/auth/client';
129
- import type { AppUser } from './auth.config.js';
130
-
131
- const client = createAuthClient({ baseURL: '/api/auth' });
132
-
133
- // Or, to reuse an existing reactive session: createAuthHooks({ session: yourSessionStore }).
134
- export const { useUser, useSession, useAuth, useSignIn, useSignOut, protectedRoute } =
135
- createAuthHooks<AppUser>({ client, loginPath: '/login' });
136
- `;
137
- var authMiddleware = () => `import { defineMiddleware } from '@fluixi/start';
138
- import { authMiddleware } from '@fluixi/auth/server';
139
- import './auth.config.js';
140
-
141
- export default defineMiddleware([authMiddleware()]);
142
- `;
143
- var authRoute = () => `import { mountAuthRoutes } from '@fluixi/auth/server';
144
- import '../../../auth.config.js';
145
-
146
- const handler = mountAuthRoutes();
147
- export const GET = handler;
148
- export const POST = handler;
149
- export default handler;
150
- `;
151
704
  function generate(kind, name) {
152
705
  switch (kind) {
153
706
  case "component":
@@ -172,58 +725,376 @@ function generate(kind, name) {
172
725
  case "m":
173
726
  write(resolve("src/middleware.ts"), middleware());
174
727
  break;
728
+ case "env": {
729
+ const names = (envPublicNames(resolve("fluixi.config.ts")) ?? []).filter((n) => !n.startsWith("AUTH_"));
730
+ write(resolve("src/config/env.ts"), templates_exports.envConfig(names));
731
+ break;
732
+ }
733
+ case "module": {
734
+ if (!name) return fail("module name required, e.g. `fluixi g module billing`");
735
+ const slug = kebab(name);
736
+ const file = resolve("src/services", slug, `${slug}.module.ts`);
737
+ write(file, templates_exports.moduleFile(pascal(name), slug));
738
+ registerIn(false, file, `${pascal(name)}Module`);
739
+ break;
740
+ }
741
+ case "service":
742
+ case "s": {
743
+ if (!name) return fail("service name required, e.g. `fluixi g service Orders`");
744
+ const Name = pascal(name).replace(/Service$/, "") || "App";
745
+ const server = process.argv.includes("--server");
746
+ const file = resolve("src/services", `${kebab(Name)}${server ? ".server" : ""}.ts`);
747
+ write(file, templates_exports.serviceFile(Name, kebab(Name), server));
748
+ registerIn(server, file, `${Name}Module`);
749
+ break;
750
+ }
751
+ case "api": {
752
+ if (!name) return fail("api path required, e.g. `fluixi g api users/[id]`");
753
+ const file = resolve("src/api", `${name.replace(/\.ts$/, "")}.ts`);
754
+ const role = option("role");
755
+ if (!role) {
756
+ write(file, templates_exports.apiRoute());
757
+ break;
758
+ }
759
+ const verify = resolve("src/services/verify.server.ts");
760
+ write(file, templates_exports.guardedApiRoute(importPath(file, verify), role));
761
+ writeOnce2(verify, templates_exports.verifyServer());
762
+ {
763
+ const steps = [];
764
+ ensureAuthEnv(steps, process.cwd());
765
+ report(steps);
766
+ }
767
+ break;
768
+ }
769
+ case "server-fn": {
770
+ if (!name) return fail("function name required, e.g. `fluixi g server-fn getUser`");
771
+ const fn = name.replace(/[^a-zA-Z0-9]+(.)/g, (_, ch) => ch.toUpperCase());
772
+ write(resolve("src/server", `${fn}.ts`), templates_exports.serverFn(fn));
773
+ break;
774
+ }
175
775
  case "auth":
176
- write(resolve("src/auth.config.ts"), authConfig());
177
- write(resolve("src/auth.client.ts"), authClient());
178
- write(resolve("src/middleware.ts"), authMiddleware());
179
- write(resolve("src/routes/api/auth/[...all].ts"), authRoute());
180
- console.log(` ${c.gray("next: install")} ${c.cyan("better-auth")}${c.gray(", set your DB adapter in auth.config.ts, and forward `request` in entry-server")}`);
776
+ try {
777
+ if (name === "oauth2") {
778
+ reportAuth(
779
+ setupOAuth2(process.cwd(), {
780
+ provider: option("provider"),
781
+ tokens: tokensOption(),
782
+ format: detectFormat()
783
+ }),
784
+ "install @fluixi/oauth2"
785
+ );
786
+ } else if (!name || name === "better-auth") {
787
+ reportAuth(setupBetterAuth(process.cwd()), "install @fluixi/auth and better-auth");
788
+ } else {
789
+ return fail(`unknown auth kind ${name}: oauth2 or better-auth`);
790
+ }
791
+ } catch (error) {
792
+ if (error instanceof ScaffoldError) return fail(error.message);
793
+ throw error;
794
+ }
181
795
  break;
182
796
  default:
183
797
  console.error(GEN_USAGE);
184
798
  process.exit(1);
185
799
  }
186
800
  }
801
+ function tokensOption() {
802
+ const tokens = option("tokens");
803
+ if (tokens !== void 0 && tokens !== "browser" && tokens !== "server") {
804
+ fail("--tokens is browser or server");
805
+ }
806
+ return tokens;
807
+ }
187
808
  function fail(msg) {
188
- console.error(` ${c.red("✗")} ${msg}`);
809
+ console.error(` ${c3.red("✗")} ${msg}`);
189
810
  process.exit(1);
190
811
  }
191
812
 
813
+ // src/add.ts
814
+ import { execFileSync } from "node:child_process";
815
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
816
+ import { join as join2 } from "node:path";
817
+ import { stdin } from "node:process";
818
+ import { c as c4 } from "@fluixi/start/ui";
819
+ var ADD_USAGE = `Usage: fluixi add <feature> [options]
820
+
821
+ Features:
822
+ auth [oauth2|better-auth] authentication, asked for when not given
823
+ --provider <p> ${PROVIDERS.join(", ")}
824
+ --tokens browser|server where an OAuth2 app keeps its tokens
825
+ --no-install write the files, leave the packages to you
826
+ `;
827
+ function option2(args, name) {
828
+ const i = args.indexOf(`--${name}`);
829
+ if (i !== -1 && args[i + 1] && !args[i + 1].startsWith("-")) return args[i + 1];
830
+ return args.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3);
831
+ }
832
+ function installCommand(root, specs) {
833
+ if (existsSync4(join2(root, "pnpm-lock.yaml"))) return ["pnpm", ["add", ...specs]];
834
+ if (existsSync4(join2(root, "yarn.lock"))) return ["yarn", ["add", ...specs]];
835
+ if (existsSync4(join2(root, "bun.lockb")) || existsSync4(join2(root, "bun.lock"))) return ["bun", ["add", ...specs]];
836
+ return ["npm", ["install", ...specs]];
837
+ }
838
+ function channelOf(root) {
839
+ try {
840
+ const version = JSON.parse(readFileSync4(join2(root, "node_modules/@fluixi/start/package.json"), "utf8")).version;
841
+ return version.match(/-([a-z]+)\./)?.[1] ?? "latest";
842
+ } catch {
843
+ return "alpha";
844
+ }
845
+ }
846
+ async function addAuth(root, args) {
847
+ const ask = stdin.isTTY;
848
+ let kind = args[1] && !args[1].startsWith("-") ? args[1] : void 0;
849
+ let provider = option2(args, "provider");
850
+ let tokens = option2(args, "tokens");
851
+ if (kind && kind !== "oauth2" && kind !== "better-auth") throw new ScaffoldError(`unknown auth kind ${kind}: oauth2 or better-auth`);
852
+ if (tokens && tokens !== "browser" && tokens !== "server") throw new ScaffoldError("--tokens is browser or server");
853
+ if (provider && !PROVIDERS.includes(provider)) throw new ScaffoldError(`unknown provider ${provider}: ${PROVIDERS.join(", ")}`);
854
+ if (!kind && ask) {
855
+ kind = await askSelect("Authentication", [
856
+ { value: "oauth2", label: "OAuth2 / OIDC", hint: "@fluixi/oauth2 · Keycloak, Auth0, Okta, Google…" },
857
+ { value: "better-auth", label: "Better Auth", hint: "@fluixi/auth · your own user table" }
858
+ ]);
859
+ }
860
+ kind ??= "oauth2";
861
+ if (kind === "oauth2" && !provider && ask) {
862
+ provider = await askSelect("Identity provider", PROVIDERS.map((p) => ({ value: p, label: p, hint: "" })));
863
+ }
864
+ if (kind === "oauth2" && !tokens && ask && !SERVER_ONLY[provider ?? "oidc"]) {
865
+ tokens = await askSelect("Where the tokens live", [
866
+ { value: "browser", label: "Browser", hint: "public client · PKCE" },
867
+ { value: "server", label: "Server", hint: "httpOnly cookie · client secret" }
868
+ ]);
869
+ }
870
+ const channel = channelOf(root);
871
+ const result = kind === "oauth2" ? setupOAuth2(root, { provider, tokens, format: projectFormat(root) }, channel) : setupBetterAuth(root, channel);
872
+ const specs = Object.entries(result.dependencies).map(([name, spec]) => `${name}@${spec}`);
873
+ if (args.includes("--no-install")) {
874
+ reportAuth(result, `install ${specs.join(" ")}`);
875
+ return;
876
+ }
877
+ reportAuth(result);
878
+ const [bin, binArgs] = installCommand(root, specs);
879
+ console.log(` ${c4.gray("›")} ${c4.cyan([bin, ...binArgs].join(" "))}`);
880
+ execFileSync(bin, binArgs, { cwd: root, stdio: "inherit" });
881
+ }
882
+ async function add(feature, args, root = process.cwd()) {
883
+ if (feature !== "auth") {
884
+ console.error(ADD_USAGE);
885
+ process.exitCode = 1;
886
+ return;
887
+ }
888
+ try {
889
+ await addAuth(root, args);
890
+ } catch (error) {
891
+ if (!(error instanceof ScaffoldError)) throw error;
892
+ console.error(` ${c4.red("✗")} ${error.message}`);
893
+ process.exitCode = 1;
894
+ }
895
+ }
896
+
192
897
  // src/start-copy.ts
193
898
  import { realpathSync } from "node:fs";
194
899
  import { createRequire } from "node:module";
195
- import { dirname as dirname2, join } from "node:path";
900
+ import { dirname as dirname4, join as join3 } from "node:path";
196
901
  function locate(from) {
197
902
  try {
198
903
  const file = createRequire(from).resolve("@fluixi/start/package.json");
199
- return { dir: dirname2(realpathSync(file)), version: createRequire(from)(file).version };
904
+ return { dir: dirname4(realpathSync(file)), version: createRequire(from)(file).version };
200
905
  } catch {
201
906
  return null;
202
907
  }
203
908
  }
204
909
  function startMismatch(appRoot, cliFile) {
205
- const app = locate(join(appRoot, "package.json"));
910
+ const app = locate(join3(appRoot, "package.json"));
206
911
  const cli = locate(cliFile);
207
912
  if (!app || !cli || app.dir === cli.dir) return null;
208
913
  return { app, cli };
209
914
  }
210
915
 
916
+ // src/check.ts
917
+ import { existsSync as existsSync5 } from "node:fs";
918
+ import { createRequire as createRequire2 } from "node:module";
919
+ import { dirname as dirname5, join as join4, relative as relative4, resolve as resolve2 } from "node:path";
920
+ import { envAuthDiagnostics } from "@fluixi/ts-plugin/rules";
921
+ import { c as c5 } from "@fluixi/start/ui";
922
+ function loadTypeScript(root) {
923
+ try {
924
+ return createRequire2(join4(root, "package.json"))("typescript");
925
+ } catch {
926
+ throw new Error("fluixi check needs typescript in the app: npm install -D typescript");
927
+ }
928
+ }
929
+ function rootFiles(ts, configPath, seen = /* @__PURE__ */ new Set()) {
930
+ seen.add(configPath);
931
+ const read = ts.readConfigFile(configPath, ts.sys.readFile);
932
+ if (read.error) throw new Error(ts.flattenDiagnosticMessageText(read.error.messageText, "\n"));
933
+ const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname5(configPath));
934
+ const files = [...parsed.fileNames];
935
+ let options = parsed.options;
936
+ for (const ref of parsed.projectReferences ?? []) {
937
+ const path = ts.resolveProjectReferencePath(ref);
938
+ if (seen.has(path) || !existsSync5(path)) continue;
939
+ const child = rootFiles(ts, path, seen);
940
+ files.push(...child.files);
941
+ if (!parsed.fileNames.length) options = child.options;
942
+ }
943
+ return { files, options };
944
+ }
945
+ function checkProject(root = process.cwd(), ts = loadTypeScript(root)) {
946
+ const configPath = ts.findConfigFile(root, ts.sys.fileExists, "tsconfig.json");
947
+ if (!configPath) throw new Error(`no tsconfig.json in ${root}`);
948
+ const { files, options } = rootFiles(ts, configPath);
949
+ for (const name of ["fluixi.config.ts", "fluixi.config.mts", "fluixi.config.js"]) {
950
+ const path = resolve2(root, name);
951
+ if (existsSync5(path) && !files.includes(path)) files.push(path);
952
+ }
953
+ const compilerOptions = { ...options, noEmit: true };
954
+ const host = ts.createCompilerHost(compilerOptions, true);
955
+ const program = ts.createProgram({ rootNames: [...new Set(files)], options: compilerOptions, host });
956
+ const out = [];
957
+ for (const sf of program.getSourceFiles()) {
958
+ if (sf.isDeclarationFile || /[\\/]node_modules[\\/]/.test(sf.fileName)) continue;
959
+ for (const d of envAuthDiagnostics(ts, program, sf.fileName, ts.sys)) {
960
+ const at = sf.getLineAndCharacterOfPosition(d.start ?? 0);
961
+ out.push({
962
+ file: relative4(root, sf.fileName),
963
+ line: at.line + 1,
964
+ column: at.character + 1,
965
+ code: d.code,
966
+ severity: d.category === ts.DiagnosticCategory.Error ? "error" : d.category === ts.DiagnosticCategory.Warning ? "warning" : "suggestion",
967
+ message: ts.flattenDiagnosticMessageText(d.messageText, " ")
968
+ });
969
+ }
970
+ }
971
+ return out.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column);
972
+ }
973
+ function check(root = process.cwd(), strict = false) {
974
+ const found = checkProject(root);
975
+ const shown = found.filter((f) => f.severity !== "suggestion");
976
+ const mark = { error: c5.red("error"), warning: c5.yellow("warning"), suggestion: c5.gray("note") };
977
+ const lines = shown.map(
978
+ (f) => ` ${c5.cyan(`${f.file}:${f.line}:${f.column}`)} ${mark[f.severity]} ${c5.gray(`FX${f.code}`)} ${f.message}`
979
+ );
980
+ const errors = shown.filter((f) => f.severity === "error").length;
981
+ const warnings = shown.length - errors;
982
+ const notes = found.length - shown.length;
983
+ const tally = [`${errors} error${errors === 1 ? "" : "s"}`, `${warnings} warning${warnings === 1 ? "" : "s"}`];
984
+ if (notes) tally.push(`${notes} note${notes === 1 ? "" : "s"}`);
985
+ console.log(["", ...lines, ...lines.length ? [""] : [], ` ${shown.length ? c5.bold(tally.join(", ")) : `${c5.green("✓")} no env or auth findings`}`, ""].join("\n"));
986
+ return errors || strict && warnings ? 1 : 0;
987
+ }
988
+
989
+ // src/doctor.ts
990
+ import { existsSync as existsSync6, readdirSync, readFileSync as readFileSync5, realpathSync as realpathSync2 } from "node:fs";
991
+ import { createRequire as createRequire3 } from "node:module";
992
+ import { join as join5 } from "node:path";
993
+ var readJson = (file) => JSON.parse(readFileSync5(file, "utf8"));
994
+ function resolvedVersions(root) {
995
+ const out = {};
996
+ const scope = join5(root, "node_modules/@fluixi");
997
+ if (!existsSync6(scope)) return out;
998
+ for (const name of readdirSync(scope).sort()) {
999
+ const file = join5(scope, name, "package.json");
1000
+ if (existsSync6(file)) out[`@fluixi/${name}`] = readJson(file).version;
1001
+ }
1002
+ return out;
1003
+ }
1004
+ function installedCopies(root) {
1005
+ const found = /* @__PURE__ */ new Map();
1006
+ const seen = /* @__PURE__ */ new Set();
1007
+ const add2 = (dir) => {
1008
+ const file = join5(dir, "package.json");
1009
+ if (!existsSync6(file)) return;
1010
+ const real = realpathSync2(dir);
1011
+ if (seen.has(real)) return;
1012
+ seen.add(real);
1013
+ const { name, version } = readJson(file);
1014
+ if (!found.has(name)) found.set(name, /* @__PURE__ */ new Set());
1015
+ found.get(name).add(version);
1016
+ };
1017
+ const scan = (modules, depth) => {
1018
+ const scope = join5(modules, "@fluixi");
1019
+ if (existsSync6(scope)) {
1020
+ for (const name of readdirSync(scope)) {
1021
+ add2(join5(scope, name));
1022
+ if (depth > 0) scan(join5(scope, name, "node_modules"), depth - 1);
1023
+ }
1024
+ }
1025
+ };
1026
+ const top = join5(root, "node_modules");
1027
+ scan(top, 2);
1028
+ const store = join5(top, ".pnpm");
1029
+ if (existsSync6(store)) {
1030
+ for (const entry of readdirSync(store)) {
1031
+ if (entry.startsWith("@fluixi+")) scan(join5(store, entry, "node_modules"), 0);
1032
+ }
1033
+ }
1034
+ return Object.fromEntries([...found].map(([k, v]) => [k, [...v].sort()]));
1035
+ }
1036
+ function pluginConfigured(root) {
1037
+ const file = join5(root, "tsconfig.json");
1038
+ if (!existsSync6(file)) return null;
1039
+ let config;
1040
+ try {
1041
+ const ts = createRequire3(join5(root, "package.json"))("typescript");
1042
+ config = ts.readConfigFile(file, ts.sys.readFile).config;
1043
+ } catch {
1044
+ try {
1045
+ config = readJson(file);
1046
+ } catch {
1047
+ return null;
1048
+ }
1049
+ }
1050
+ return (config?.compilerOptions?.plugins ?? []).some((p) => p.name === "@fluixi/ts-plugin");
1051
+ }
1052
+ function diagnose(root) {
1053
+ const problems = [];
1054
+ for (const [name, versions] of Object.entries(installedCopies(root))) {
1055
+ if (versions.length > 1) {
1056
+ problems.push({ severity: "error", message: `${name} is installed ${versions.length} times (${versions.join(", ")}); each copy keeps its own state` });
1057
+ }
1058
+ }
1059
+ const pkg = existsSync6(join5(root, "package.json")) ? readJson(join5(root, "package.json")) : {};
1060
+ const declared = { ...pkg.dependencies, ...pkg.devDependencies };
1061
+ const prerelease = Object.entries(declared).filter(([n]) => n.startsWith("@fluixi/")).map(([, v]) => v.match(/-(alpha|beta|rc)\.\d+/)?.[1]).filter(Boolean);
1062
+ if (new Set(prerelease).size > 1) {
1063
+ problems.push({ severity: "warning", message: `@fluixi/* dependencies mix prerelease tags (${[...new Set(prerelease)].join(", ")})` });
1064
+ }
1065
+ const plugin = pluginConfigured(root);
1066
+ if (plugin === false) {
1067
+ problems.push({
1068
+ severity: "warning",
1069
+ message: 'tsconfig.json does not load @fluixi/ts-plugin: the editor shows no env or auth warnings. Add { "name": "@fluixi/ts-plugin" } to compilerOptions.plugins'
1070
+ });
1071
+ } else if (plugin && !existsSync6(join5(root, "node_modules/@fluixi/ts-plugin"))) {
1072
+ problems.push({ severity: "warning", message: "tsconfig.json names @fluixi/ts-plugin, which is not installed" });
1073
+ }
1074
+ return problems;
1075
+ }
1076
+
211
1077
  // src/cli.ts
212
1078
  function usage() {
213
- const cmd = (name, desc) => ` ${c2.cyan(name.padEnd(25))}${c2.gray(desc)}`;
1079
+ const cmd = (name, desc) => ` ${c6.cyan(name.padEnd(25))}${c6.gray(desc)}`;
214
1080
  return [
215
1081
  "",
216
- ` ${wordmark()} ${c2.gray("the Fluixi command-line tool")}`,
1082
+ ` ${wordmark()} ${c6.gray("the Fluixi command-line tool")}`,
217
1083
  "",
218
- ` ${c2.bold("Usage")} ${c2.gray("fluixi <command>")}`,
1084
+ ` ${c6.bold("Usage")} ${c6.gray("fluixi <command>")}`,
219
1085
  "",
220
1086
  cmd("dev", "start the SSR dev server (Vite middleware + HMR)"),
221
1087
  cmd("build", "build the client + server bundles for production"),
222
1088
  cmd("build --format=web-component", "build custom elements as portable files"),
223
1089
  cmd("start", "run the production SSR server (after build)"),
224
- cmd("generate <kind> <name>", "scaffold a component / route / middleware / auth " + c2.dim("(alias: g)")),
1090
+ cmd("generate <kind> <name>", "scaffold code, see fluixi g --help " + c6.dim("(alias: g)")),
1091
+ cmd("add auth", "set up authentication: asks, writes, installs"),
1092
+ cmd("check [--strict]", "env and auth rules over the project, for CI"),
1093
+ cmd("env", "declared and set variables, secrets that would ship, env types"),
1094
+ cmd("doctor", "duplicate packages, editor plugin, env problems"),
1095
+ cmd("info", "versions, adapter, modules, page and API routes"),
225
1096
  "",
226
- ` ${c2.gray("New project:")} ${c2.cyan("npm create fluixi")} ${c2.gray("<dir>")}`,
1097
+ ` ${c6.gray("New project:")} ${c6.cyan("npm create fluixi")} ${c6.gray("<dir>")}`,
227
1098
  ""
228
1099
  ].join("\n");
229
1100
  }
@@ -237,13 +1108,21 @@ async function main() {
237
1108
  generate(process.argv[3], process.argv[4]);
238
1109
  return;
239
1110
  }
1111
+ if (cmd === "add") {
1112
+ await add(process.argv[3], process.argv.slice(3));
1113
+ return;
1114
+ }
1115
+ if (cmd === "check") {
1116
+ process.exitCode = check(process.cwd(), process.argv.includes("--strict"));
1117
+ return;
1118
+ }
240
1119
  const config = await loadConfig();
241
1120
  const mismatch = startMismatch(process.cwd(), import.meta.url);
242
1121
  if (mismatch) {
243
1122
  const { app, cli } = mismatch;
244
1123
  console.warn(
245
1124
  `
246
- ${c2.yellow("!")} fluixi is running @fluixi/start ${cli.version} from ${cli.dir}
1125
+ ${c6.yellow("!")} fluixi is running @fluixi/start ${cli.version} from ${cli.dir}
247
1126
  but this app resolves ${app.version} from ${app.dir}.
248
1127
  Changes to the app's copy will not take effect. With npm, add
249
1128
  "overrides": { "@fluixi/start": "$@fluixi/start" } to package.json and reinstall.
@@ -263,16 +1142,36 @@ async function main() {
263
1142
  case "start":
264
1143
  await start(config);
265
1144
  break;
1145
+ case "env":
1146
+ process.exitCode = await env2(config);
1147
+ break;
1148
+ case "info":
1149
+ await info(config, resolvedVersions(config.root ?? process.cwd()));
1150
+ break;
1151
+ case "doctor":
1152
+ process.exitCode = await doctor(config);
1153
+ break;
266
1154
  default:
267
1155
  console.error(`
268
- ${c2.red("✗")} Unknown command: ${c2.bold(cmd)}`);
1156
+ ${c6.red("✗")} Unknown command: ${c6.bold(cmd)}`);
269
1157
  console.log(usage());
270
1158
  process.exit(1);
271
1159
  }
272
1160
  }
1161
+ async function doctor(config) {
1162
+ const problems = diagnose(config.root ?? process.cwd());
1163
+ const r = await envReport(config);
1164
+ for (const n of r.secretPublic) problems.push({ severity: "error", message: `${n} is in env.public and reads like a secret` });
1165
+ for (const e of r.exposed) problems.push({ severity: "error", message: `${e.name} in ${e.file} carries the client prefix, so Vite ships it` });
1166
+ for (const p of r.public.filter((p2) => !p2.set)) problems.push({ severity: "warning", message: `${p.name} is in env.public and not set` });
1167
+ for (const n of r.missing) problems.push({ severity: "warning", message: `${n} is in .env.example and not set locally` });
1168
+ const lines = problems.map((p) => ` ${p.severity === "error" ? c6.red("✗") : c6.yellow("!")} ${p.message}`);
1169
+ console.log(["", ...lines.length ? lines : [` ${c6.green("✓")} nothing to report`], ""].join("\n"));
1170
+ return problems.some((p) => p.severity === "error") ? 1 : 0;
1171
+ }
273
1172
  main().catch((e) => {
274
1173
  console.error(`
275
- ${c2.red("✗")} ${e?.message ?? e}
1174
+ ${c6.red("✗")} ${e?.message ?? e}
276
1175
  `);
277
1176
  process.exit(1);
278
1177
  });