create-fluixi 0.1.0-alpha.8 → 1.0.0-alpha.99

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