@fluixi/start 0.1.0-alpha.73 → 0.1.0-alpha.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/adapter.cjs +748 -0
  2. package/dist/adapter.mjs +717 -0
  3. package/dist/adapters/entry.cjs +122 -0
  4. package/dist/adapters/entry.mjs +95 -0
  5. package/dist/adapters/platforms.cjs +311 -0
  6. package/dist/adapters/platforms.mjs +284 -0
  7. package/dist/api-RH6E5UTH.mjs +114 -0
  8. package/dist/api.cjs +145 -0
  9. package/dist/api.mjs +116 -0
  10. package/dist/commands/api-23MJFSYL.mjs +17 -0
  11. package/dist/commands/api-4IYNQRKG.mjs +16 -0
  12. package/dist/commands/api-RH6E5UTH.mjs +114 -0
  13. package/dist/commands/build.cjs +870 -0
  14. package/dist/commands/build.mjs +710 -0
  15. package/dist/commands/chunk-NS5GR2GX.mjs +115 -0
  16. package/dist/commands/chunk-OCPCK4ZJ.mjs +117 -0
  17. package/dist/commands/dev.cjs +663 -0
  18. package/dist/commands/dev.mjs +505 -0
  19. package/dist/commands/index.cjs +1138 -0
  20. package/dist/commands/index.mjs +975 -0
  21. package/dist/commands/prerender.cjs +402 -0
  22. package/dist/commands/prerender.mjs +375 -0
  23. package/dist/commands/start.cjs +461 -0
  24. package/dist/commands/start.mjs +426 -0
  25. package/dist/config.cjs +144 -0
  26. package/dist/config.mjs +108 -0
  27. package/dist/di.cjs +200 -0
  28. package/dist/di.mjs +169 -0
  29. package/dist/document.cjs +115 -0
  30. package/dist/document.mjs +86 -0
  31. package/dist/generated-api.cjs +43 -0
  32. package/dist/generated-api.mjs +18 -0
  33. package/dist/generated-server-fns.cjs +43 -0
  34. package/dist/generated-server-fns.mjs +18 -0
  35. package/dist/handler-core.cjs +211 -0
  36. package/dist/handler-core.mjs +185 -0
  37. package/dist/handler.cjs +181 -0
  38. package/dist/handler.mjs +150 -0
  39. package/dist/head.cjs +25 -0
  40. package/dist/head.mjs +4 -0
  41. package/dist/image.cjs +146 -0
  42. package/dist/image.mjs +120 -0
  43. package/dist/index.cjs +1036 -0
  44. package/dist/index.mjs +968 -0
  45. package/dist/interceptors.cjs +71 -0
  46. package/dist/interceptors.mjs +42 -0
  47. package/dist/internal.cjs +388 -0
  48. package/dist/internal.mjs +218 -0
  49. package/dist/middleware.cjs +58 -0
  50. package/dist/middleware.mjs +31 -0
  51. package/dist/preload.cjs +42 -0
  52. package/dist/preload.mjs +18 -0
  53. package/dist/router.cjs +25 -0
  54. package/dist/router.mjs +4 -0
  55. package/dist/server-fn-setup.cjs +46 -0
  56. package/dist/server-fn-setup.mjs +22 -0
  57. package/dist/server-fn.cjs +109 -0
  58. package/dist/server-fn.mjs +79 -0
  59. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  60. package/dist/ui.cjs +123 -0
  61. package/dist/ui.mjs +93 -0
  62. package/package.json +45 -25
