create-fluixi 0.1.0-alpha.12 → 0.1.0-alpha.13

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/index.js CHANGED
@@ -1,153 +1,583 @@
1
1
  #!/usr/bin/env node
2
- /**
3
- * `npm create fluixi <dir>`: scaffold a new Fluixi app. Prompts for a name, a mode
4
- * (SSR via @fluixi/start, or SPA via vite + @fluixi/vite-plugin), and a template syntax
5
- * (JSX or html``), unless given on the command line: `create-fluixi my-app --spa --html`
6
- * (`--ssr`/`--spa`, `--jsx`/`--html`). The html`` variant is JSX-free, plain `.ts`
7
- * sources, no `jsx` in tsconfig. Zero runtime deps, the styled prompts (gradient
8
- * wordmark, gutter, arrow-key select) are hand-rolled ANSI.
9
- */
10
- import { cpSync, renameSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
11
- import { resolve, basename, join } from 'node:path';
12
- import { fileURLToPath } from 'node:url';
13
- import { createInterface } from 'node:readline/promises';
14
- import { emitKeypressEvents } from 'node:readline';
15
- import { stdin as input, stdout as output, argv, exit, env } from 'node:process';
16
- const here = (p) => fileURLToPath(new URL(p, import.meta.url));
17
- // ── tiny zero-dep ANSI styling ──────────────────────────────────────────────
18
- const COLOR = env.NO_COLOR || env.FORCE_COLOR === '0'
19
- ? false
20
- : (!!output.isTTY || !!env.FORCE_COLOR) && env.TERM !== 'dumb';
21
- const sgr = (o, x) => (s) => (COLOR ? `\x1b[${o}m${s}\x1b[${x}m` : `${s}`);
22
- const c = {
23
- bold: sgr(1, 22), dim: sgr(2, 22), green: sgr(32, 39), yellow: sgr(33, 39),
24
- cyan: sgr(36, 39), gray: sgr(90, 39), red: sgr(31, 39),
2
+
3
+ // src/index.ts
4
+ import { cpSync, renameSync, readFileSync as readFileSync3, writeFileSync as writeFileSync3, existsSync as existsSync3 } from "node:fs";
5
+ import { resolve, basename, join as join2 } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+
8
+ // ../cli/dist/scaffold/index.mjs
9
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
10
+ import { dirname as dirname2, join, relative } from "node:path";
11
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
+ import { dirname } from "node:path";
13
+ import { createInterface } from "node:readline/promises";
14
+ import { emitKeypressEvents } from "node:readline";
15
+ import { stdin as input, stdout as output, exit, env } from "node:process";
16
+ var __defProp = Object.defineProperty;
17
+ var __export = (target, all) => {
18
+ for (var name in all)
19
+ __defProp(target, name, { get: all[name], enumerable: true });
25
20
  };
26
- const rgb = (r, g, b) => (s) => (COLOR ? `\x1b[38;2;${r};${g};${b}m${s}\x1b[39m` : s);
27
- const BRAND = [
28
- [34, 211, 238], [56, 189, 248], [129, 140, 248], [167, 139, 250], [192, 132, 252],
29
- ];
30
- const gradient = (text) => {
31
- if (!COLOR)
32
- return text;
33
- const ch = [...text];
34
- return ch.map((x, i) => {
35
- const [r, g, b] = BRAND[Math.min(BRAND.length - 1, Math.floor((i / Math.max(1, ch.length - 1)) * (BRAND.length - 1)))];
36
- return rgb(r, g, b)(x);
37
- }).join('');
21
+ function closing(text, open) {
22
+ let depth = 0;
23
+ for (let i = open; i < text.length; i++) {
24
+ const ch = text[i];
25
+ if (ch === "/" && text[i + 1] === "/") i = text.indexOf("\n", i) === -1 ? text.length : text.indexOf("\n", i);
26
+ else if (ch === "/" && text[i + 1] === "*") i = text.indexOf("*/", i + 2) + 1;
27
+ else if (ch === "'" || ch === '"' || ch === "`") {
28
+ for (i++; i < text.length && text[i] !== ch; i++) if (text[i] === "\\") i++;
29
+ } else if ("([{".includes(ch)) depth++;
30
+ else if (")]}".includes(ch) && --depth === 0) return i;
31
+ }
32
+ return -1;
33
+ }
34
+ function appendToArray(text, open, items) {
35
+ const close = closing(text, open);
36
+ const inner = text.slice(open + 1, close);
37
+ if (!inner.trim()) return text.slice(0, open + 1) + items.join(", ") + text.slice(close);
38
+ if (inner.includes("\n")) {
39
+ const last = inner.trimEnd();
40
+ const indent = last.slice(last.lastIndexOf("\n") + 1).match(/^\s*/)[0];
41
+ const comma = last.endsWith(",") ? "" : ",";
42
+ const tail = inner.slice(last.length);
43
+ return text.slice(0, open + 1) + last + comma + items.map((i) => `
44
+ ${indent}${i},`).join("") + tail + text.slice(close);
45
+ }
46
+ const body = inner.replace(/,?\s*$/, "");
47
+ const trailing = inner.slice(body.length).replace(/^,/, "");
48
+ return text.slice(0, open + 1) + body + ", " + items.join(", ") + trailing + text.slice(close);
49
+ }
50
+ function addImport(text, line) {
51
+ if (text.includes(line)) return text;
52
+ const imports = [...text.matchAll(/^import[\s\S]*?from\s+['"][^'"]+['"];?[^\n]*\n/gm)];
53
+ const at = imports.length ? imports[imports.length - 1].index + imports[imports.length - 1][0].length : 0;
54
+ return text.slice(0, at) + line + "\n" + text.slice(at);
55
+ }
56
+ function register(log, file, header, r) {
57
+ const imports = [...r.extraImports ?? [], r.importLine];
58
+ if (!existsSync(file)) {
59
+ mkdirSync(dirname(file), { recursive: true });
60
+ writeFileSync(
61
+ file,
62
+ `${header}import { defineApp } from '@fluixi/start/app';
63
+ ${imports.join("\n")}
64
+
65
+ export default defineApp({ imports: [${r.entry}] });
66
+ `
67
+ );
68
+ log.push({ kind: "created", file });
69
+ return true;
70
+ }
71
+ let text = readFileSync(file, "utf8");
72
+ if (text.includes(r.importLine)) {
73
+ log.push({ kind: "listed", file, detail: r.entry });
74
+ return true;
75
+ }
76
+ const m = text.match(/\bimports\s*:\s*\[/);
77
+ if (!m) {
78
+ log.push({ kind: "hint", file, lines: [...imports, `imports: [${r.entry}]`] });
79
+ return false;
80
+ }
81
+ text = appendToArray(text, m.index + m[0].length - 1, [r.entry]);
82
+ for (const line of imports) text = addImport(text, line);
83
+ writeFileSync(file, text);
84
+ log.push({ kind: "updated", file, detail: `imports ${r.entry}` });
85
+ return true;
86
+ }
87
+ function envPublicNames(configFile) {
88
+ if (!existsSync(configFile)) return null;
89
+ const text = readFileSync(configFile, "utf8");
90
+ const m = text.match(/\bpublic\s*:\s*\[/);
91
+ if (!m) return null;
92
+ const open = m.index + m[0].length - 1;
93
+ const list = text.slice(open, closing(text, open) + 1);
94
+ return [...list.matchAll(/['"]([A-Za-z_][A-Za-z0-9_]*)['"]/g)].map((x) => x[1]);
95
+ }
96
+ function addEnvPublic(log, configFile, names) {
97
+ const list = (indent) => `${indent}public: [
98
+ ${names.map((n) => `${indent} '${n}',
99
+ `).join("")}${indent}],
100
+ `;
101
+ const have = envPublicNames(configFile);
102
+ if (have === null) {
103
+ const text2 = existsSync(configFile) ? readFileSync(configFile, "utf8") : "";
104
+ const call = text2.match(/defineConfig\(\{\n/);
105
+ if (call && !/\benv\s*:/.test(text2)) {
106
+ const at = call.index + call[0].length;
107
+ writeFileSync(configFile, text2.slice(0, at) + ` env: {
108
+ ${list(" ")} },
109
+ ` + text2.slice(at));
110
+ log.push({ kind: "updated", file: configFile, detail: `env.public ${names.join(", ")}` });
111
+ return;
112
+ }
113
+ log.push({ kind: "hint", file: configFile, lines: [`env: { public: [${names.map((n) => `'${n}'`).join(", ")}] },`] });
114
+ return;
115
+ }
116
+ const missing = names.filter((n) => !have.includes(n));
117
+ if (!missing.length) return;
118
+ const text = readFileSync(configFile, "utf8");
119
+ const m = text.match(/\bpublic\s*:\s*\[/);
120
+ writeFileSync(configFile, appendToArray(text, m.index + m[0].length - 1, missing.map((n) => `'${n}'`)));
121
+ log.push({ kind: "updated", file: configFile, detail: `env.public + ${missing.join(", ")}` });
122
+ }
123
+ function addEnvExample(log, file, comment, vars) {
124
+ const text = existsSync(file) ? readFileSync(file, "utf8") : "";
125
+ const have = new Set([...text.matchAll(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/gm)].map((m) => m[1]));
126
+ const add = Object.entries(vars).filter(([k]) => !have.has(k) && !have.has(`VITE_${k}`));
127
+ if (!add.length) return;
128
+ const block = `${comment.split("\n").map((l) => `# ${l}`).join("\n")}
129
+ ${add.map(([k, v]) => `${k}=${v}`).join("\n")}
130
+ `;
131
+ writeFileSync(file, text ? `${text.replace(/\n*$/, "\n")}
132
+ ${block}` : block);
133
+ log.push({ kind: text ? "updated" : "created", file, detail: add.map(([k]) => k).join(", ") });
134
+ }
135
+ var templates_exports = {};
136
+ __export(templates_exports, {
137
+ AUTH_READER: () => AUTH_READER,
138
+ PROVIDERS: () => PROVIDERS,
139
+ PROVIDER_VARS: () => PROVIDER_VARS,
140
+ SERVER_ONLY: () => SERVER_ONLY,
141
+ apiRoute: () => apiRoute,
142
+ authEnvConfig: () => authEnvConfig,
143
+ authServerFile: () => authServerFile,
144
+ authServiceFile: () => authServiceFile,
145
+ betterAuthClient: () => betterAuthClient,
146
+ betterAuthConfig: () => betterAuthConfig,
147
+ betterAuthMiddleware: () => betterAuthMiddleware,
148
+ betterAuthRoute: () => betterAuthRoute,
149
+ callbackRoute: () => callbackRoute,
150
+ camel: () => camel,
151
+ envConfig: () => envConfig,
152
+ guardedApiRoute: () => guardedApiRoute,
153
+ loginRoute: () => loginRoute,
154
+ moduleFile: () => moduleFile,
155
+ serverFn: () => serverFn,
156
+ serviceFile: () => serviceFile,
157
+ verifyServer: () => verifyServer
158
+ });
159
+ var camel = (name) => name.toLowerCase().replace(/_+([a-z0-9])/g, (_, ch) => ch.toUpperCase());
160
+ var envConfig = (names) => {
161
+ const fields = names.length ? names.map((n) => ` ${camel(n)}: '${n}',`).join("\n") : ` // apiUrl: 'API_URL',`;
162
+ return `import { pickEnv } from '@fluixi/start/env';
163
+
164
+ // Every missing variable is reported at once, when this module loads. A field that may be
165
+ // unset takes { key, optional: true } or { key, default }; parse: asNumber and friends convert.
166
+ export const config = pickEnv({
167
+ ${fields}
168
+ });
169
+ `;
170
+ };
171
+ var moduleFile = (Name, name) => `import { defineModule } from '@fluixi/start/app';
172
+
173
+ export const ${Name}Module = defineModule({
174
+ name: '${name}',
175
+ imports: [],
176
+ providers: [],
177
+ });
178
+ `;
179
+ var serviceFile = (Name, name, server) => `${server ? `// Server only: the browser build refuses a page that imports this file.
180
+ ` : ""}import { injectionToken } from '@fluixi/start/di';
181
+ import { defineModule } from '@fluixi/start/app';
182
+
183
+ export class ${Name}Service {}
184
+
185
+ export const ${Name}Token = injectionToken<${Name}Service>('${Name}');
186
+
187
+ export const ${Name}Module = defineModule({
188
+ name: '${name}',
189
+ providers: [{ provide: ${Name}Token, useFactory: () => new ${Name}Service() }],
190
+ });
191
+ `;
192
+ var apiRoute = () => `export function GET(request: Request) {
193
+ return Response.json({ path: new URL(request.url).pathname });
194
+ }
195
+ `;
196
+ var guardedApiRoute = (guardImport, role) => `import { guard } from '${guardImport}';
197
+
198
+ export const GET = guard(
199
+ async (request, claims) => {
200
+ return Response.json({ sub: claims.sub });
201
+ },
202
+ { role: '${role}' },
203
+ );
204
+ `;
205
+ var verifyServer = () => `import { createTokenVerifier, createApiGuard } from '@fluixi/oauth2/verify';
206
+ import { auth } from '../config/env.js';
207
+
208
+ // Checks a bearer token's signature, issuer, audience and expiry against the provider.
209
+ export const verify = createTokenVerifier(auth.provider.verifier(auth.clientId));
210
+
211
+ // Answers 401 without a valid token and 403 without the role.
212
+ export const guard = createApiGuard({ verify, roles: auth.provider.roles });
213
+ `;
214
+ var serverFn = (name) => `export async function ${name}(input: { id: string }) {
215
+ 'use server';
216
+ // Runs on the server only. The browser calls it over RPC, so input and result are plain data.
217
+ return { id: input.id };
218
+ }
219
+ `;
220
+ var PROVIDERS = ["oidc", "keycloak", "auth0", "okta", "google", "dex", "oauth2"];
221
+ var SERVER_ONLY = {
222
+ google: "Google answers a token request without a client secret with `client_secret is missing`",
223
+ dex: "Dex sends no CORS headers on discovery or the token endpoint"
224
+ };
225
+ var PROVIDER_VARS = {
226
+ oidc: { AUTH_ISSUER: "https://id.example.com" },
227
+ keycloak: { AUTH_BASE_URL: "http://localhost:8080", AUTH_REALM: "master" },
228
+ auth0: { AUTH_DOMAIN: "example.eu.auth0.com", AUTH_AUDIENCE: "https://api.example.com" },
229
+ okta: { AUTH_DOMAIN: "example.okta.com" },
230
+ google: {},
231
+ dex: { AUTH_BASE_URL: "http://localhost:5556/dex" },
232
+ oauth2: {
233
+ AUTH_ISSUER: "https://id.example.com",
234
+ AUTH_AUTHORIZATION_ENDPOINT: "https://id.example.com/authorize",
235
+ AUTH_TOKEN_ENDPOINT: "https://id.example.com/token"
236
+ }
237
+ };
238
+ var AUTH_READER = `// Provider, issuer, client and token mode from the AUTH_* variables in env.public. Moving to
239
+ // another provider is a change to .env.
240
+ export const auth = authFromEnv(publicEnv(), { clientPrefix: '' });
241
+ `;
242
+ var authEnvConfig = () => `import { publicEnv } from '@fluixi/start/env';
243
+ import { authFromEnv } from '@fluixi/oauth2/env';
244
+
245
+ ${AUTH_READER}`;
246
+ var authServiceFile = (tokens) => `import { createAuthService, authModule } from '@fluixi/oauth2';
247
+ import { env } from '@fluixi/start/env';
248
+ ${tokens === "browser" ? `import { auth as authEnv } from '../config/env.js';
249
+ ` : ""}
250
+ export interface User {
251
+ sub: string;
252
+ email?: string;
253
+ name?: string;
254
+ }
255
+
256
+ const appUrl = env('APP_URL') ?? 'http://localhost:3000';
257
+
258
+ export const auth = createAuthService<User>({
259
+ ${tokens === "browser" ? ` config: {
260
+ ...authEnv.client,
261
+ tokens: 'browser',
262
+ redirectUri: \`\${appUrl}/callback\`,
263
+ postLogoutRedirectUri: \`\${appUrl}/login\`,
264
+ },` : ` // The tokens stay on the server behind an httpOnly cookie. The browser calls the routes
265
+ // auth.server.ts mounts under basePath and never sees a token.
266
+ config: {
267
+ tokens: 'server',
268
+ redirectUri: \`\${appUrl}/auth/callback\`,
269
+ postLogoutRedirectUri: \`\${appUrl}/login\`,
270
+ basePath: '/auth',
271
+ },`}
272
+ });
273
+
274
+ export const AuthModule = authModule(auth);
275
+ export const { protectedRoute, Protect, Can, useUser } = auth;
276
+ `;
277
+ var authServerFile = () => `import { authServerModule } from '@fluixi/oauth2/server';
278
+ import { publicEnv, serverEnv } from '@fluixi/start/env';
279
+ import { auth } from '../config/env.js';
280
+
281
+ // A function: serverEnv with required throws when a secret is unset, and it is only read
282
+ // when app.config.server.ts registers this.
283
+ export function authServer() {
284
+ const appUrl = publicEnv().APP_URL ?? 'http://localhost:3000';
285
+ return authServerModule({
286
+ ...auth.client,
287
+ clientSecret: serverEnv('OIDC_CLIENT_SECRET', { required: true }),
288
+ cookieSecret: serverEnv('SESSION_SECRET', { required: true }),
289
+ redirectUri: \`\${appUrl}/auth/callback\`,
290
+ defaultReturnTo: '/',
291
+ secureCookie: appUrl.startsWith('https://'),
292
+ });
293
+ }
294
+ `;
295
+ var callbackRoute = (html) => html ? `import { html } from '@fluixi/core';
296
+ import { OAuthCallback } from '@fluixi/oauth2/callback';
297
+
298
+ export default OAuthCallback({
299
+ pending: () => html\`<p>Signing you in</p>\`,
300
+ failed: (reason) => html\`<p>\${reason}</p><a href="/login">Try again</a>\`,
301
+ });
302
+ ` : `import { OAuthCallback } from '@fluixi/oauth2/callback';
303
+
304
+ export default OAuthCallback({
305
+ pending: () => <p>Signing you in</p>,
306
+ failed: (reason) => (
307
+ <>
308
+ <p>{reason}</p>
309
+ <a href="/login">Try again</a>
310
+ </>
311
+ ),
312
+ });
313
+ `;
314
+ var loginRoute = (html) => html ? `import { html } from '@fluixi/core';
315
+ import { auth } from '../services/auth.js';
316
+
317
+ export default function Login() {
318
+ return html\`<button @click=\${() => auth.signIn({ returnTo: '/' })}>Sign in</button>\`;
319
+ }
320
+ ` : `import { auth } from '../services/auth.js';
321
+
322
+ export default function Login() {
323
+ return <button onClick={() => auth.signIn({ returnTo: '/' })}>Sign in</button>;
324
+ }
325
+ `;
326
+ var betterAuthConfig = () => `import { betterAuth } from 'better-auth';
327
+ import { defineAuth } from '@fluixi/auth/server';
328
+
329
+ export type AppUser = { id: string; email: string; name?: string; role?: string };
330
+
331
+ // Better Auth owns the audited primitives; defineAuth registers it with @fluixi/auth.
332
+ export const auth = defineAuth<AppUser>(
333
+ betterAuth({
334
+ // database: <your adapter>,
335
+ emailAndPassword: { enabled: true },
336
+ // socialProviders: { google: { \u2026 }, github: { \u2026 } },
337
+ } as Parameters<typeof betterAuth>[0]),
338
+ );
339
+ `;
340
+ var betterAuthClient = () => `import { createAuthClient } from 'better-auth/client';
341
+ import { createAuthHooks } from '@fluixi/auth/client';
342
+ import type { AppUser } from './auth.config.js';
343
+
344
+ const client = createAuthClient({ baseURL: '/api/auth' });
345
+
346
+ // Or, to reuse an existing reactive session: createAuthHooks({ session: yourSessionStore }).
347
+ export const { useUser, useSession, useAuth, useSignIn, useSignOut, protectedRoute } =
348
+ createAuthHooks<AppUser>({ client, loginPath: '/login' });
349
+ `;
350
+ var betterAuthMiddleware = () => `import { defineMiddleware } from '@fluixi/start';
351
+ import { authMiddleware } from '@fluixi/auth/server';
352
+ import './auth.config.js';
353
+
354
+ export default defineMiddleware([authMiddleware()]);
355
+ `;
356
+ var betterAuthRoute = () => `import { mountAuthRoutes } from '@fluixi/auth/server';
357
+ import '../../auth.config.js';
358
+
359
+ const handler = mountAuthRoutes();
360
+ export const GET = handler;
361
+ export const POST = handler;
362
+ export default handler;
363
+ `;
364
+ var ScaffoldError = class extends Error {
38
365
  };
39
- const BAR = c.gray('│');
40
- // ── interactive prompt primitives (clack-style gutter) ──────────────────────
366
+ function importPath(from, to) {
367
+ const p = relative(dirname2(from), to).replace(/\\/g, "/").replace(/\.tsx?$/, ".js");
368
+ return p.startsWith(".") ? p : `./${p}`;
369
+ }
370
+ function writeOnce(log, file, content) {
371
+ if (existsSync2(file)) {
372
+ log.push({ kind: "kept", file });
373
+ return false;
374
+ }
375
+ mkdirSync2(dirname2(file), { recursive: true });
376
+ writeFileSync2(file, content);
377
+ log.push({ kind: "created", file });
378
+ return true;
379
+ }
380
+ var APP_HEADER = "// Registered by @fluixi/start ahead of both entries.\n";
381
+ var APP_SERVER_HEADER = "// Only the server build imports this file, so what it lists never reaches the browser.\n";
382
+ function registerModule(log, root, server, file, name, entry = name) {
383
+ const config = join(root, server ? "src/app.config.server.ts" : "src/app.config.ts");
384
+ register(log, config, server ? APP_SERVER_HEADER : APP_HEADER, {
385
+ importLine: `import { ${name} } from '${importPath(config, file)}';`,
386
+ entry
387
+ });
388
+ }
389
+ function ensureAuthEnv(log, root) {
390
+ const file = join(root, "src/config/env.ts");
391
+ if (writeOnce(log, file, authEnvConfig())) return;
392
+ let text = readFileSync2(file, "utf8");
393
+ if (/export\s+const\s+auth\b/.test(text)) return;
394
+ if (!/\bpublicEnv\b/.test(text)) text = addImport(text, `import { publicEnv } from '@fluixi/start/env';`);
395
+ text = addImport(text, `import { authFromEnv } from '@fluixi/oauth2/env';`);
396
+ writeFileSync2(file, `${text.replace(/\n*$/, "\n")}
397
+ ${AUTH_READER}`);
398
+ log.push({ kind: "updated", file, detail: "auth" });
399
+ }
400
+ function resolveTokens(provider, tokens) {
401
+ const refusal = SERVER_ONLY[provider];
402
+ if (refusal && tokens === "browser") throw new ScaffoldError(`${provider} needs server tokens: ${refusal}`);
403
+ return { tokens: tokens ?? (refusal ? "server" : "browser"), forced: !!refusal && !tokens };
404
+ }
405
+ function setupOAuth2(root, options, dependencySpec = "alpha") {
406
+ const provider = options.provider ?? "oidc";
407
+ if (!PROVIDERS.includes(provider)) throw new ScaffoldError(`unknown provider ${provider}: ${PROVIDERS.join(", ")}`);
408
+ const { tokens, forced } = resolveTokens(provider, options.tokens);
409
+ const html = options.format === "html";
410
+ const ext = html ? "ts" : "tsx";
411
+ const steps = [];
412
+ const at = (rel) => join(root, rel);
413
+ ensureAuthEnv(steps, root);
414
+ const service = at("src/services/auth.ts");
415
+ if (writeOnce(steps, service, authServiceFile(tokens))) registerModule(steps, root, false, service, "AuthModule");
416
+ if (tokens === "browser") writeOnce(steps, at(`src/routes/callback.${ext}`), callbackRoute(html));
417
+ writeOnce(steps, at(`src/routes/login.${ext}`), loginRoute(html));
418
+ if (tokens === "server") {
419
+ const server = at("src/services/auth.server.ts");
420
+ if (writeOnce(steps, server, authServerFile())) registerModule(steps, root, true, server, "authServer", "authServer()");
421
+ }
422
+ const vars = {
423
+ AUTH_PROVIDER: provider,
424
+ AUTH_CLIENT_ID: "my-app",
425
+ AUTH_TOKENS: tokens,
426
+ ...PROVIDER_VARS[provider],
427
+ APP_URL: "http://localhost:3000"
428
+ };
429
+ addEnvPublic(steps, at("fluixi.config.ts"), Object.keys(vars));
430
+ addEnvExample(steps, at(".env.example"), `@fluixi/oauth2 (${provider}). Listed in env.public: the browser sees them.`, vars);
431
+ if (tokens === "server") {
432
+ addEnvExample(steps, at(".env.example"), "Server only, never in env.public. SESSION_SECRET: 32 bytes or more.", {
433
+ OIDC_CLIENT_SECRET: "",
434
+ SESSION_SECRET: ""
435
+ });
436
+ }
437
+ const redirect = tokens === "browser" ? "/callback" : "/auth/callback";
438
+ return {
439
+ steps,
440
+ dependencies: { "@fluixi/oauth2": dependencySpec },
441
+ next: ["copy .env.example to .env and fill it in", `register <APP_URL>${redirect} as the redirect URI at the provider`],
442
+ notes: forced ? [`${provider} refuses a public client, so the tokens stay on the server`] : []
443
+ };
444
+ }
445
+ function setupBetterAuth(root, dependencySpec = "alpha") {
446
+ const steps = [];
447
+ const at = (rel) => join(root, rel);
448
+ writeOnce(steps, at("src/auth.config.ts"), betterAuthConfig());
449
+ writeOnce(steps, at("src/auth.client.ts"), betterAuthClient());
450
+ if (!writeOnce(steps, at("src/middleware.ts"), betterAuthMiddleware())) {
451
+ steps.push({
452
+ kind: "hint",
453
+ file: at("src/middleware.ts"),
454
+ lines: [`import { authMiddleware } from '@fluixi/auth/server';`, `import './auth.config.js';`, "authMiddleware() in the middleware list"]
455
+ });
456
+ }
457
+ writeOnce(steps, at("src/api/auth/[...all].ts"), betterAuthRoute());
458
+ return {
459
+ steps,
460
+ dependencies: { "@fluixi/auth": dependencySpec, "better-auth": "^1" },
461
+ next: ["set your database adapter in src/auth.config.ts"],
462
+ notes: []
463
+ };
464
+ }
465
+ var COLOR = env.NO_COLOR || env.FORCE_COLOR === "0" ? false : (!!output.isTTY || !!env.FORCE_COLOR) && env.TERM !== "dumb";
466
+ var sgr = (o, x) => (s) => COLOR ? `\x1B[${o}m${s}\x1B[${x}m` : `${s}`;
467
+ var c = { bold: sgr(1, 22), green: sgr(32, 39), cyan: sgr(36, 39), gray: sgr(90, 39) };
468
+ var BAR = c.gray("\u2502");
41
469
  async function askText(label, fallback) {
42
- output.write(`${c.green('◇')} ${c.bold(label)} ${c.gray(`(${fallback})`)}\n`);
43
- const rl = createInterface({ input, output });
44
- const answer = (await rl.question(`${BAR} `)).trim();
45
- rl.close();
46
- output.write(`${BAR}\n`);
47
- return answer || fallback;
470
+ output.write(`${c.green("\u25C7")} ${c.bold(label)} ${c.gray(`(${fallback})`)}
471
+ `);
472
+ const rl = createInterface({ input, output });
473
+ const answer = (await rl.question(`${BAR} `)).trim();
474
+ rl.close();
475
+ output.write(`${BAR}
476
+ `);
477
+ return answer || fallback;
48
478
  }
49
479
  function askSelect(label, choices) {
50
- return new Promise((done) => {
51
- let idx = 0;
52
- output.write(`${c.green('◆')} ${c.bold(label)}\n`);
53
- const draw = (first) => {
54
- if (!first)
55
- output.write(`\x1b[${choices.length}A`);
56
- for (let i = 0; i < choices.length; i++) {
57
- const on = i === idx;
58
- const dot = on ? c.green('●') : c.gray('○');
59
- const name = on ? c.cyan(c.bold(choices[i].label)) : choices[i].label;
60
- output.write(`\x1b[2K${BAR} ${dot} ${name} ${c.gray(choices[i].hint)}\n`);
61
- }
62
- };
63
- draw(true);
64
- emitKeypressEvents(input);
65
- if (input.isTTY)
66
- input.setRawMode(true);
67
- const onKey = (_s, k) => {
68
- if (k.name === 'up' || k.name === 'k') {
69
- idx = (idx - 1 + choices.length) % choices.length;
70
- draw(false);
71
- }
72
- else if (k.name === 'down' || k.name === 'j') {
73
- idx = (idx + 1) % choices.length;
74
- draw(false);
75
- }
76
- // Both names. A terminal sends `\r` and readline calls that `return`; a pty or a
77
- // piped answer sends `\n`, which it calls `enter`. Accepting only the first left
78
- // the prompt waiting for a key that never came.
79
- else if (k.name === 'return' || k.name === 'enter') {
80
- finish();
81
- done(choices[idx].value);
82
- }
83
- else if (k.name === 'c' && k.ctrl) {
84
- finish();
85
- output.write('\n');
86
- exit(1);
87
- }
88
- };
89
- // Enter on a closed stream still means "take what is highlighted". Without this a
90
- // piped answer (`printf 'app\n\n\n' | create-fluixi`) drew the list and stopped.
91
- const onEnd = () => { finish(); done(choices[idx].value); };
92
- const finish = () => {
93
- input.off('keypress', onKey);
94
- input.off('end', onEnd);
95
- input.off('close', onEnd);
96
- if (input.isTTY)
97
- input.setRawMode(false);
98
- // Pause it again or the live stdin handle keeps the event loop alive and the CLI
99
- // never exits.
100
- input.pause();
101
- output.write(`${BAR}\n`);
102
- };
103
- // Already at EOF, so no event is coming: a fully buffered answer
104
- // (`printf 'app\n\n\n' | create-fluixi`) is consumed by the name prompt and the
105
- // stream ends before this one is set up. Take the highlighted value now.
106
- if (input.readableEnded) {
107
- finish();
108
- done(choices[idx].value);
109
- return;
110
- }
111
- input.on('keypress', onKey);
112
- input.on('end', onEnd);
113
- input.on('close', onEnd);
114
- // The reason this prompt used to go nowhere. `askText` closes its readline
115
- // interface, which leaves stdin paused, and `emitKeypressEvents` only wires the
116
- // stream up the first time it is called. Attaching a listener to a paused stream
117
- // reads nothing, so no key ever arrived: the list drew with the first option
118
- // highlighted, the event loop drained, and the process exited 0 having created
119
- // nothing.
120
- input.resume();
121
- });
480
+ return new Promise((done) => {
481
+ let idx = 0;
482
+ output.write(`${c.green("\u25C6")} ${c.bold(label)}
483
+ `);
484
+ const draw = (first) => {
485
+ if (!first) output.write(`\x1B[${choices.length}A`);
486
+ for (let i = 0; i < choices.length; i++) {
487
+ const on = i === idx;
488
+ const dot = on ? c.green("\u25CF") : c.gray("\u25CB");
489
+ const name = on ? c.cyan(c.bold(choices[i].label)) : choices[i].label;
490
+ output.write(`\x1B[2K${BAR} ${dot} ${name} ${c.gray(choices[i].hint)}
491
+ `);
492
+ }
493
+ };
494
+ draw(true);
495
+ emitKeypressEvents(input);
496
+ if (input.isTTY) input.setRawMode(true);
497
+ const onKey = (_s, k) => {
498
+ if (k.name === "up" || k.name === "k") {
499
+ idx = (idx - 1 + choices.length) % choices.length;
500
+ draw(false);
501
+ } else if (k.name === "down" || k.name === "j") {
502
+ idx = (idx + 1) % choices.length;
503
+ draw(false);
504
+ } else if (k.name === "return" || k.name === "enter") {
505
+ finish();
506
+ done(choices[idx].value);
507
+ } else if (k.name === "c" && k.ctrl) {
508
+ finish();
509
+ output.write("\n");
510
+ exit(1);
511
+ }
512
+ };
513
+ const onEnd = () => {
514
+ finish();
515
+ done(choices[idx].value);
516
+ };
517
+ const finish = () => {
518
+ input.off("keypress", onKey);
519
+ input.off("end", onEnd);
520
+ input.off("close", onEnd);
521
+ if (input.isTTY) input.setRawMode(false);
522
+ input.pause();
523
+ output.write(`${BAR}
524
+ `);
525
+ };
526
+ if (input.readableEnded) {
527
+ finish();
528
+ done(choices[idx].value);
529
+ return;
530
+ }
531
+ input.on("keypress", onKey);
532
+ input.on("end", onEnd);
533
+ input.on("close", onEnd);
534
+ input.resume();
535
+ });
122
536
  }
123
- /**
124
- * What every @fluixi-ui app needs, and nothing more.
125
- *
126
- * The base layer: tokens and theme, the primitives and the behaviour they share, the
127
- * layout and animation helpers. No component package is here on purpose, an app installs
128
- * the ones it uses, and the resolver turns `<Button />` into an import from whichever it
129
- * installed.
130
- */
131
- const UI_DEPS = {
132
- '@fluixi-ui/fx': 'alpha',
133
- '@fluixi-ui/interactions': 'alpha',
134
- '@fluixi-ui/kit': 'alpha',
135
- '@fluixi-ui/layout': 'alpha',
136
- '@fluixi-ui/polymorphic': 'alpha',
137
- '@fluixi-ui/primitives': 'alpha',
138
- '@fluixi-ui/theme': 'alpha',
139
- '@fluixi-ui/tokens': 'alpha',
537
+
538
+ // src/index.ts
539
+ import { stdin as input2, stdout as output2, stderr, argv, exit as exit2, env as env2 } from "node:process";
540
+ var here = (p) => fileURLToPath(new URL(p, import.meta.url));
541
+ var COLOR2 = env2.NO_COLOR || env2.FORCE_COLOR === "0" ? false : (!!output2.isTTY || !!env2.FORCE_COLOR) && env2.TERM !== "dumb";
542
+ var sgr2 = (o, x) => (s) => COLOR2 ? `\x1B[${o}m${s}\x1B[${x}m` : `${s}`;
543
+ var c2 = {
544
+ bold: sgr2(1, 22),
545
+ dim: sgr2(2, 22),
546
+ green: sgr2(32, 39),
547
+ yellow: sgr2(33, 39),
548
+ cyan: sgr2(36, 39),
549
+ gray: sgr2(90, 39),
550
+ red: sgr2(31, 39)
551
+ };
552
+ var rgb = (r, g, b) => (s) => COLOR2 ? `\x1B[38;2;${r};${g};${b}m${s}\x1B[39m` : s;
553
+ var BRAND = [
554
+ [34, 211, 238],
555
+ [56, 189, 248],
556
+ [129, 140, 248],
557
+ [167, 139, 250],
558
+ [192, 132, 252]
559
+ ];
560
+ var gradient = (text) => {
561
+ if (!COLOR2) return text;
562
+ const ch = [...text];
563
+ return ch.map((x, i) => {
564
+ const [r, g, b] = BRAND[Math.min(BRAND.length - 1, Math.floor(i / Math.max(1, ch.length - 1) * (BRAND.length - 1)))];
565
+ return rgb(r, g, b)(x);
566
+ }).join("");
140
567
  };
141
- /** Build-time only: it runs in the config, not in the app. */
142
- const UI_DEV_DEPS = { '@fluixi-ui/resolver': 'alpha' };
143
- /**
144
- * What `fluixi.d.ts` holds until the compiler regenerates it.
145
- *
146
- * Only the intrinsics: the component globals depend on which packages are installed and
147
- * on the resolver rules, so listing them here would go stale the moment a component is
148
- * added. The compiler rewrites the whole file on the first dev run.
149
- */
150
- const INTRINSICS_DTS = `// GENERATED by @fluixi/compiler, do not edit.
568
+ var BAR2 = c2.gray("\u2502");
569
+ var UI_DEPS = {
570
+ "@fluixi-ui/fx": "alpha",
571
+ "@fluixi-ui/interactions": "alpha",
572
+ "@fluixi-ui/kit": "alpha",
573
+ "@fluixi-ui/layout": "alpha",
574
+ "@fluixi-ui/polymorphic": "alpha",
575
+ "@fluixi-ui/primitives": "alpha",
576
+ "@fluixi-ui/theme": "alpha",
577
+ "@fluixi-ui/tokens": "alpha"
578
+ };
579
+ var UI_DEV_DEPS = { "@fluixi-ui/resolver": "alpha" };
580
+ var INTRINSICS_DTS = `// GENERATED by @fluixi/compiler, do not edit.
151
581
  //
152
582
  // The reactive intrinsics, which the compiler lowers to their \`create*\` calls. They
153
583
  // need no import. This file is rewritten on the first \`fluixi dev\`, which adds the
@@ -167,239 +597,243 @@ declare global {
167
597
  const $untrackStore: typeof __fluixi_reactive_store.untrackStore;
168
598
  }
169
599
  `;
170
- /**
171
- * The cascade-layer order, declared before anything defines a layer.
172
- *
173
- * A layer ranks by where it is FIRST declared, and one nobody declared is appended last,
174
- * which makes it the strongest. That default is wrong twice over here. The fluixi-css
175
- * reset defines `flx.base`, which @fluixi-ui's own sheets do not declare, so the reset
176
- * would outrank the components it is meant to sit under, and an app's plain
177
- * `button { ... }` reset would outrank them too.
178
- *
179
- * Declaring the order up front fixes both: the app's element resets sit lowest, then the
180
- * engine's preflight, then the component layers. An app's own `@layer base` and
181
- * `@layer components` are deliberately absent, so they stay unregistered and keep
182
- * winning, which is what an app expects of its own classes.
183
- */
184
- const LAYERS_CSS = `/* Cascade-layer order. Imported before any component CSS, because a layer ranks by
600
+ var LAYERS_CSS = `/* Cascade-layer order. Imported before any component CSS, because a layer ranks by
185
601
  where it is first declared and an undeclared one would rank last, above everything.
186
602
  Add this app's own layers only if you want them to rank BELOW the component styles. */
187
603
  @layer app-reset, flx.reset, flx.base, flx.tokens, flx.components, flx.skin;
188
604
  `;
189
- /** Add to a package.json section without dropping what the template already had. */
605
+ var option = (args, name) => {
606
+ const i = args.indexOf(`--${name}`);
607
+ if (i !== -1 && args[i + 1] && !args[i + 1].startsWith("-")) return args[i + 1];
608
+ return args.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3);
609
+ };
610
+ var PROVIDER_HINTS = {
611
+ oidc: "any provider with a discovery document",
612
+ keycloak: "realm on a Keycloak server",
613
+ auth0: "tenant domain",
614
+ okta: "org domain",
615
+ google: "server tokens only",
616
+ dex: "server tokens only",
617
+ oauth2: "no discovery \xB7 endpoints by hand"
618
+ };
190
619
  function addDeps(pkg, section, deps) {
191
- pkg[section] = Object.fromEntries(Object.entries({ ...(pkg[section] ?? {}), ...deps }).sort(([a], [b]) => a.localeCompare(b)));
620
+ pkg[section] = Object.fromEntries(
621
+ Object.entries({ ...pkg[section] ?? {}, ...deps }).sort(([a], [b]) => a.localeCompare(b))
622
+ );
192
623
  }
193
- /**
194
- * The app's own stylesheet, in the shape the chosen css engine expects.
195
- *
196
- * The component tokens are not here: they are a stylesheet the package ships and the
197
- * entry imports directly, so this file only holds what the engine has to read, the dark
198
- * variant, where to scan, and the theme the app defines.
199
- */
200
624
  function styleSheet(ui, css) {
201
- // Dark from the attribute @fluixi/core's createTheme sets, not the OS preference, so
202
- // a theme toggle in the app actually drives it.
203
- const darkVariant = `@custom-variant dark (&:where([data-theme='dark'], [data-theme='dark'] *));`;
204
- // Where to look for utility classes. Relative to this file.
205
- const sources = `@source '.';\n@source '../index.html';`;
206
- const theme = `@theme {\n /* Design tokens. A --color-* scale here drives the whole app. */\n}`;
207
- if (css === 'fluixi-css') {
208
- // The layers are pulled in by directive rather than by import, and they come last:
209
- // `@theme` above has to be read before `utilities` is generated from it.
210
- return [
211
- darkVariant,
212
- '',
213
- sources,
214
- '',
215
- theme,
216
- '',
217
- '@fluixi base;',
218
- '@fluixi utilities;',
219
- '@fluixi components;',
220
- '',
221
- ].join('\n');
222
- }
223
- if (css === 'tailwind') {
224
- return [`@import 'tailwindcss';`, '', darkVariant, '', theme, ''].join('\n');
225
- }
226
- // No css engine: the component tokens are imported from the entry like any other
227
- // stylesheet, so there is nothing for this file to hold.
228
- return '';
625
+ const darkVariant = `@custom-variant dark (&:where([data-theme='dark'], [data-theme='dark'] *));`;
626
+ const sources = `@source '.';
627
+ @source '../index.html';`;
628
+ const theme = `@theme {
629
+ /* Design tokens. A --color-* scale here drives the whole app. */
630
+ }`;
631
+ if (css === "fluixi-css") {
632
+ return [
633
+ darkVariant,
634
+ "",
635
+ sources,
636
+ "",
637
+ theme,
638
+ "",
639
+ "@fluixi base;",
640
+ "@fluixi utilities;",
641
+ "@fluixi components;",
642
+ ""
643
+ ].join("\n");
644
+ }
645
+ if (css === "tailwind") {
646
+ return [`@import 'tailwindcss';`, "", darkVariant, "", theme, ""].join("\n");
647
+ }
648
+ return "";
229
649
  }
230
- /** Where the component resolver is configured, which differs by mode. */
231
- const configFor = (mode) => mode === 'ssr' ? 'fluixi.config.ts' : 'vite.config.ts';
232
- /**
233
- * Let a capitalised tag resolve to a @fluixi-ui package.
234
- *
235
- * Added alongside the rule the template ships rather than replacing it, so a local
236
- * `src/components/Card.tsx` still wins and only the names it does not define fall
237
- * through to the kit.
238
- */
650
+ var configFor = (mode) => mode === "ssr" ? "fluixi.config.ts" : "vite.config.ts";
239
651
  function addUiResolver(target, mode) {
240
- const file = join(target, configFor(mode));
241
- if (!existsSync(file))
242
- return;
243
- let src = readFileSync(file, 'utf8');
244
- src = `import { uiComponents } from '@fluixi-ui/resolver';\n` + src;
245
- src = src.replace("resolve: [{ match: /^([A-Z]\\w+)$/, module: '/src/components/$1.tsx' }]", "resolve: [{ match: /^([A-Z]\\w+)$/, module: '/src/components/$1.tsx' }, uiComponents()]");
246
- writeFileSync(file, src);
652
+ const file = join2(target, configFor(mode));
653
+ if (!existsSync3(file)) return;
654
+ let src = readFileSync3(file, "utf8");
655
+ src = `import { uiComponents } from '@fluixi-ui/resolver';
656
+ ` + src;
657
+ src = src.replace(
658
+ "resolve: [{ match: /^([A-Z]\\w+)$/, module: '/src/components/$1.tsx' }]",
659
+ "resolve: [{ match: /^([A-Z]\\w+)$/, module: '/src/components/$1.tsx' }, uiComponents()]"
660
+ );
661
+ writeFileSync3(file, src);
247
662
  }
248
- /**
249
- * Put a plugin in the app's vite config.
250
- *
251
- * An SSR app has none by default, because @fluixi/start owns the build. It still reads
252
- * one when it is there, so a css engine that ships a vite plugin gets a file created for
253
- * it rather than having nowhere to go.
254
- */
255
663
  function addVitePlugin(target, mode, importLine, call) {
256
- // A start app declares extra plugins in its own config; it has no vite config, and
257
- // adding one just to hold a plugin would leave the project with two build configs
258
- // that have to agree.
259
- const file = join(target, configFor(mode));
260
- if (!existsSync(file))
261
- return;
262
- let src = importLine + '\n' + readFileSync(file, 'utf8');
263
- src =
264
- mode === 'ssr'
265
- ? src.replace('export default defineConfig({', `export default defineConfig({\n plugins: [${call}],`)
266
- : src.replace('plugins: [', `plugins: [\n ${call},`);
267
- writeFileSync(file, src);
664
+ const file = join2(target, configFor(mode));
665
+ if (!existsSync3(file)) return;
666
+ let src = importLine + "\n" + readFileSync3(file, "utf8");
667
+ src = mode === "ssr" ? src.replace("export default defineConfig({", `export default defineConfig({
668
+ plugins: [${call}],`) : src.replace("plugins: [", `plugins: [
669
+ ${call},`);
670
+ writeFileSync3(file, src);
268
671
  }
269
- /**
270
- * Import the stylesheets from whichever file boots the client.
271
- *
272
- * The component tokens come first and from the entry rather than from `styles.css`:
273
- * they are a stylesheet the package ships, not something the app's css engine should be
274
- * asked to resolve, and the components below need them defined before their own rules
275
- * land. `emitUiTokens` does not replace this, that bridge covers a subset.
276
- */
277
672
  function importStyles(target, mode, ui, css) {
278
- const base = mode === 'ssr' ? 'entry-client' : 'main';
279
- const file = ['tsx', 'ts']
280
- .map((ext) => join(target, 'src', `${base}.${ext}`))
281
- .find((p) => existsSync(p));
282
- if (!file)
283
- return;
284
- const head = [
285
- // First, before anything that defines a layer.
286
- ...(css === 'fluixi-css' ? [`import './layers.css';`] : []),
287
- ...(ui === 'fluixi-ui' ? [`import '@fluixi-ui/tokens/tokens.css';`] : []),
288
- `import './styles.css';`,
289
- '',
290
- ].join('\n');
291
- writeFileSync(file, head + readFileSync(file, 'utf8'));
673
+ const base = mode === "ssr" ? "entry-client" : "main";
674
+ const file = ["tsx", "ts"].map((ext) => join2(target, "src", `${base}.${ext}`)).find((p) => existsSync3(p));
675
+ if (!file) return;
676
+ const head = [
677
+ // First, before anything that defines a layer.
678
+ ...css === "fluixi-css" ? [`import './layers.css';`] : [],
679
+ ...ui === "fluixi-ui" ? [`import '@fluixi-ui/tokens/tokens.css';`] : [],
680
+ `import './styles.css';`,
681
+ ""
682
+ ].join("\n");
683
+ writeFileSync3(file, head + readFileSync3(file, "utf8"));
292
684
  }
293
685
  async function main() {
294
- const args = argv.slice(2);
295
- let dir = args.find((a) => !a.startsWith('-'));
296
- let mode = args.includes('--spa') ? 'spa' : args.includes('--ssr') ? 'ssr' : undefined;
297
- let format = args.includes('--html') ? 'html' : args.includes('--jsx') ? 'jsx' : undefined;
298
- let ui = args.includes('--ui') ? 'fluixi-ui' : args.includes('--no-ui') ? 'none' : undefined;
299
- let css = args.includes('--tailwind') ? 'tailwind'
300
- : args.includes('--fluixi-css') ? 'fluixi-css'
301
- : args.includes('--no-css') ? 'none'
302
- : undefined;
303
- const interactive = input.isTTY && (!dir || !mode || !format || !ui || !css);
304
- if (interactive) {
305
- output.write(`\n${c.gray('┌')} ${gradient('◆')} ${c.bold(gradient('create-fluixi'))}\n${BAR}\n`);
306
- if (!dir)
307
- dir = await askText('Project name', 'fluixi-app');
308
- if (!mode) {
309
- mode = (await askSelect('App mode', [
310
- { value: 'ssr', label: 'SSR', hint: 'server-rendered · @fluixi/start' },
311
- { value: 'spa', label: 'SPA', hint: 'client-only · vite' },
312
- ]));
313
- }
314
- if (!format) {
315
- format = (await askSelect('Template syntax', [
316
- { value: 'jsx', label: 'JSX', hint: 'default · .tsx · html`` works inline too' },
317
- { value: 'html', label: 'html``', hint: 'no JSX · plain .ts · @fluixi/ts-plugin' },
318
- ]));
319
- }
320
- if (!ui) {
321
- ui = (await askSelect('Component library', [
322
- { value: 'none', label: 'None', hint: 'bring your own components' },
323
- { value: 'fluixi-ui', label: '@fluixi-ui', hint: 'kit + tokens · install components as you need them' },
324
- ]));
325
- }
326
- if (!css) {
327
- css = (await askSelect('Styling', [
328
- { value: 'none', label: 'None', hint: 'plain css' },
329
- { value: 'tailwind', label: 'Tailwind CSS', hint: 'v4 · via @tailwindcss/vite' },
330
- { value: 'fluixi-css', label: '@fluixi-css', hint: 'the Fluixi stylesheet' },
331
- ]));
332
- }
686
+ const args = argv.slice(2);
687
+ let dir = args.find((a) => !a.startsWith("-"));
688
+ let mode = args.includes("--spa") ? "spa" : args.includes("--ssr") ? "ssr" : void 0;
689
+ let format = args.includes("--html") ? "html" : args.includes("--jsx") ? "jsx" : void 0;
690
+ let ui = args.includes("--ui") ? "fluixi-ui" : args.includes("--no-ui") ? "none" : void 0;
691
+ let css = args.includes("--tailwind") ? "tailwind" : args.includes("--fluixi-css") ? "fluixi-css" : args.includes("--no-css") ? "none" : void 0;
692
+ let auth = args.includes("--no-auth") ? "none" : option(args, "auth");
693
+ let provider = option(args, "provider");
694
+ let tokens = option(args, "tokens");
695
+ const refuse = (message) => {
696
+ stderr.write(`${c2.red("\u2717")} ${message}
697
+ `);
698
+ exit2(1);
699
+ };
700
+ if (auth && !["none", "oauth2", "better-auth"].includes(auth)) refuse(`--auth is oauth2, better-auth or none`);
701
+ if (provider && !PROVIDERS.includes(provider)) refuse(`--provider is one of ${PROVIDERS.join(", ")}`);
702
+ if (tokens && tokens !== "browser" && tokens !== "server") refuse(`--tokens is browser or server`);
703
+ if (mode === "spa" && auth && auth !== "none") refuse(`authentication needs an SSR app: drop --spa or --auth`);
704
+ const interactive = input2.isTTY && (!dir || !mode || !format || !ui || !css || mode !== "spa" && !auth);
705
+ if (interactive) {
706
+ output2.write(`
707
+ ${c2.gray("\u250C")} ${gradient("\u25C6")} ${c2.bold(gradient("create-fluixi"))}
708
+ ${BAR2}
709
+ `);
710
+ if (!dir) dir = await askText("Project name", "fluixi-app");
711
+ if (!mode) {
712
+ mode = await askSelect("App mode", [
713
+ { value: "ssr", label: "SSR", hint: "server-rendered \xB7 @fluixi/start" },
714
+ { value: "spa", label: "SPA", hint: "client-only \xB7 vite" }
715
+ ]);
333
716
  }
334
- dir = dir ?? 'fluixi-app';
335
- mode = mode ?? 'ssr';
336
- format = format ?? 'jsx';
337
- ui = ui ?? 'none';
338
- css = css ?? 'none';
339
- const target = resolve(dir);
340
- const name = basename(target);
341
- if (existsSync(target)) {
342
- output.write(`${c.gray('└')} ${c.red('✗')} "${c.bold(name)}" already exists — pick another name or remove it.\n\n`);
343
- exit(1);
717
+ if (!format) {
718
+ format = await askSelect("Template syntax", [
719
+ { value: "jsx", label: "JSX", hint: "default \xB7 .tsx \xB7 html`` works inline too" },
720
+ { value: "html", label: "html``", hint: "no JSX \xB7 plain .ts \xB7 @fluixi/ts-plugin" }
721
+ ]);
344
722
  }
345
- const template = `../template-${mode}${format === 'html' ? '-html' : ''}`;
346
- cpSync(here(template), target, { recursive: true });
347
- // npm strips a real .gitignore from published packages → restore it from _gitignore.
348
- const gi = join(target, '_gitignore');
349
- if (existsSync(gi))
350
- renameSync(gi, join(target, '.gitignore'));
351
- // The ambient declarations for the `$` intrinsics.
352
- //
353
- // The compiler rewrites this file on the first `fluixi dev`, adding whatever the
354
- // resolver supplies without an import. Shipping it now means an editor knows what
355
- // `$signal` is before the app has ever been run, instead of reporting "Cannot find
356
- // name" across a project that compiles.
357
- writeFileSync(join(target, 'fluixi.d.ts'), INTRINSICS_DTS);
358
- const pkgPath = join(target, 'package.json');
359
- const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
360
- pkg.name = name;
361
- if (ui === 'fluixi-ui') {
362
- addDeps(pkg, 'dependencies', UI_DEPS);
363
- addDeps(pkg, 'devDependencies', UI_DEV_DEPS);
364
- addUiResolver(target, mode);
723
+ if (!ui) {
724
+ ui = await askSelect("Component library", [
725
+ { value: "none", label: "None", hint: "bring your own components" },
726
+ { value: "fluixi-ui", label: "@fluixi-ui", hint: "kit + tokens \xB7 install components as you need them" }
727
+ ]);
365
728
  }
366
- if (css === 'tailwind') {
367
- addDeps(pkg, 'devDependencies', { tailwindcss: '^4', '@tailwindcss/vite': '^4' });
368
- addVitePlugin(target, mode, `import tailwindcss from '@tailwindcss/vite';`, 'tailwindcss()');
729
+ if (!css) {
730
+ css = await askSelect("Styling", [
731
+ { value: "none", label: "None", hint: "plain css" },
732
+ { value: "tailwind", label: "Tailwind CSS", hint: "v4 \xB7 via @tailwindcss/vite" },
733
+ { value: "fluixi-css", label: "@fluixi-css", hint: "the Fluixi stylesheet" }
734
+ ]);
369
735
  }
370
- if (css === 'fluixi-css') {
371
- addDeps(pkg, 'dependencies', { '@fluixi-css/core': 'next' });
372
- addDeps(pkg, 'devDependencies', { '@fluixi-css/vite': 'next', lightningcss: '^1.29.3' });
373
- addVitePlugin(target, mode, `import fluixiCss from '@fluixi-css/vite';`,
374
- // The bridge only matters with the component kit installed: it maps the theme
375
- // scales onto the `--flx-ui-*` custom properties those components read.
376
- `fluixiCss({ reset: true${ui === 'fluixi-ui' ? ', emitUiTokens: true' : ''} })`);
377
- // No `fluixi.css.config.js`: `@theme`, `@source` and `@custom-variant` in the
378
- // stylesheet say the same things, and a project with both has two places to change
379
- // one colour. The config file is still read when an app adds one.
736
+ if (mode === "ssr" && !auth) {
737
+ auth = await askSelect("Authentication", [
738
+ { value: "none", label: "None", hint: "add it later with fluixi add auth" },
739
+ { value: "oauth2", label: "OAuth2 / OIDC", hint: "@fluixi/oauth2 \xB7 Keycloak, Auth0, Okta, Google\u2026" },
740
+ { value: "better-auth", label: "Better Auth", hint: "@fluixi/auth \xB7 your own user table" }
741
+ ]);
380
742
  }
381
- if (ui === 'fluixi-ui' || css !== 'none') {
382
- // Only for fluixi-css: it is the engine that defines `flx.base`, and without a
383
- // declared order that layer lands above the components it belongs under.
384
- if (css === 'fluixi-css')
385
- writeFileSync(join(target, 'src', 'layers.css'), LAYERS_CSS);
386
- const sheet = styleSheet(ui, css);
387
- // An empty sheet still gets written: it is where an app puts its own css, and the
388
- // entry already imports it.
389
- writeFileSync(join(target, 'src', 'styles.css'), sheet);
390
- importStyles(target, mode, ui, css);
743
+ if (auth === "oauth2" && !provider) {
744
+ provider = await askSelect(
745
+ "Identity provider",
746
+ PROVIDERS.map((p) => ({ value: p, label: p, hint: PROVIDER_HINTS[p] }))
747
+ );
391
748
  }
392
- writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
393
- // Outro + next steps. The leading gutter only makes sense after the intro/prompts.
394
- const tag = `${c.cyan(mode.toUpperCase())} ${c.gray('·')} ${c.cyan(format === 'html' ? 'html``' : 'JSX')}`;
395
- if (interactive)
396
- output.write(`${BAR}\n`);
397
- else
398
- output.write('\n');
399
- output.write(`${c.green('◇')} ${c.green('Created')} ${c.bold(name)} ${c.gray('·')} ${tag}\n${c.gray('└')}\n\n`);
400
- output.write(` ${c.bold('Next')}\n`);
401
- output.write(` ${c.gray('›')} cd ${dir}\n`);
402
- output.write(` ${c.gray('›')} ${c.cyan('pnpm install')} ${c.gray('# or npm / yarn')}\n`);
403
- output.write(` ${c.gray('›')} ${c.cyan('pnpm dev')}\n\n`);
749
+ if (auth === "oauth2" && !tokens && !SERVER_ONLY[provider ?? "oidc"]) {
750
+ tokens = await askSelect("Where the tokens live", [
751
+ { value: "browser", label: "Browser", hint: "public client \xB7 PKCE" },
752
+ { value: "server", label: "Server", hint: "httpOnly cookie \xB7 client secret" }
753
+ ]);
754
+ }
755
+ }
756
+ dir = dir ?? "fluixi-app";
757
+ mode = mode ?? "ssr";
758
+ format = format ?? "jsx";
759
+ ui = ui ?? "none";
760
+ css = css ?? "none";
761
+ auth = mode === "spa" ? "none" : auth ?? "none";
762
+ const target = resolve(dir);
763
+ const name = basename(target);
764
+ if (existsSync3(target)) {
765
+ output2.write(`${c2.gray("\u2514")} ${c2.red("\u2717")} "${c2.bold(name)}" already exists \u2014 pick another name or remove it.
766
+
767
+ `);
768
+ exit2(1);
769
+ }
770
+ const template = `../template-${mode}${format === "html" ? "-html" : ""}`;
771
+ cpSync(here(template), target, { recursive: true });
772
+ const gi = join2(target, "_gitignore");
773
+ if (existsSync3(gi)) renameSync(gi, join2(target, ".gitignore"));
774
+ writeFileSync3(join2(target, "fluixi.d.ts"), INTRINSICS_DTS);
775
+ const pkgPath = join2(target, "package.json");
776
+ const pkg = JSON.parse(readFileSync3(pkgPath, "utf8"));
777
+ pkg.name = name;
778
+ if (ui === "fluixi-ui") {
779
+ addDeps(pkg, "dependencies", UI_DEPS);
780
+ addDeps(pkg, "devDependencies", UI_DEV_DEPS);
781
+ addUiResolver(target, mode);
782
+ }
783
+ if (css === "tailwind") {
784
+ addDeps(pkg, "devDependencies", { tailwindcss: "^4", "@tailwindcss/vite": "^4" });
785
+ addVitePlugin(target, mode, `import tailwindcss from '@tailwindcss/vite';`, "tailwindcss()");
786
+ }
787
+ if (css === "fluixi-css") {
788
+ addDeps(pkg, "dependencies", { "@fluixi-css/core": "next" });
789
+ addDeps(pkg, "devDependencies", { "@fluixi-css/vite": "next", lightningcss: "^1.29.3" });
790
+ addVitePlugin(
791
+ target,
792
+ mode,
793
+ `import fluixiCss from '@fluixi-css/vite';`,
794
+ // The bridge only matters with the component kit installed: it maps the theme
795
+ // scales onto the `--flx-ui-*` custom properties those components read.
796
+ `fluixiCss({ reset: true${ui === "fluixi-ui" ? ", emitUiTokens: true" : ""} })`
797
+ );
798
+ }
799
+ if (ui === "fluixi-ui" || css !== "none") {
800
+ if (css === "fluixi-css") writeFileSync3(join2(target, "src", "layers.css"), LAYERS_CSS);
801
+ const sheet = styleSheet(ui, css);
802
+ writeFileSync3(join2(target, "src", "styles.css"), sheet);
803
+ importStyles(target, mode, ui, css);
804
+ }
805
+ let authResult;
806
+ try {
807
+ if (auth === "oauth2") authResult = setupOAuth2(target, { provider, tokens, format });
808
+ else if (auth === "better-auth") authResult = setupBetterAuth(target);
809
+ } catch (error) {
810
+ if (error instanceof ScaffoldError) refuse(error.message);
811
+ throw error;
812
+ }
813
+ if (authResult) addDeps(pkg, "dependencies", authResult.dependencies);
814
+ writeFileSync3(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
815
+ const authTag = auth === "oauth2" ? `OAuth2 ${provider ?? "oidc"}` : auth === "better-auth" ? "Better Auth" : "";
816
+ const tag = `${c2.cyan(mode.toUpperCase())} ${c2.gray("\xB7")} ${c2.cyan(format === "html" ? "html``" : "JSX")}` + (authTag ? ` ${c2.gray("\xB7")} ${c2.cyan(authTag)}` : "");
817
+ if (interactive) output2.write(`${BAR2}
818
+ `);
819
+ else output2.write("\n");
820
+ output2.write(`${c2.green("\u25C7")} ${c2.green("Created")} ${c2.bold(name)} ${c2.gray("\xB7")} ${tag}
821
+ ${c2.gray("\u2514")}
822
+
823
+ `);
824
+ output2.write(` ${c2.bold("Next")}
825
+ `);
826
+ output2.write(` ${c2.gray("\u203A")} cd ${dir}
827
+ `);
828
+ output2.write(` ${c2.gray("\u203A")} ${c2.cyan("pnpm install")} ${c2.gray("# or npm / yarn")}
829
+ `);
830
+ for (const step of authResult?.next ?? []) output2.write(` ${c2.gray("\u203A")} ${step}
831
+ `);
832
+ output2.write(` ${c2.gray("\u203A")} ${c2.cyan("pnpm dev")}
833
+
834
+ `);
835
+ for (const note of authResult?.notes ?? []) output2.write(` ${c2.gray(note)}
836
+
837
+ `);
404
838
  }
405
839
  main();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-fluixi",
3
- "version": "0.1.0-alpha.12",
3
+ "version": "0.1.0-alpha.13",
4
4
  "license": "MIT",
5
5
  "author": "Ibrahima Touré",
6
6
  "description": "Scaffold a new Fluixi app — `npm create fluixi <dir>`.",
@@ -26,7 +26,22 @@
26
26
  "url": "https://github.com/fluixi/core.git",
27
27
  "directory": "packages/create"
28
28
  },
29
+ "devDependencies": {
30
+ "esbuild": "^0.24.0",
31
+ "vitest": "^1.6.1",
32
+ "@fluixi/cli": "0.1.0-alpha.83"
33
+ },
34
+ "nx": {
35
+ "targets": {
36
+ "test": {
37
+ "dependsOn": [
38
+ "build"
39
+ ]
40
+ }
41
+ }
42
+ },
29
43
  "scripts": {
30
- "build": "tsc -p tsconfig.lib.json"
44
+ "build": "tsc -p tsconfig.lib.json && esbuild src/index.ts --bundle --platform=node --format=esm --target=node18 --outfile=dist/index.js",
45
+ "test": "vitest run"
31
46
  }
32
47
  }
@@ -17,6 +17,7 @@
17
17
  "devDependencies": {
18
18
  "@fluixi/ts-plugin": "alpha",
19
19
  "@fluixi/vite-plugin": "alpha",
20
+ "typescript": "^5.9.0",
20
21
  "vite": "^5.0.0"
21
22
  }
22
23
  }
@@ -16,6 +16,7 @@
16
16
  "devDependencies": {
17
17
  "@fluixi/ts-plugin": "alpha",
18
18
  "@fluixi/vite-plugin": "alpha",
19
+ "typescript": "^5.9.0",
19
20
  "vite": "^5.0.0"
20
21
  }
21
22
  }
@@ -20,6 +20,7 @@
20
20
  "devDependencies": {
21
21
  "@fluixi/ts-plugin": "alpha",
22
22
  "@types/node": "^20.0.0",
23
+ "typescript": "^5.9.0",
23
24
  "vite": "^5.0.0"
24
25
  }
25
26
  }
@@ -15,3 +15,8 @@ export function renderStream(url: string): ReadableStream<Uint8Array> {
15
15
  // this app's `"use server"` modules populate. @fluixi/start routes RPC calls here.
16
16
  import '@fluixi/start/server-fns'; // registers every "use server" module (incl. lazy routes)
17
17
  export { isServerFnRequest, handleServerFn } from '@fluixi/start/server-fn';
18
+
19
+ // File-based API routes under src/api. The dev server dispatches to them itself; a built
20
+ // server finds them through this, and without it every /api request would fall through
21
+ // to the page renderer. Harmless when there are no routes.
22
+ export { isApiRequest, handleApiRequest } from '@fluixi/start/api-routes';
@@ -19,6 +19,7 @@
19
19
  "devDependencies": {
20
20
  "@fluixi/ts-plugin": "alpha",
21
21
  "@types/node": "^20.0.0",
22
+ "typescript": "^5.9.0",
22
23
  "vite": "^5.0.0"
23
24
  }
24
25
  }
@@ -15,3 +15,8 @@ export function renderStream(url: string): ReadableStream<Uint8Array> {
15
15
  // this app's `"use server"` modules populate. @fluixi/start routes RPC calls here.
16
16
  import '@fluixi/start/server-fns'; // registers every "use server" module (incl. lazy routes)
17
17
  export { isServerFnRequest, handleServerFn } from '@fluixi/start/server-fn';
18
+
19
+ // File-based API routes under src/api. The dev server dispatches to them itself; a built
20
+ // server finds them through this, and without it every /api request would fall through
21
+ // to the page renderer. Harmless when there are no routes.
22
+ export { isApiRequest, handleApiRequest } from '@fluixi/start/api-routes';