@@ -0,0 +1,663 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // src/api.ts
34
+ var api_exports = {};
35
+ __export(api_exports, {
36
+ API_VIRTUAL_MODULE: () => API_VIRTUAL_MODULE,
37
+ apiRoutesVitePlugin: () => apiRoutesVitePlugin,
38
+ derivePattern: () => derivePattern,
39
+ handleApi: () => handleApi,
40
+ isApiPath: () => isApiPath,
41
+ matchApiRoutes: () => matchApiRoutes
42
+ });
43
+ function derivePattern(rel, prefix = "/api") {
44
+ const segs = rel.split("/").filter(Boolean);
45
+ if (segs[segs.length - 1] === "index") segs.pop();
46
+ const keys = [];
47
+ let rank = 0;
48
+ const parts = segs.map((seg) => {
49
+ const catchAll = seg.match(/^\[\.\.\.(.+)\]$/);
50
+ if (catchAll) {
51
+ keys.push(catchAll[1]);
52
+ return "(.+)";
53
+ }
54
+ const param = seg.match(/^\[(.+)\]$/);
55
+ if (param) {
56
+ keys.push(param[1]);
57
+ rank += 1;
58
+ return "([^/]+)";
59
+ }
60
+ rank += 10;
61
+ return seg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
62
+ });
63
+ return { source: `^${prefix}${parts.length ? "/" + parts.join("/") : ""}/?$`, keys, rank };
64
+ }
65
+ function isApiPath(pathname, prefix = "/api") {
66
+ return pathname === prefix || pathname.startsWith(prefix + "/");
67
+ }
68
+ function matchApiRoutes(routes, pathname) {
69
+ for (const r of [...routes].sort((a, b) => b.rank - a.rank)) {
70
+ const m = new RegExp(r.source).exec(pathname);
71
+ if (!m) continue;
72
+ const params = {};
73
+ r.keys.forEach((k, i) => params[k] = decodeURIComponent(m[i + 1] ?? ""));
74
+ return { mod: r.mod, params };
75
+ }
76
+ return null;
77
+ }
78
+ async function handleApi(routes, request, prefix = "/api") {
79
+ const pathname = new URL(request.url).pathname;
80
+ const match = matchApiRoutes(routes, pathname);
81
+ if (!match) return new Response("Not Found", { status: 404 });
82
+ const fn = match.mod[request.method];
83
+ if (typeof fn !== "function") {
84
+ const allow = METHODS.filter((m) => typeof match.mod[m] === "function").join(", ");
85
+ return new Response("Method Not Allowed", { status: 405, headers: allow ? { allow } : void 0 });
86
+ }
87
+ const out = await fn(request, { params: match.params });
88
+ if (out instanceof Response) return out;
89
+ return new Response(JSON.stringify(out ?? null), { headers: { "content-type": "application/json; charset=utf-8" } });
90
+ }
91
+ function scanFiles(dir, base = dir) {
92
+ let out = [];
93
+ let entries = [];
94
+ try {
95
+ entries = (0, import_node_fs.readdirSync)(dir);
96
+ } catch {
97
+ return out;
98
+ }
99
+ for (const name of entries) {
100
+ const full = (0, import_node_path2.join)(dir, name);
101
+ if ((0, import_node_fs.statSync)(full).isDirectory()) out = out.concat(scanFiles(full, base));
102
+ else if (/\.(ts|tsx|js|mjs)$/.test(name) && !/\.(spec|test)\./.test(name)) out.push(full);
103
+ }
104
+ return out;
105
+ }
106
+ function apiRoutesVitePlugin(opts) {
107
+ let root = process.cwd();
108
+ const prefix = opts.prefix ?? "/api";
109
+ const id = "\0" + API_VMOD;
110
+ return {
111
+ name: "fluixi-api",
112
+ // Must beat node resolution: '@fluixi/start/api-routes' is a real file in this package,
113
+ // so without `pre` Vite resolves the typed stub and the generated table never loads —
114
+ // the app builds and every API route 404s.
115
+ enforce: "pre",
116
+ configResolved(config) {
117
+ root = config.root || root;
118
+ },
119
+ resolveId(source) {
120
+ return source === API_VMOD || source === "@fluixi/start/api-routes" ? id : null;
121
+ },
122
+ load(source) {
123
+ if (source !== id) return null;
124
+ const dir = (0, import_node_path2.resolve)(root, opts.dir);
125
+ const files = scanFiles(dir);
126
+ const imports = [];
127
+ const entries = [];
128
+ files.forEach((file, i) => {
129
+ const rel = (0, import_node_path2.relative)(dir, file).replace(/\.(ts|tsx|js|mjs)$/, "").split(/[\\/]/).join("/");
130
+ const { source: src, keys, rank } = derivePattern(rel, prefix);
131
+ imports.push(`import * as _${i} from ${JSON.stringify(file)};`);
132
+ entries.push(`{ source: ${JSON.stringify(src)}, keys: ${JSON.stringify(keys)}, rank: ${rank}, mod: _${i} }`);
133
+ });
134
+ return `import { isApiPath, handleApi } from '@fluixi/start/api';
135
+ ${imports.join("\n")}
136
+ const routes = [${entries.join(",")}];
137
+ export const isApiRequest = (request) => isApiPath(new URL(request.url).pathname, ${JSON.stringify(prefix)});
138
+ export const handleApiRequest = (request) => handleApi(routes, request, ${JSON.stringify(prefix)});
139
+ `;
140
+ }
141
+ };
142
+ }
143
+ var import_node_fs, import_node_path2, API_VMOD, METHODS, API_VIRTUAL_MODULE;
144
+ var init_api = __esm({
145
+ "src/api.ts"() {
146
+ "use strict";
147
+ import_node_fs = require("node:fs");
148
+ import_node_path2 = require("node:path");
149
+ API_VMOD = "virtual:fluixi-api";
150
+ METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"];
151
+ API_VIRTUAL_MODULE = API_VMOD;
152
+ }
153
+ });
154
+
155
+ // src/commands/dev.ts
156
+ var dev_exports = {};
157
+ __export(dev_exports, {
158
+ dev: () => dev
159
+ });
160
+ module.exports = __toCommonJS(dev_exports);
161
+ var import_node_http = require("node:http");
162
+ var import_node_fs3 = require("node:fs");
163
+ var import_node_path4 = require("node:path");
164
+
165
+ // src/config.ts
166
+ var import_node_path = require("node:path");
167
+ function resolveConfig(config = {}) {
168
+ const root = (0, import_node_path.resolve)(config.root ?? process.cwd());
169
+ return {
170
+ root,
171
+ ssr: config.ssr ?? true,
172
+ port: config.port ?? 3e3,
173
+ serverEntry: config.serverEntry ?? "src/entry-server.ts",
174
+ clientEntry: config.clientEntry ?? "src/entry-client.ts",
175
+ template: config.template ?? "index.html",
176
+ mountId: config.mountId ?? "root",
177
+ routesDir: config.routesDir ?? "src/routes",
178
+ apiDir: config.apiDir ?? "src/api",
179
+ middleware: config.middleware ?? "src/middleware.ts",
180
+ ssrNoExternal: config.ssrNoExternal ?? [],
181
+ resolve: config.resolve ?? [],
182
+ adapter: config.adapter,
183
+ i18n: resolveI18n(config.i18n),
184
+ prerender: resolvePrerender(config.prerender)
185
+ };
186
+ }
187
+ function resolvePrerender(prerender) {
188
+ if (!prerender) return false;
189
+ const opts = typeof prerender === "object" ? prerender : {};
190
+ return {
191
+ routes: opts.routes?.length ? opts.routes : ["/"],
192
+ crawl: opts.crawl ?? true
193
+ };
194
+ }
195
+ function resolveI18n(i18n) {
196
+ if (i18n === false) return false;
197
+ const opts = typeof i18n === "object" ? i18n : {};
198
+ return {
199
+ dir: opts.dir ?? "src/i18n",
200
+ defaultLocale: opts.defaultLocale,
201
+ locales: opts.locales
202
+ };
203
+ }
204
+
205
+ // src/internal.ts
206
+ var import_node_fs2 = require("node:fs");
207
+ var import_node_path3 = require("node:path");
208
+
209
+ // src/document.ts
210
+ var import_head = require("@fluixi/head");
211
+ function injectApp(template, appHtml, mountId = "root") {
212
+ const mount = new RegExp(`<div id=["']${mountId}["']\\s*>\\s*</div>`);
213
+ if (mount.test(template)) {
214
+ return template.replace(mount, `<div id="${mountId}">${appHtml}</div>`);
215
+ }
216
+ if (template.includes("<!--ssr-outlet-->")) {
217
+ return template.replace("<!--ssr-outlet-->", appHtml);
218
+ }
219
+ return template.replace("</body>", `<div id="${mountId}">${appHtml}</div></body>`);
220
+ }
221
+ function splitTemplate(template, mountId = "root") {
222
+ const mount = new RegExp(`<div id=["']${mountId}["']\\s*>\\s*</div>`);
223
+ const m = template.match(mount);
224
+ if (m && m.index !== void 0) {
225
+ return {
226
+ head: template.slice(0, m.index) + `<div id="${mountId}">`,
227
+ tail: `</div>` + template.slice(m.index + m[0].length)
228
+ };
229
+ }
230
+ const outlet = template.indexOf("<!--ssr-outlet-->");
231
+ if (outlet !== -1) {
232
+ return {
233
+ head: template.slice(0, outlet),
234
+ tail: template.slice(outlet + "<!--ssr-outlet-->".length)
235
+ };
236
+ }
237
+ const body = template.indexOf("</body>");
238
+ if (body !== -1) {
239
+ return {
240
+ head: template.slice(0, body) + `<div id="${mountId}">`,
241
+ tail: `</div>` + template.slice(body)
242
+ };
243
+ }
244
+ return { head: template, tail: "" };
245
+ }
246
+ function setHtmlAttr(html, name, value) {
247
+ const existing = new RegExp(`(<html\\b[^>]*?)\\s${name}="[^"]*"`, "i");
248
+ if (existing.test(html)) return html.replace(existing, `$1 ${name}="${value}"`);
249
+ return html.replace(/<html\b/i, `<html ${name}="${value}"`);
250
+ }
251
+ function injectAppAndHead(template, rendered, mountId = "root") {
252
+ const { head, body } = (0, import_head.extractHeadMarker)(rendered);
253
+ let html = injectApp(template, body, mountId);
254
+ if (head) {
255
+ if (head.headHtml) {
256
+ if (/<title[\s>]/i.test(head.headHtml)) html = html.replace(/<title>[\s\S]*?<\/title>/i, "");
257
+ html = html.replace("</head>", `${head.headHtml}</head>`);
258
+ }
259
+ for (const [k, v] of Object.entries(head.htmlAttrs)) html = setHtmlAttr(html, k, v);
260
+ }
261
+ return html;
262
+ }
263
+ function guardHandler(handler, onError) {
264
+ return async (request) => {
265
+ try {
266
+ return await handler(request);
267
+ } catch (e) {
268
+ onError?.(e);
269
+ return new Response(String(e?.stack || e), {
270
+ status: 500,
271
+ headers: { "content-type": "text/plain; charset=utf-8" }
272
+ });
273
+ }
274
+ };
275
+ }
276
+
277
+ // src/internal.ts
278
+ var SERVER_FNS_VMOD = "virtual:fluixi-server-fns";
279
+ var I18N_VMOD = "virtual:fluixi-i18n";
280
+ function i18nVitePlugin(opts) {
281
+ let root = process.cwd();
282
+ const id = "\0" + I18N_VMOD;
283
+ return {
284
+ name: "fluixi-i18n",
285
+ configResolved(config) {
286
+ root = config.root || root;
287
+ },
288
+ resolveId(source) {
289
+ return source === I18N_VMOD ? id : null;
290
+ },
291
+ load(source) {
292
+ if (source !== id) return null;
293
+ const dir = (0, import_node_path3.resolve)(root, opts.dir);
294
+ let files = [];
295
+ try {
296
+ files = (0, import_node_fs2.readdirSync)(dir).filter((f) => f.endsWith(".json"));
297
+ } catch {
298
+ }
299
+ const discovered = files.map((f) => f.replace(/\.json$/, "")).sort();
300
+ const locales = opts.locales?.length ? opts.locales : discovered;
301
+ const defaultLocale = opts.defaultLocale ?? locales[0] ?? "en";
302
+ const imports = locales.map((l, i) => `import _${i} from ${JSON.stringify((0, import_node_path3.resolve)(dir, l + ".json"))};`).join("\n");
303
+ const messages = `export const messages = {${locales.map((l, i) => `${JSON.stringify(l)}:_${i}`).join(",")}};`;
304
+ return `${imports}
305
+ export const locales = ${JSON.stringify(locales)};
306
+ export const defaultLocale = ${JSON.stringify(defaultLocale)};
307
+ ${messages}
308
+ `;
309
+ }
310
+ };
311
+ }
312
+ async function loadServerEnv(root, mode) {
313
+ const { loadEnv } = await import("vite");
314
+ const env = loadEnv(mode, root, "");
315
+ for (const [k, v] of Object.entries(env)) {
316
+ if (process.env[k] === void 0) process.env[k] = v;
317
+ }
318
+ }
319
+ function i18nTypeBlock(root, i18n) {
320
+ const dir = (0, import_node_path3.resolve)(root, i18n.dir);
321
+ let discovered = [];
322
+ try {
323
+ discovered = (0, import_node_fs2.readdirSync)(dir).filter((f) => f.endsWith(".json")).map((f) => f.replace(/\.json$/, "")).sort();
324
+ } catch {
325
+ }
326
+ const locales = i18n.locales?.length ? i18n.locales : discovered;
327
+ const defaultLocale = i18n.defaultLocale ?? locales[0] ?? "en";
328
+ const typed = locales.length > 0 && locales.every((l) => discovered.includes(l));
329
+ if (!typed) {
330
+ return [
331
+ `declare module 'virtual:fluixi-i18n' {`,
332
+ ` export const messages: Record<string, Record<string, unknown>>;`,
333
+ ` export const locales: string[];`,
334
+ ` export const defaultLocale: string;`,
335
+ `}`
336
+ ];
337
+ }
338
+ const srcDir = (0, import_node_path3.resolve)(root, "src");
339
+ const toSpec = (l) => {
340
+ const rel = (0, import_node_path3.relative)(srcDir, (0, import_node_path3.resolve)(dir, l + ".json")).split(/[\\/]/).join("/");
341
+ return rel.startsWith(".") ? rel : "./" + rel;
342
+ };
343
+ const entries = locales.map((l) => ` ${JSON.stringify(l)}: (typeof import(${JSON.stringify(toSpec(l))}))['default'];`);
344
+ const tuple = locales.map((l) => JSON.stringify(l)).join(", ");
345
+ return [
346
+ `declare module 'virtual:fluixi-i18n' {`,
347
+ ` export const messages: {`,
348
+ ...entries,
349
+ ` };`,
350
+ ` export const locales: readonly [${tuple}];`,
351
+ ` export const defaultLocale: ${JSON.stringify(defaultLocale)};`,
352
+ `}`
353
+ ];
354
+ }
355
+ function startTypesPlugin(cfg) {
356
+ let root = process.cwd();
357
+ return {
358
+ name: "fluixi-start-types",
359
+ configResolved(config) {
360
+ root = config.root || root;
361
+ },
362
+ buildStart() {
363
+ const blocks = [];
364
+ if (cfg.i18n) blocks.push(...i18nTypeBlock(root, cfg.i18n));
365
+ if (blocks.length === 0) return;
366
+ const content = `// Auto-generated by @fluixi/start — do not edit.
367
+ ${blocks.join("\n")}
368
+ `;
369
+ const file = (0, import_node_path3.resolve)(root, "src/fluixi-start-env.d.ts");
370
+ try {
371
+ if (!(0, import_node_fs2.existsSync)(file) || (0, import_node_fs2.readFileSync)(file, "utf8") !== content) (0, import_node_fs2.writeFileSync)(file, content);
372
+ } catch {
373
+ }
374
+ }
375
+ };
376
+ }
377
+ async function fluixiPlugins(cfg) {
378
+ const { fluixi, fluixiRoutesPlugin } = await import("@fluixi/core/plugins");
379
+ const { serverFunctionsVitePlugin } = await import("@fluixi/compiler/integrations");
380
+ const plugins = [
381
+ serverFunctionsVitePlugin(),
382
+ fluixiRoutesPlugin({ routesDir: cfg.routesDir, polyfills: false }),
383
+ // The app's component-resolution rules reach the compiler here; without this an SSR
384
+ // app has no way to say where an unimported tag comes from.
385
+ //
386
+ // `fluixi()` and not `createVitePlugin()`: the latter is the bare compiler integration,
387
+ // and the reactive graph — agent, source marks, /__fluixi/graph — is composed on top of
388
+ // it by the former. A start app got no graph at all until this changed.
389
+ fluixi({ resolve: cfg.resolve })
390
+ ];
391
+ if (cfg.i18n) plugins.push(i18nVitePlugin(cfg.i18n));
392
+ const { apiRoutesVitePlugin: apiRoutesVitePlugin2 } = await Promise.resolve().then(() => (init_api(), api_exports));
393
+ plugins.push(apiRoutesVitePlugin2({ dir: cfg.apiDir }));
394
+ plugins.push(startTypesPlugin(cfg));
395
+ return plugins;
396
+ }
397
+ var _guardsInstalled = false;
398
+ function installCrashGuards() {
399
+ if (_guardsInstalled) return;
400
+ _guardsInstalled = true;
401
+ process.on(
402
+ "unhandledRejection",
403
+ (reason) => console.warn("[fluixi] unhandled rejection (backend likely down) —", reason?.message || reason)
404
+ );
405
+ process.on(
406
+ "uncaughtException",
407
+ (err) => console.warn("[fluixi] uncaught exception —", err?.message || err)
408
+ );
409
+ }
410
+
411
+ // src/handler.ts
412
+ function streamDocument(head, body, tail) {
413
+ const enc = new TextEncoder();
414
+ const stream = new ReadableStream({
415
+ async start(controller) {
416
+ try {
417
+ controller.enqueue(enc.encode(head));
418
+ const reader = body.getReader();
419
+ for (; ; ) {
420
+ const { done, value } = await reader.read();
421
+ if (done) break;
422
+ controller.enqueue(value);
423
+ }
424
+ controller.enqueue(enc.encode(tail));
425
+ controller.close();
426
+ } catch (err) {
427
+ controller.error(err);
428
+ }
429
+ }
430
+ });
431
+ return new Response(stream, {
432
+ status: 200,
433
+ headers: { "content-type": "text/html; charset=utf-8" }
434
+ });
435
+ }
436
+ function nodeToRequest(req) {
437
+ const host = req.headers.host ?? "localhost";
438
+ const url = `http://${host}${req.url ?? "/"}`;
439
+ const headers = new Headers();
440
+ for (const [k, v] of Object.entries(req.headers)) {
441
+ if (Array.isArray(v)) v.forEach((x) => headers.append(k, x));
442
+ else if (v != null) headers.set(k, v);
443
+ }
444
+ const method = req.method ?? "GET";
445
+ const init = { method, headers };
446
+ if (method !== "GET" && method !== "HEAD") {
447
+ init.body = req;
448
+ init.duplex = "half";
449
+ }
450
+ return new Request(url, init);
451
+ }
452
+ async function sendResponse(res, response) {
453
+ res.statusCode = response.status;
454
+ response.headers.forEach((value, key) => res.setHeader(key, value));
455
+ const body = response.body;
456
+ if (!body) {
457
+ res.end(await response.text().catch(() => ""));
458
+ return;
459
+ }
460
+ const reader = body.getReader();
461
+ try {
462
+ for (; ; ) {
463
+ const { done, value } = await reader.read();
464
+ if (done) break;
465
+ res.write(value);
466
+ }
467
+ } finally {
468
+ res.end();
469
+ }
470
+ }
471
+ function toNodeHandler(handler) {
472
+ return async (req, res) => {
473
+ const response = await handler(nodeToRequest(req));
474
+ await sendResponse(res, response);
475
+ };
476
+ }
477
+
478
+ // src/middleware.ts
479
+ function normalizeMiddleware(mod) {
480
+ const def = mod?.default ?? mod;
481
+ if (def == null) return [];
482
+ if (Array.isArray(def)) return def.filter((m) => typeof m === "function");
483
+ return typeof def === "function" ? [def] : [];
484
+ }
485
+ function composeMiddleware(middlewares, core) {
486
+ if (middlewares.length === 0) return core;
487
+ return (request) => {
488
+ let lastCalled = -1;
489
+ const dispatch = (i) => {
490
+ if (i <= lastCalled) {
491
+ return Promise.reject(new Error("middleware called next() more than once"));
492
+ }
493
+ lastCalled = i;
494
+ const mw = middlewares[i];
495
+ if (!mw) return Promise.resolve(core(request));
496
+ return Promise.resolve(mw(request, () => dispatch(i + 1)));
497
+ };
498
+ return dispatch(0);
499
+ };
500
+ }
501
+
502
+ // src/commands/dev.ts
503
+ init_api();
504
+
505
+ // src/ui.ts
506
+ var import_node_os = require("node:os");
507
+ var COLOR = process.env.NO_COLOR || process.env.FORCE_COLOR === "0" ? false : (!!process.stdout.isTTY || !!process.env.FORCE_COLOR) && process.env.TERM !== "dumb";
508
+ var sgr = (open, close) => (s) => COLOR ? `\x1B[${open}m${s}\x1B[${close}m` : `${s}`;
509
+ var c = {
510
+ bold: sgr(1, 22),
511
+ dim: sgr(2, 22),
512
+ italic: sgr(3, 23),
513
+ underline: sgr(4, 24),
514
+ red: sgr(31, 39),
515
+ green: sgr(32, 39),
516
+ yellow: sgr(33, 39),
517
+ blue: sgr(34, 39),
518
+ magenta: sgr(35, 39),
519
+ cyan: sgr(36, 39),
520
+ gray: sgr(90, 39)
521
+ };
522
+ var rgb = (r, g, b) => (s) => COLOR ? `\x1B[38;2;${r};${g};${b}m${s}\x1B[39m` : s;
523
+ var BRAND = [
524
+ [34, 211, 238],
525
+ // cyan-400
526
+ [56, 189, 248],
527
+ [129, 140, 248],
528
+ [167, 139, 250],
529
+ [192, 132, 252],
530
+ // violet-400
531
+ [217, 130, 245]
532
+ ];
533
+ function gradient(text) {
534
+ if (!COLOR) return text;
535
+ const chars = [...text];
536
+ return chars.map((ch, i) => {
537
+ const [r, g, b] = BRAND[Math.min(BRAND.length - 1, Math.floor(i / Math.max(1, chars.length - 1) * (BRAND.length - 1)))];
538
+ return rgb(r, g, b)(ch);
539
+ }).join("");
540
+ }
541
+ function wordmark(version) {
542
+ const mark = `${gradient("◆")} ${c.bold(gradient("fluixi"))}`;
543
+ return version ? `${mark} ${c.dim(`v${version}`)}` : mark;
544
+ }
545
+ var SYM = {
546
+ arrow: c.gray("➜"),
547
+ ok: c.green("✓"),
548
+ err: c.red("✗")
549
+ };
550
+ function networkAddress() {
551
+ for (const list of Object.values((0, import_node_os.networkInterfaces)())) {
552
+ for (const net of list ?? []) {
553
+ const family = typeof net.family === "string" ? net.family : `IPv${net.family}`;
554
+ if (family === "IPv4" && !net.internal) return net.address;
555
+ }
556
+ }
557
+ return null;
558
+ }
559
+ function devReady(opts) {
560
+ const ms = Date.now() - opts.startedAt;
561
+ const local = `http://localhost:${opts.port}/`;
562
+ const net = networkAddress();
563
+ const link = (u) => c.cyan(c.underline(u));
564
+ const label = (s) => c.gray(s.padEnd(8));
565
+ const lines = [
566
+ "",
567
+ ` ${wordmark(opts.version)} ${c.gray(`dev ready in ${c.bold(String(ms))} ms`)}`,
568
+ "",
569
+ ` ${SYM.arrow} ${label("Local")} ${link(local)}`,
570
+ net ? ` ${SYM.arrow} ${label("Network")} ${link(`http://${net}:${opts.port}/`)}` : ` ${SYM.arrow} ${label("Network")} ${c.dim("not exposed")}`,
571
+ ""
572
+ ];
573
+ process.stdout.write(lines.join("\n") + "\n");
574
+ }
575
+
576
+ // src/commands/dev.ts
577
+ var STYLE_FILE = /\.(css|scss|sass|less|styl|stylus|pcss|postcss)(\?|$)/;
578
+ async function renderedStyles(vite, entry) {
579
+ const seen = /* @__PURE__ */ new Set();
580
+ const found = [];
581
+ const visit = (mod) => {
582
+ if (!mod || seen.has(mod.url)) return;
583
+ seen.add(mod.url);
584
+ if (STYLE_FILE.test(mod.url)) found.push(mod.url);
585
+ for (const dep of mod.importedModules ?? []) visit(dep);
586
+ };
587
+ try {
588
+ visit(await vite.moduleGraph.getModuleByUrl("/" + entry, true));
589
+ } catch {
590
+ return [];
591
+ }
592
+ return found;
593
+ }
594
+ function injectStyles(html, urls) {
595
+ if (urls.length === 0) return html;
596
+ const links = urls.map((url) => `<link rel="stylesheet" href="${url}${url.includes("?") ? "&" : "?"}direct">`).join("\n ");
597
+ return html.includes("</head>") ? html.replace("</head>", ` ${links}
598
+ </head>`) : html;
599
+ }
600
+ async function dev(config = {}) {
601
+ const startedAt = Date.now();
602
+ const cfg = resolveConfig(config);
603
+ installCrashGuards();
604
+ await loadServerEnv(cfg.root, "development");
605
+ const { createServer } = await import("vite");
606
+ const template = (0, import_node_fs3.readFileSync)((0, import_node_path4.resolve)(cfg.root, cfg.template), "utf-8");
607
+ let vite;
608
+ const renderHandler = guardHandler(async (request) => {
609
+ const url = new URL(request.url);
610
+ const path = url.pathname + url.search;
611
+ if (url.pathname === "/_server") {
612
+ const sf = await vite.ssrLoadModule(SERVER_FNS_VMOD);
613
+ if (sf.isServerFnRequest(request)) return sf.handleServerFn(request);
614
+ }
615
+ if (isApiPath(url.pathname)) {
616
+ const api = await vite.ssrLoadModule(API_VIRTUAL_MODULE);
617
+ if (api.isApiRequest(request)) return api.handleApiRequest(request);
618
+ }
619
+ if (!cfg.ssr) {
620
+ const html2 = await vite.transformIndexHtml(path, template);
621
+ return new Response(html2, { status: 200, headers: { "content-type": "text/html; charset=utf-8" } });
622
+ }
623
+ const mod = await vite.ssrLoadModule("/" + cfg.serverEntry);
624
+ if (typeof mod.renderStream === "function") {
625
+ const shell = await vite.transformIndexHtml(
626
+ path,
627
+ injectStyles(template, await renderedStyles(vite, cfg.serverEntry))
628
+ );
629
+ const { head, tail } = splitTemplate(shell, cfg.mountId);
630
+ return streamDocument(head, await mod.renderStream(path, request), tail);
631
+ }
632
+ const render = mod.render ?? mod.default;
633
+ const appHtml = await render(path, request);
634
+ const styled = injectStyles(
635
+ injectAppAndHead(template, appHtml, cfg.mountId),
636
+ await renderedStyles(vite, cfg.serverEntry)
637
+ );
638
+ const html = await vite.transformIndexHtml(path, styled);
639
+ return new Response(html, { status: 200, headers: { "content-type": "text/html; charset=utf-8" } });
640
+ }, (e) => vite.ssrFixStacktrace?.(e));
641
+ const hasMiddleware = (0, import_node_fs3.existsSync)((0, import_node_path4.resolve)(cfg.root, cfg.middleware));
642
+ const handler = hasMiddleware ? guardHandler(async (request) => {
643
+ const mwMod = await vite.ssrLoadModule("/" + cfg.middleware);
644
+ return composeMiddleware(normalizeMiddleware(mwMod), renderHandler)(request);
645
+ }, (e) => vite.ssrFixStacktrace?.(e)) : renderHandler;
646
+ const nodeHandler = toNodeHandler(handler);
647
+ const http = (0, import_node_http.createServer)((req, res) => {
648
+ vite.middlewares(req, res, () => nodeHandler(req, res));
649
+ });
650
+ vite = await createServer({
651
+ root: cfg.root,
652
+ plugins: await fluixiPlugins(cfg),
653
+ // file routing + JSX/SSR transform (fluixi)
654
+ server: { middlewareMode: true, hmr: { server: http } },
655
+ appType: "custom",
656
+ ssr: cfg.ssrNoExternal.length ? { noExternal: cfg.ssrNoExternal } : void 0
657
+ });
658
+ http.listen(cfg.port, () => devReady({ port: cfg.port, startedAt }));
659
+ }
660
+ // Annotate the CommonJS export names for ESM import in node:
661
+ 0 && (module.exports = {
662
+ dev
663
+ });