@finesoft/front 0.1.39 → 0.1.41

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 (41) hide show
  1. package/dist/app-re7jUCuM.mjs +178 -0
  2. package/dist/app-re7jUCuM.mjs.map +1 -0
  3. package/dist/index.d.mts +1276 -0
  4. package/dist/index.d.mts.map +1 -0
  5. package/dist/index.mjs +2749 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/dist/locale-D2Bu7w47.mjs +27 -0
  8. package/dist/locale-D2Bu7w47.mjs.map +1 -0
  9. package/dist/rolldown-runtime-wcPFST8Q.mjs +13 -0
  10. package/dist/server-peer-modules-BSSsxBaF.d.mts +41 -0
  11. package/dist/server-peer-modules-BSSsxBaF.d.mts.map +1 -0
  12. package/package.json +21 -32
  13. package/README.md +0 -1136
  14. package/dist/app-XEMPAI6H.js +0 -10
  15. package/dist/app-XEMPAI6H.js.map +0 -1
  16. package/dist/browser.cjs +0 -1465
  17. package/dist/browser.cjs.map +0 -1
  18. package/dist/browser.d.cts +0 -904
  19. package/dist/browser.d.ts +0 -904
  20. package/dist/browser.js +0 -115
  21. package/dist/browser.js.map +0 -1
  22. package/dist/chunk-4PPCVAKZ.js +0 -463
  23. package/dist/chunk-4PPCVAKZ.js.map +0 -1
  24. package/dist/chunk-OYTIGVEG.js +0 -193
  25. package/dist/chunk-OYTIGVEG.js.map +0 -1
  26. package/dist/chunk-PSPVIVC2.js +0 -25
  27. package/dist/chunk-PSPVIVC2.js.map +0 -1
  28. package/dist/chunk-SDPWQT2T.js +0 -936
  29. package/dist/chunk-SDPWQT2T.js.map +0 -1
  30. package/dist/chunk-XQ3UWZOS.js +0 -187
  31. package/dist/chunk-XQ3UWZOS.js.map +0 -1
  32. package/dist/index.cjs +0 -3661
  33. package/dist/index.cjs.map +0 -1
  34. package/dist/index.d.cts +0 -582
  35. package/dist/index.d.ts +0 -582
  36. package/dist/index.js +0 -1648
  37. package/dist/index.js.map +0 -1
  38. package/dist/locale-CAZ4INCX.js +0 -7
  39. package/dist/locale-CAZ4INCX.js.map +0 -1
  40. package/dist/src-XNC7QNVI.js +0 -21
  41. package/dist/src-XNC7QNVI.js.map +0 -1
package/dist/index.js DELETED
@@ -1,1648 +0,0 @@
1
- import {
2
- History,
3
- createPrefetchedIntentsFromDom,
4
- deserializeServerData,
5
- registerActionHandlers,
6
- registerExternalUrlHandler,
7
- registerFlowActionHandler,
8
- startBrowserApp,
9
- tryScroll
10
- } from "./chunk-4PPCVAKZ.js";
11
- import {
12
- MAX_SSR_DEPTH,
13
- SSR_DEPTH_HEADER,
14
- createInternalFetch,
15
- createSSRApp
16
- } from "./chunk-OYTIGVEG.js";
17
- import {
18
- SSR_PLACEHOLDERS,
19
- createSSRRender,
20
- injectCSRShell,
21
- injectSSRContent,
22
- serializeServerData,
23
- ssrRender
24
- } from "./chunk-XQ3UWZOS.js";
25
- import {
26
- ACTION_KINDS,
27
- ActionDispatcher,
28
- BaseController,
29
- BaseLogger,
30
- CompositeLogger,
31
- CompositeLoggerFactory,
32
- ConsoleLogger,
33
- ConsoleLoggerFactory,
34
- Container,
35
- DEP_KEYS,
36
- Framework,
37
- HttpClient,
38
- HttpError,
39
- IntentDispatcher,
40
- LruMap,
41
- PrefetchedIntents,
42
- Router,
43
- buildUrl,
44
- createBrowserContext,
45
- createServerContext,
46
- defineRoutes,
47
- deny,
48
- generateUuid,
49
- getBaseUrl,
50
- isCompoundAction,
51
- isExternalUrlAction,
52
- isFlowAction,
53
- isNone,
54
- isSome,
55
- makeDependencies,
56
- makeExternalUrlAction,
57
- makeFlowAction,
58
- mapEach,
59
- next,
60
- pipe,
61
- pipeAsync,
62
- redirect,
63
- removeHost,
64
- removeQueryParams,
65
- removeScheme,
66
- resetFilterCache,
67
- rewrite,
68
- runAfterLoadGuards,
69
- runBeforeLoadGuards,
70
- shouldLog,
71
- stableStringify
72
- } from "./chunk-SDPWQT2T.js";
73
- import {
74
- parseAcceptLanguage
75
- } from "./chunk-PSPVIVC2.js";
76
-
77
- // ../server/src/proxy.ts
78
- function sanitizeProxyPath(raw) {
79
- if (raw.startsWith("//")) return null;
80
- return raw.startsWith("/") ? raw : `/${raw}`;
81
- }
82
- function validateConfig(config) {
83
- if (!config.prefix.startsWith("/")) {
84
- throw new Error(
85
- `[proxy] prefix must start with "/": "${config.prefix}"`
86
- );
87
- }
88
- if (!config.target.startsWith("https://")) {
89
- throw new Error(`[proxy] target must use HTTPS: "${config.target}"`);
90
- }
91
- }
92
- function registerProxyRoutes(app, configs) {
93
- for (const config of configs) {
94
- validateConfig(config);
95
- const methods = config.methods ?? ["all"];
96
- const pattern = `${config.prefix}/*`;
97
- const handler = async (c) => {
98
- const subPath = sanitizeProxyPath(
99
- c.req.path.replace(config.prefix, "")
100
- );
101
- if (!subPath) return c.text("Invalid path", 400);
102
- const targetUrl = new URL(subPath, config.target);
103
- const reqUrl = new URL(c.req.url);
104
- reqUrl.searchParams.forEach(
105
- (v, k) => targetUrl.searchParams.set(k, v)
106
- );
107
- const headers = { ...config.headers };
108
- if (config.auth) {
109
- const token = process.env[config.auth.envKey] ?? "";
110
- if (token) {
111
- headers.Authorization = config.auth.type === "bearer" ? `Bearer ${token}` : `Basic ${token}`;
112
- }
113
- }
114
- try {
115
- const resp = await fetch(targetUrl.toString(), {
116
- headers,
117
- redirect: config.followRedirects ? "follow" : "manual"
118
- });
119
- const body = await resp.text();
120
- const respHeaders = {
121
- "Content-Type": resp.headers.get("Content-Type") ?? "application/json"
122
- };
123
- if (config.cache) {
124
- respHeaders["Cache-Control"] = config.cache;
125
- }
126
- return c.newResponse(body, resp.status, respHeaders);
127
- } catch (e) {
128
- console.error(`[Proxy ${config.prefix}]`, e);
129
- return c.json({ error: "Proxy request failed" }, 502);
130
- }
131
- };
132
- for (const method of methods) {
133
- app[method](pattern, handler);
134
- }
135
- }
136
- }
137
- function generateProxyCode(configs) {
138
- if (!configs || configs.length === 0) return "";
139
- for (const config of configs) {
140
- validateConfig(config);
141
- }
142
- const blocks = [];
143
- blocks.push(`
144
- // \u2500\u2500\u2500 \u6846\u67B6\u58F0\u660E\u5F0F\u4EE3\u7406\u8DEF\u7531 \u2500\u2500\u2500
145
- function _sanitizeProxyPath(raw) {
146
- if (raw.startsWith("//")) return null;
147
- return raw.startsWith("/") ? raw : "/" + raw;
148
- }
149
- `);
150
- for (const config of configs) {
151
- const methods = config.methods ?? ["all"];
152
- const pattern = `"${config.prefix}/*"`;
153
- const headersJson = JSON.stringify(config.headers ?? {});
154
- const cacheStr = config.cache ? JSON.stringify(config.cache) : "null";
155
- const redirect2 = config.followRedirects ? '"follow"' : '"manual"';
156
- let authCode = "";
157
- if (config.auth) {
158
- const envKey = JSON.stringify(config.auth.envKey);
159
- const prefix = config.auth.type === "bearer" ? "Bearer " : "Basic ";
160
- authCode = `
161
- const _token = (typeof process !== "undefined" && process.env && process.env[${envKey}]) || "";
162
- if (_token) _headers.Authorization = "${prefix}" + _token;`;
163
- }
164
- const handlerCode = `async (c) => {
165
- const _sub = _sanitizeProxyPath(c.req.path.replace(${JSON.stringify(
166
- config.prefix
167
- )}, ""));
168
- if (!_sub) return c.text("Invalid path", 400);
169
- const _target = new URL(_sub, ${JSON.stringify(config.target)});
170
- const _reqUrl = new URL(c.req.url);
171
- _reqUrl.searchParams.forEach((v, k) => _target.searchParams.set(k, v));
172
- const _headers = ${headersJson};${authCode}
173
- try {
174
- const _resp = await fetch(_target.toString(), { headers: _headers, redirect: ${redirect2} });
175
- const _body = await _resp.text();
176
- const _rh = { "Content-Type": _resp.headers.get("Content-Type") || "application/json" };
177
- if (${cacheStr}) _rh["Cache-Control"] = ${cacheStr};
178
- return c.newResponse(_body, _resp.status, _rh);
179
- } catch (_e) {
180
- console.error("[Proxy ${config.prefix}]", _e);
181
- return c.json({ error: "Proxy request failed" }, 502);
182
- }
183
- }`;
184
- for (const method of methods) {
185
- blocks.push(`app.${method}(${pattern}, ${handlerCode});`);
186
- }
187
- }
188
- return blocks.join("\n");
189
- }
190
-
191
- // ../server/src/adapters/shared.ts
192
- var BUILD_TOOL_EXTERNALS = [
193
- "vite",
194
- "esbuild",
195
- "rollup",
196
- "fsevents",
197
- "lightningcss"
198
- ];
199
- function generateSSREntry(ctx, opts) {
200
- const setupImport = ctx.setupPath ? `import _setupDefault from "./${ctx.setupPath}";` : ``;
201
- const setupCall = ctx.setupPath ? `if (typeof _setupDefault === "function") await _setupDefault(app);` : ``;
202
- const locales = JSON.stringify(ctx.locales);
203
- const defaultLocale = JSON.stringify(ctx.defaultLocale);
204
- const renderModes = JSON.stringify(ctx.renderModes ?? {});
205
- const cacheImpl = opts.platformCache ? opts.platformCache : `
206
- const ISR_CACHE_MAX = 1000;
207
- const _isrMap = new Map();
208
- async function platformCacheGet(url) {
209
- return _isrMap.get(url) ?? null;
210
- }
211
- async function platformCacheSet(url, html) {
212
- if (_isrMap.size >= ISR_CACHE_MAX) {
213
- const first = _isrMap.keys().next().value;
214
- _isrMap.delete(first);
215
- }
216
- _isrMap.set(url, html);
217
- }`;
218
- return `
219
- import { Hono } from "hono";
220
- ${opts.platformImport}
221
- import { render, serializeServerData } from "./${ctx.ssrEntry}";
222
- ${setupImport}
223
-
224
- const TEMPLATE = ${JSON.stringify(ctx.templateHtml)};
225
- const LOCALES = ${locales};
226
- const DEFAULT_LOCALE = ${defaultLocale};
227
- const RENDER_MODES = ${renderModes};
228
- ${cacheImpl}
229
-
230
- function parseAcceptLanguage(header) {
231
- if (!header) return DEFAULT_LOCALE;
232
- const langs = header.split(",").map(p => {
233
- const [l, q] = p.trim().split(";q=");
234
- return { l: l.trim().toLowerCase(), q: q ? (+q || 0) : 1 };
235
- }).sort((a, b) => b.q - a.q);
236
- for (const { l } of langs) {
237
- const prefix = l.split("-")[0];
238
- if (LOCALES.includes(prefix)) return prefix;
239
- }
240
- return DEFAULT_LOCALE;
241
- }
242
-
243
- function injectSSR(t, locale, head, css, html, data) {
244
- return t
245
- .replace("<!--ssr-lang-->", locale)
246
- .replace("<!--ssr-head-->", head + "\\n<style>" + css + "</style>")
247
- .replace("<!--ssr-body-->", html)
248
- .replace("<!--ssr-data-->", '<script id="serialized-server-data" type="application/json">' + data + "</script>");
249
- }
250
-
251
- function injectCSRShell(t, locale) {
252
- return t
253
- .replace("<!--ssr-lang-->", locale)
254
- .replace("<!--ssr-head-->", "")
255
- .replace("<!--ssr-body-->", "")
256
- .replace("<!--ssr-data-->", "");
257
- }
258
-
259
- function matchRenderMode(url) {
260
- const path = url.split("?")[0];
261
- if (RENDER_MODES[path]) return RENDER_MODES[path];
262
- for (const [pattern, mode] of Object.entries(RENDER_MODES)) {
263
- if (pattern.includes("*")) {
264
- const escaped = pattern.replace(/[.+?^\${}()|[\\]\\\\]/g, "\\\\$&");
265
- const re = new RegExp("^" + escaped.replace(/\\*/g, ".*") + "$");
266
- if (re.test(path)) return mode;
267
- }
268
- }
269
- return null;
270
- }
271
-
272
- const app = new Hono();
273
- ${generateProxyCode(ctx.proxies ?? [])}
274
- ${setupCall}
275
- ${opts.platformMiddleware ?? ""}
276
-
277
- // \u5185\u90E8 fetch \u56DE\u73AF\uFF1ASSR \u63A7\u5236\u5668\u7684 fetch \u8BF7\u6C42\u76F4\u63A5\u8D70 Hono \u5185\u5B58\u8DEF\u7531
278
- // \u6DF1\u5EA6\u901A\u8FC7\u8BF7\u6C42\u5934\u4F20\u9012\uFF0C\u5E76\u53D1\u5B89\u5168\u4E14\u80FD\u8DE8\u6E32\u67D3\u6B63\u786E\u8FFD\u8E2A\u9012\u5F52
279
- const _SSR_DEPTH_HEADER = "x-ssr-depth";
280
- const _MAX_SSR_DEPTH = 5;
281
-
282
- function _createInternalFetch(depth) {
283
- return function(input, init) {
284
- if (typeof input === "string" && input.startsWith("/")) {
285
- const req = new Request("http://localhost" + input, init);
286
- req.headers.set(_SSR_DEPTH_HEADER, String(depth));
287
- return app.fetch(req);
288
- }
289
- return globalThis.fetch(input, init);
290
- };
291
- }
292
-
293
- app.get("*", async (c) => {
294
- // \u9012\u5F52\u6DF1\u5EA6\u4FDD\u62A4\uFF1A\u4ECE\u8BF7\u6C42\u5934\u8BFB\u53D6 SSR \u6DF1\u5EA6
295
- const _ssrDepth = parseInt(c.req.header(_SSR_DEPTH_HEADER) || "0", 10);
296
- if (_ssrDepth >= _MAX_SSR_DEPTH) {
297
- return c.text("SSR recursion loop detected", 508);
298
- }
299
-
300
- const url = c.req.path + (c.req.url.includes("?") ? "?" + c.req.url.split("?")[1] : "");
301
- try {
302
- const locale = parseAcceptLanguage(c.req.header("accept-language"));
303
-
304
- // Vite \u914D\u7F6E\u7EA7\u522B\u8986\u76D6: CSR \u76F4\u63A5\u8FD4\u56DE\u7A7A\u58F3
305
- const overrideMode = matchRenderMode(url);
306
- if (overrideMode === "csr") {
307
- return c.html(injectCSRShell(TEMPLATE, locale));
308
- }
309
-
310
- // ISR \u7F13\u5B58\u547D\u4E2D\uFF08key \u542B locale\uFF0C\u907F\u514D\u8DE8\u8BED\u8A00\u7F13\u5B58\u6C61\u67D3\uFF09
311
- const _cacheKey = locale + ":" + url;
312
- const cached = await platformCacheGet(_cacheKey);
313
- if (cached) return c.html(cached);
314
-
315
- const { html: appHtml, head, css, serverData, renderMode } = await render(url, locale, { fetch: _createInternalFetch(_ssrDepth + 1) });
316
-
317
- // \u8DEF\u7531\u7EA7 CSR
318
- if (renderMode === "csr") {
319
- return c.html(injectCSRShell(TEMPLATE, locale));
320
- }
321
-
322
- const serializedData = serializeServerData(serverData);
323
- const finalHtml = injectSSR(TEMPLATE, locale, head, css, appHtml, serializedData);
324
-
325
- // Prerender ISR \u7F13\u5B58\uFF08\u5305\u62EC Vite \u914D\u7F6E\u8986\u76D6\u548C\u8DEF\u7531\u7EA7\uFF09
326
- if (renderMode === "prerender" || overrideMode === "prerender") {
327
- await platformCacheSet(_cacheKey, finalHtml);
328
- ${opts.platformPrerenderResponseHook ?? ""}
329
- }
330
-
331
- return c.html(finalHtml);
332
- } catch (e) {
333
- console.error("[SSR Error]", e);
334
- return c.text("Internal Server Error", 500);
335
- }
336
- });
337
-
338
- ${opts.platformExport}
339
- `;
340
- }
341
- async function buildBundle(ctx, opts) {
342
- await ctx.vite.build({
343
- root: ctx.root,
344
- build: {
345
- ssr: opts.entry,
346
- outDir: opts.outDir,
347
- emptyOutDir: true,
348
- target: opts.target ?? "node18",
349
- rollupOptions: {
350
- output: { entryFileNames: opts.fileName ?? "index.mjs" }
351
- }
352
- },
353
- ssr: {
354
- noExternal: opts.noExternal !== false,
355
- external: opts.external ?? BUILD_TOOL_EXTERNALS
356
- },
357
- resolve: ctx.resolvedResolve,
358
- css: ctx.resolvedCss
359
- });
360
- }
361
- function copyStaticAssets(ctx, destDir, opts) {
362
- const { fs, path } = ctx;
363
- fs.cpSync(path.resolve(ctx.root, "dist/client"), destDir, {
364
- recursive: true
365
- });
366
- if (opts?.excludeHtml !== false) {
367
- fs.rmSync(path.join(destDir, "index.html"), { force: true });
368
- }
369
- }
370
- async function prerenderRoutes(ctx) {
371
- const { fs, path, root, vite } = ctx;
372
- const { pathToFileURL } = await import(
373
- /* @vite-ignore */
374
- "url"
375
- );
376
- const routesExport = ctx.bootstrapEntry ?? "src/lib/bootstrap.ts";
377
- let routes = [];
378
- const routesFileExists = fs.existsSync(path.resolve(root, routesExport));
379
- if (routesFileExists) {
380
- await vite.build({
381
- root,
382
- build: {
383
- ssr: routesExport,
384
- outDir: path.resolve(root, "dist/server"),
385
- emptyOutDir: false,
386
- rollupOptions: {
387
- output: { entryFileNames: "_routes_prerender.mjs" }
388
- }
389
- },
390
- resolve: ctx.resolvedResolve
391
- });
392
- const routesPath = pathToFileURL(
393
- path.resolve(root, "dist/server/_routes_prerender.mjs")
394
- ).href;
395
- const routesMod = await import(
396
- /* @vite-ignore */
397
- routesPath
398
- );
399
- routes = routesMod.routes ?? routesMod.default ?? [];
400
- fs.rmSync(path.resolve(root, "dist/server/_routes_prerender.mjs"), {
401
- force: true
402
- });
403
- }
404
- const prerenderPaths = /* @__PURE__ */ new Set();
405
- for (const r of routes) {
406
- if (r.renderMode === "prerender" && r.path && !r.path.includes(":")) {
407
- prerenderPaths.add(r.path);
408
- }
409
- }
410
- if (ctx.renderModes) {
411
- for (const [pattern, mode] of Object.entries(ctx.renderModes)) {
412
- if (mode === "prerender" && !pattern.includes("*") && !pattern.includes(":")) {
413
- prerenderPaths.add(pattern);
414
- }
415
- }
416
- }
417
- if (prerenderPaths.size === 0) return [];
418
- const ssrPath = pathToFileURL(
419
- path.resolve(root, "dist/server/ssr.js")
420
- ).href;
421
- const ssrModule = await import(
422
- /* @vite-ignore */
423
- ssrPath
424
- );
425
- const results = [];
426
- for (const routePath of prerenderPaths) {
427
- for (const locale of ctx.locales) {
428
- const url = locale === ctx.defaultLocale ? routePath : `/${locale}${routePath === "/" ? "" : routePath}`;
429
- try {
430
- const {
431
- html: appHtml,
432
- head,
433
- css,
434
- serverData
435
- } = await ssrModule.render(url, locale);
436
- const serializedData = ssrModule.serializeServerData(serverData);
437
- const finalHtml = ctx.templateHtml.replace("<!--ssr-lang-->", locale).replace(
438
- "<!--ssr-head-->",
439
- head + "\n<style>" + css + "</style>"
440
- ).replace("<!--ssr-body-->", appHtml).replace(
441
- "<!--ssr-data-->",
442
- '<script id="serialized-server-data" type="application/json">' + serializedData + "</script>"
443
- );
444
- results.push({ url, html: finalHtml });
445
- } catch (e) {
446
- console.warn(` [prerender] Failed to render ${url}:`, e);
447
- }
448
- }
449
- }
450
- if (results.length > 0) {
451
- console.log(
452
- ` Pre-rendered ${results.length} pages (${prerenderPaths.size} routes \xD7 ${ctx.locales.length} locales)
453
- `
454
- );
455
- }
456
- return results;
457
- }
458
-
459
- // ../server/src/adapters/cloudflare.ts
460
- function cloudflareAdapter() {
461
- return {
462
- name: "cloudflare",
463
- async build(ctx) {
464
- const { fs, path, root } = ctx;
465
- const outputDir = path.resolve(root, "dist/cloudflare");
466
- fs.rmSync(outputDir, { recursive: true, force: true });
467
- const entrySource = generateSSREntry(ctx, {
468
- platformImport: ``,
469
- platformExport: `export default app;`,
470
- // Cloudflare Cache API — 持久化 ISR 缓存到 CDN 边缘节点
471
- platformCache: `
472
- const ISR_CACHE_TTL = 3600; // 1 hour
473
- async function platformCacheGet(url) {
474
- try {
475
- const cache = caches.default;
476
- const cacheKey = new Request("https://isr-cache/" + encodeURIComponent(url));
477
- const resp = await cache.match(cacheKey);
478
- if (resp) return await resp.text();
479
- } catch {}
480
- return null;
481
- }
482
- async function platformCacheSet(url, html) {
483
- try {
484
- const cache = caches.default;
485
- const cacheKey = new Request("https://isr-cache/" + encodeURIComponent(url));
486
- const resp = new Response(html, {
487
- headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "public, max-age=" + ISR_CACHE_TTL },
488
- });
489
- await cache.put(cacheKey, resp);
490
- } catch {}
491
- }`
492
- });
493
- const tempEntry = path.resolve(root, ".cf-entry.tmp.mjs");
494
- fs.writeFileSync(tempEntry, entrySource);
495
- try {
496
- await buildBundle(ctx, {
497
- entry: ".cf-entry.tmp.mjs",
498
- outDir: outputDir,
499
- target: "es2022",
500
- fileName: "_worker.js"
501
- // 使用默认 external(vite/esbuild/rollup/fsevents/lightningcss)
502
- // 这些构建工具运行时不需要,且 fsevents 是 macOS .node 原生二进制无法打包
503
- });
504
- copyStaticAssets(ctx, path.resolve(outputDir, "assets"));
505
- const prerendered = await prerenderRoutes(ctx);
506
- for (const { url, html } of prerendered) {
507
- const filePath = url === "/" ? path.join(outputDir, "assets", "index.html") : path.join(outputDir, "assets", url, "index.html");
508
- fs.mkdirSync(path.resolve(filePath, ".."), {
509
- recursive: true
510
- });
511
- fs.writeFileSync(filePath, html);
512
- }
513
- } finally {
514
- fs.rmSync(tempEntry, { force: true });
515
- }
516
- console.log(" Cloudflare output \u2192 dist/cloudflare/\n");
517
- }
518
- };
519
- }
520
-
521
- // ../server/src/adapters/netlify.ts
522
- function netlifyAdapter() {
523
- return {
524
- name: "netlify",
525
- async build(ctx) {
526
- const { fs, path, root } = ctx;
527
- const funcDir = path.resolve(
528
- root,
529
- ".netlify/functions-internal/ssr"
530
- );
531
- fs.rmSync(path.resolve(root, ".netlify"), {
532
- recursive: true,
533
- force: true
534
- });
535
- const entrySource = generateSSREntry(ctx, {
536
- platformImport: `import { handle } from "hono/netlify";`,
537
- platformExport: `export default handle(app);
538
- export const config = { path: "/*", preferStatic: true };`,
539
- // Netlify CDN 缓存 — 使用 Netlify-CDN-Cache-Control 头做 ISR
540
- platformCache: `
541
- const ISR_SWR_TTL = 3600;
542
- const ISR_CACHE_MAX = 1000;
543
- const _isrMap = new Map();
544
- async function platformCacheGet(url) {
545
- return _isrMap.get(url) ?? null;
546
- }
547
- async function platformCacheSet(url, html) {
548
- if (_isrMap.size >= ISR_CACHE_MAX) {
549
- const first = _isrMap.keys().next().value;
550
- _isrMap.delete(first);
551
- }
552
- _isrMap.set(url, html);
553
- }`,
554
- platformPrerenderResponseHook: `c.header("Cache-Control", "public, max-age=0, must-revalidate");
555
- c.header("Netlify-CDN-Cache-Control", "public, max-age=" + ISR_SWR_TTL + ", stale-while-revalidate=" + ISR_SWR_TTL + ", durable");`
556
- });
557
- const tempEntry = path.resolve(root, ".netlify-entry.tmp.mjs");
558
- fs.writeFileSync(tempEntry, entrySource);
559
- try {
560
- await buildBundle(ctx, {
561
- entry: ".netlify-entry.tmp.mjs",
562
- outDir: funcDir,
563
- target: "node18"
564
- });
565
- } finally {
566
- fs.rmSync(tempEntry, { force: true });
567
- }
568
- const redirects = `/* /.netlify/functions/ssr 200
569
- `;
570
- fs.writeFileSync(
571
- path.resolve(root, "dist/client/_redirects"),
572
- redirects
573
- );
574
- const prerendered = await prerenderRoutes(ctx);
575
- const clientDir = path.resolve(root, "dist/client");
576
- for (const { url, html } of prerendered) {
577
- const filePath = url === "/" ? path.join(clientDir, "index.html") : path.join(clientDir, url, "index.html");
578
- fs.mkdirSync(path.resolve(filePath, ".."), { recursive: true });
579
- fs.writeFileSync(filePath, html);
580
- }
581
- console.log(
582
- " Netlify output \u2192 .netlify/functions-internal/ssr/\n Publish dir: dist/client/\n"
583
- );
584
- }
585
- };
586
- }
587
-
588
- // ../server/src/adapters/node.ts
589
- function nodeAdapter() {
590
- return {
591
- name: "node",
592
- async build(ctx) {
593
- const { fs, path, root } = ctx;
594
- const entrySource = generateSSREntry(ctx, {
595
- platformImport: `import { serve } from "@hono/node-server";
596
- import { readFileSync, existsSync } from "node:fs";
597
- import { resolve, dirname } from "node:path";
598
- import { fileURLToPath } from "node:url";`,
599
- platformMiddleware: `
600
- // \u9884\u6E32\u67D3\u6587\u4EF6\u4E2D\u95F4\u4EF6\uFF1A\u68C0\u67E5 dist/prerender/ \u4E0B\u662F\u5426\u6709\u5BF9\u5E94\u7684\u9759\u6001 HTML
601
- const __entry_dirname = dirname(fileURLToPath(import.meta.url));
602
- const prerenderDir = resolve(__entry_dirname, "../prerender");
603
-
604
- app.use("*", async (c, next) => {
605
- const urlPath = c.req.path;
606
- const candidates = [
607
- resolve(prerenderDir, "." + urlPath, "index.html"),
608
- resolve(prerenderDir, "." + urlPath + ".html"),
609
- ];
610
- if (urlPath === "/") candidates.unshift(resolve(prerenderDir, "index.html"));
611
- for (const f of candidates) {
612
- if (existsSync(f)) {
613
- const html = readFileSync(f, "utf-8");
614
- return c.html(html);
615
- }
616
- }
617
- await next();
618
- });
619
- `,
620
- platformExport: `
621
- const port = +(process.env.PORT || 3000);
622
- serve({ fetch: app.fetch, port }, (info) => {
623
- console.log(\`Server running at http://localhost:\${info.port}\`);
624
- });
625
- `
626
- });
627
- const tempEntry = path.resolve(root, ".node-entry.tmp.mjs");
628
- fs.writeFileSync(tempEntry, entrySource);
629
- try {
630
- await buildBundle(ctx, {
631
- entry: ".node-entry.tmp.mjs",
632
- outDir: path.resolve(root, "dist/server"),
633
- target: "node18"
634
- });
635
- } finally {
636
- fs.rmSync(tempEntry, { force: true });
637
- }
638
- const prerendered = await prerenderRoutes(ctx);
639
- if (prerendered.length > 0) {
640
- const prerenderDir = path.resolve(root, "dist/prerender");
641
- fs.mkdirSync(prerenderDir, { recursive: true });
642
- for (const { url, html } of prerendered) {
643
- const filePath = url === "/" ? path.join(prerenderDir, "index.html") : path.join(prerenderDir, url, "index.html");
644
- fs.mkdirSync(path.resolve(filePath, ".."), {
645
- recursive: true
646
- });
647
- fs.writeFileSync(filePath, html);
648
- }
649
- }
650
- console.log(
651
- " Node output \u2192 dist/server/index.mjs\n Run: node dist/server/index.mjs\n"
652
- );
653
- }
654
- };
655
- }
656
-
657
- // ../server/src/adapters/static.ts
658
- function staticAdapter(opts = {}) {
659
- return {
660
- name: "static",
661
- async build(ctx) {
662
- const { fs, path, root, vite } = ctx;
663
- const outputDir = path.resolve(root, "dist/static");
664
- fs.rmSync(outputDir, { recursive: true, force: true });
665
- fs.mkdirSync(outputDir, { recursive: true });
666
- const { pathToFileURL } = await import(
667
- /* @vite-ignore */
668
- "url"
669
- );
670
- const ssrPath = pathToFileURL(
671
- path.resolve(root, "dist/server/ssr.js")
672
- ).href;
673
- const ssrModule = await import(
674
- /* @vite-ignore */
675
- ssrPath
676
- );
677
- ctx.copyStaticAssets(outputDir, { excludeHtml: true });
678
- const { paths: routePaths, defs: routeDefs } = await extractRoutesWithModes(ctx, opts);
679
- const allUrls = [];
680
- for (const routePath of routePaths) {
681
- for (const locale of ctx.locales) {
682
- const url = locale === ctx.defaultLocale ? routePath : `/${locale}${routePath === "/" ? "" : routePath}`;
683
- allUrls.push(url);
684
- }
685
- }
686
- console.log(
687
- ` Pre-rendering ${allUrls.length} pages (${routePaths.length} routes \xD7 ${ctx.locales.length} locales)...
688
- `
689
- );
690
- for (const url of allUrls) {
691
- try {
692
- const locale = inferLocale(
693
- url,
694
- ctx.locales,
695
- ctx.defaultLocale
696
- );
697
- const routeDef = routeDefs.find(
698
- (r) => r.path === stripLocalePrefix(url, ctx.locales)
699
- );
700
- const mode = resolveRenderMode(
701
- stripLocalePrefix(url, ctx.locales),
702
- routeDef?.renderMode,
703
- ctx.renderModes
704
- );
705
- let finalHtml;
706
- if (mode === "csr") {
707
- finalHtml = injectCSRShellForStatic(
708
- ctx.templateHtml,
709
- locale
710
- );
711
- } else {
712
- const {
713
- html: appHtml,
714
- head,
715
- css,
716
- serverData
717
- } = await ssrModule.render(url, locale);
718
- const serializedData = ssrModule.serializeServerData(serverData);
719
- finalHtml = injectSSRForStatic(
720
- ctx.templateHtml,
721
- locale,
722
- head,
723
- css,
724
- appHtml,
725
- serializedData
726
- );
727
- }
728
- const filePath = url === "/" ? path.join(outputDir, "index.html") : path.join(outputDir, url, "index.html");
729
- fs.mkdirSync(path.resolve(filePath, ".."), {
730
- recursive: true
731
- });
732
- fs.writeFileSync(filePath, finalHtml);
733
- } catch (e) {
734
- console.warn(` [static] Failed to render ${url}:`, e);
735
- }
736
- }
737
- console.log(` Static output \u2192 dist/static/
738
- `);
739
- }
740
- };
741
- }
742
- async function extractRoutesWithModes(ctx, opts) {
743
- const routesFile = opts.routesExport ?? "src/lib/bootstrap.ts";
744
- const paths = [];
745
- const defs = [];
746
- try {
747
- const { pathToFileURL } = await import(
748
- /* @vite-ignore */
749
- "url"
750
- );
751
- await ctx.vite.build({
752
- root: ctx.root,
753
- build: {
754
- ssr: routesFile,
755
- outDir: ctx.path.resolve(ctx.root, "dist/server"),
756
- emptyOutDir: false,
757
- rollupOptions: {
758
- output: { entryFileNames: "_routes.mjs" }
759
- }
760
- },
761
- resolve: ctx.resolvedResolve
762
- });
763
- const routesPath = pathToFileURL(
764
- ctx.path.resolve(ctx.root, "dist/server/_routes.mjs")
765
- ).href;
766
- const routesMod = await import(
767
- /* @vite-ignore */
768
- routesPath
769
- );
770
- const routes = routesMod.routes ?? routesMod.default;
771
- if (Array.isArray(routes)) {
772
- for (const r of routes) {
773
- if (r.path && !r.path.includes(":")) {
774
- paths.push(r.path);
775
- defs.push({ path: r.path, renderMode: r.renderMode });
776
- }
777
- }
778
- }
779
- ctx.fs.rmSync(ctx.path.resolve(ctx.root, "dist/server/_routes.mjs"), {
780
- force: true
781
- });
782
- } catch (e) {
783
- console.warn(
784
- ` [static] Could not load routes from "${routesFile}". Using "/" only.`,
785
- e
786
- );
787
- if (paths.length === 0) paths.push("/");
788
- }
789
- if (opts.dynamicRoutes) {
790
- for (const r of opts.dynamicRoutes) {
791
- if (!paths.includes(r)) paths.push(r);
792
- }
793
- }
794
- if (paths.length === 0) paths.push("/");
795
- return { paths, defs };
796
- }
797
- function inferLocale(url, locales, defaultLocale) {
798
- const segments = url.split("/").filter(Boolean);
799
- if (segments.length > 0 && locales.includes(segments[0])) {
800
- return segments[0];
801
- }
802
- return defaultLocale;
803
- }
804
- function injectSSRForStatic(template, locale, head, css, html, serializedData) {
805
- return template.replace("<!--ssr-lang-->", locale).replace("<!--ssr-head-->", head + "\n<style>" + css + "</style>").replace("<!--ssr-body-->", html).replace(
806
- "<!--ssr-data-->",
807
- '<script id="serialized-server-data" type="application/json">' + serializedData + "</script>"
808
- );
809
- }
810
- function injectCSRShellForStatic(template, locale) {
811
- return template.replace("<!--ssr-lang-->", locale).replace("<!--ssr-head-->", "").replace("<!--ssr-body-->", "").replace("<!--ssr-data-->", "");
812
- }
813
- function stripLocalePrefix(url, locales) {
814
- const segments = url.split("/").filter(Boolean);
815
- if (segments.length > 0 && locales.includes(segments[0])) {
816
- const rest = segments.slice(1).join("/");
817
- return rest ? `/${rest}` : "/";
818
- }
819
- return url;
820
- }
821
- function resolveRenderMode(routePath, routeRenderMode, renderModes) {
822
- if (renderModes) {
823
- if (renderModes[routePath]) return renderModes[routePath];
824
- for (const [pattern, mode] of Object.entries(renderModes)) {
825
- if (pattern.includes("*")) {
826
- const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
827
- const re = new RegExp("^" + escaped.replace(/\*/g, ".*") + "$");
828
- if (re.test(routePath)) return mode;
829
- }
830
- }
831
- }
832
- return routeRenderMode ?? "ssr";
833
- }
834
-
835
- // ../server/src/adapters/vercel.ts
836
- function vercelAdapter() {
837
- return {
838
- name: "vercel",
839
- async build(ctx) {
840
- const { fs, path, root } = ctx;
841
- const outputDir = path.resolve(root, ".vercel/output");
842
- fs.rmSync(outputDir, { recursive: true, force: true });
843
- const entrySource = generateSSREntry(ctx, {
844
- platformImport: `import { getRequestListener } from "@hono/node-server";`,
845
- platformExport: [
846
- `const _listener = getRequestListener(app.fetch);`,
847
- `export default (req, res) => {`,
848
- ` const m = req.headers["x-now-route-matches"];`,
849
- ` if (typeof m === "string") {`,
850
- ` try {`,
851
- ` const p = new URLSearchParams(m);`,
852
- ` const c = p.get("1");`,
853
- ` if (c != null) {`,
854
- ` const qi = (req.url || "").indexOf("?");`,
855
- ` const qs = qi !== -1 ? req.url.slice(qi) : "";`,
856
- ` req.url = "/" + decodeURIComponent(c) + qs;`,
857
- ` }`,
858
- ` } catch {}`,
859
- ` }`,
860
- ` return _listener(req, res);`,
861
- `};`
862
- ].join("\n")
863
- });
864
- const tempEntry = path.resolve(root, ".vercel-entry.tmp.mjs");
865
- fs.writeFileSync(tempEntry, entrySource);
866
- try {
867
- const funcDir = path.resolve(
868
- root,
869
- ".vercel/output/functions/ssr.func"
870
- );
871
- await buildBundle(ctx, {
872
- entry: ".vercel-entry.tmp.mjs",
873
- outDir: funcDir,
874
- target: "node18"
875
- });
876
- fs.writeFileSync(
877
- path.resolve(funcDir, ".vc-config.json"),
878
- JSON.stringify(
879
- {
880
- runtime: "nodejs20.x",
881
- handler: "index.mjs",
882
- launcherType: "Nodejs"
883
- },
884
- null,
885
- 2
886
- )
887
- );
888
- copyStaticAssets(
889
- ctx,
890
- path.resolve(root, ".vercel/output/static")
891
- );
892
- fs.writeFileSync(
893
- path.resolve(root, ".vercel/output/config.json"),
894
- JSON.stringify(
895
- {
896
- version: 3,
897
- routes: [
898
- { handle: "filesystem" },
899
- { src: "/(.*)", dest: "/ssr" }
900
- ]
901
- },
902
- null,
903
- 2
904
- )
905
- );
906
- } finally {
907
- fs.rmSync(tempEntry, { force: true });
908
- }
909
- const prerendered = await prerenderRoutes(ctx);
910
- const staticDir = path.resolve(root, ".vercel/output/static");
911
- for (const { url, html } of prerendered) {
912
- const filePath = url === "/" ? path.join(staticDir, "index.html") : path.join(staticDir, url, "index.html");
913
- fs.mkdirSync(path.resolve(filePath, ".."), { recursive: true });
914
- fs.writeFileSync(filePath, html);
915
- }
916
- if (prerendered.length > 0) {
917
- const configPath = path.resolve(
918
- root,
919
- ".vercel/output/config.json"
920
- );
921
- const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
922
- config.overrides = config.overrides ?? {};
923
- for (const { url } of prerendered) {
924
- const key = url === "/" ? "index.html" : `${url.replace(/^\//, "")}/index.html`;
925
- config.overrides[key] = {
926
- path: url === "/" ? "/" : url,
927
- contentType: "text/html; charset=utf-8"
928
- };
929
- }
930
- fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
931
- }
932
- console.log(" Vercel output \u2192 .vercel/output/\n");
933
- }
934
- };
935
- }
936
-
937
- // ../server/src/adapters/resolve.ts
938
- function resolveAdapter(value) {
939
- if (typeof value !== "string") return value;
940
- switch (value) {
941
- case "vercel":
942
- return vercelAdapter();
943
- case "cloudflare":
944
- return cloudflareAdapter();
945
- case "netlify":
946
- return netlifyAdapter();
947
- case "node":
948
- return nodeAdapter();
949
- case "static":
950
- return staticAdapter();
951
- case "auto":
952
- return autoAdapter();
953
- default:
954
- throw new Error(
955
- `[finesoft] Unknown adapter: "${value}". Available: vercel, cloudflare, netlify, node, static, auto`
956
- );
957
- }
958
- }
959
-
960
- // ../server/src/adapters/auto.ts
961
- function autoAdapter() {
962
- return {
963
- name: "auto",
964
- async build(ctx) {
965
- const detected = detectPlatform();
966
- console.log(` [auto] Detected platform: ${detected}
967
- `);
968
- const adapter = resolveAdapter(detected);
969
- return adapter.build(ctx);
970
- }
971
- };
972
- }
973
- function detectPlatform() {
974
- if (process.env.VERCEL) return "vercel";
975
- if (process.env.CF_PAGES) return "cloudflare";
976
- if (process.env.NETLIFY) return "netlify";
977
- return "node";
978
- }
979
-
980
- // ../server/src/create-server.ts
981
- import { Hono as Hono2 } from "hono";
982
-
983
- // ../server/src/runtime.ts
984
- function detectRuntime() {
985
- return {
986
- isDeno: typeof globalThis.Deno !== "undefined",
987
- isBun: typeof globalThis.Bun !== "undefined",
988
- isVercel: !!process.env.VERCEL,
989
- isProduction: process.env.NODE_ENV === "production"
990
- };
991
- }
992
- async function resolveRoot(importMetaUrl, levelsUp = 0) {
993
- const isDeno = typeof globalThis.Deno !== "undefined";
994
- if (isDeno) {
995
- let url = new URL(importMetaUrl);
996
- for (let i = 0; i < levelsUp; i++) {
997
- url = new URL("..", url);
998
- }
999
- return url.pathname;
1000
- }
1001
- const { dirname, resolve, normalize } = await import(
1002
- /* @vite-ignore */
1003
- "path"
1004
- );
1005
- const { fileURLToPath } = await import(
1006
- /* @vite-ignore */
1007
- "url"
1008
- );
1009
- let dir = normalize(dirname(fileURLToPath(importMetaUrl)));
1010
- for (let i = 0; i < levelsUp; i++) {
1011
- dir = resolve(dir, "..");
1012
- }
1013
- return dir;
1014
- }
1015
-
1016
- // ../server/src/start.ts
1017
- import { Hono } from "hono";
1018
- async function startServer(options) {
1019
- const {
1020
- app,
1021
- root,
1022
- port = 3e3,
1023
- isProduction,
1024
- vite,
1025
- routes,
1026
- locales,
1027
- ssrEntryPath
1028
- } = options;
1029
- const { isDeno, isBun, isVercel } = options.runtime ?? detectRuntime();
1030
- function printStartupBanner() {
1031
- const lines = [
1032
- `
1033
- Server running at http://localhost:${port}
1034
- `
1035
- ];
1036
- if (routes && routes.length > 0) {
1037
- lines.push(" Routes:");
1038
- for (const r of routes) {
1039
- lines.push(` ${r}`);
1040
- }
1041
- lines.push("");
1042
- }
1043
- if (locales && locales.length > 0) {
1044
- lines.push(` Locales: ${locales.join(", ")}`);
1045
- }
1046
- if (ssrEntryPath) {
1047
- lines.push(` SSR Entry: ${ssrEntryPath}`);
1048
- }
1049
- if (locales?.length || ssrEntryPath) {
1050
- lines.push("");
1051
- }
1052
- console.log(lines.join("\n"));
1053
- }
1054
- if (isVercel) {
1055
- return { vite };
1056
- }
1057
- if (!isProduction) {
1058
- let devVite = vite;
1059
- if (!devVite) {
1060
- const { createServer: createViteServer } = await import(
1061
- /* @vite-ignore */
1062
- "vite"
1063
- );
1064
- devVite = await createViteServer({
1065
- root,
1066
- server: { middlewareMode: true },
1067
- appType: "custom"
1068
- });
1069
- }
1070
- const { getRequestListener } = await import(
1071
- /* @vite-ignore */
1072
- "@hono/node-server"
1073
- );
1074
- const { createServer: createServer2 } = await import(
1075
- /* @vite-ignore */
1076
- "http"
1077
- );
1078
- const listener = getRequestListener(app.fetch);
1079
- const server = createServer2((req, res) => {
1080
- devVite.middlewares(req, res, () => listener(req, res));
1081
- });
1082
- server.listen(port, () => {
1083
- printStartupBanner();
1084
- });
1085
- return { vite: devVite };
1086
- }
1087
- if (isDeno) {
1088
- globalThis.Deno.serve({ port }, app.fetch);
1089
- } else if (isBun) {
1090
- } else {
1091
- const { serveStatic } = await import(
1092
- /* @vite-ignore */
1093
- "@hono/node-server/serve-static"
1094
- );
1095
- const { resolve } = await import(
1096
- /* @vite-ignore */
1097
- "path"
1098
- );
1099
- const prodApp = new Hono();
1100
- const clientDir = resolve(root, "dist/client");
1101
- prodApp.use(
1102
- "/*",
1103
- serveStatic({
1104
- root: clientDir,
1105
- // 禁止目录路径自动提供 index.html,让其 fall through 到 SSR
1106
- rewriteRequestPath: (path) => path.endsWith("/") ? "/__nosuchfile__" : path
1107
- })
1108
- );
1109
- prodApp.route("/", app);
1110
- const { serve } = await import(
1111
- /* @vite-ignore */
1112
- "@hono/node-server"
1113
- );
1114
- serve({ fetch: prodApp.fetch, port }, () => {
1115
- printStartupBanner();
1116
- });
1117
- }
1118
- return { vite };
1119
- }
1120
-
1121
- // ../server/src/create-server.ts
1122
- async function createServer(config = {}) {
1123
- const {
1124
- root: rootOverride,
1125
- locales,
1126
- defaultLocale,
1127
- port = Number(process.env.PORT) || 3e3,
1128
- setup,
1129
- proxies,
1130
- ssr
1131
- } = config;
1132
- const root = rootOverride ?? process.cwd();
1133
- const { existsSync } = await import(
1134
- /* @vite-ignore */
1135
- "fs"
1136
- );
1137
- const { resolve } = await import(
1138
- /* @vite-ignore */
1139
- "path"
1140
- );
1141
- const envPath = resolve(root, ".env");
1142
- if (existsSync(envPath)) {
1143
- try {
1144
- const { config: dotenvConfig } = await import(
1145
- /* @vite-ignore */
1146
- "dotenv"
1147
- );
1148
- dotenvConfig({ path: envPath });
1149
- } catch {
1150
- }
1151
- }
1152
- const runtime = detectRuntime();
1153
- let vite;
1154
- if (!runtime.isProduction && !runtime.isVercel) {
1155
- const { createServer: createViteServer } = await import(
1156
- /* @vite-ignore */
1157
- "vite"
1158
- );
1159
- vite = await createViteServer({
1160
- root,
1161
- server: { middlewareMode: true },
1162
- appType: "custom"
1163
- });
1164
- }
1165
- const app = new Hono2();
1166
- if (proxies?.length) {
1167
- registerProxyRoutes(app, proxies);
1168
- }
1169
- if (setup) {
1170
- await setup(app);
1171
- }
1172
- const ssrApp = createSSRApp({
1173
- root,
1174
- vite,
1175
- isProduction: runtime.isProduction,
1176
- supportedLocales: locales,
1177
- defaultLocale,
1178
- parentFetch: app.fetch.bind(app),
1179
- ...ssr
1180
- });
1181
- app.route("/", ssrApp);
1182
- await startServer({
1183
- app,
1184
- root,
1185
- port,
1186
- isProduction: runtime.isProduction,
1187
- vite,
1188
- runtime,
1189
- locales,
1190
- ssrEntryPath: ssr?.ssrEntryPath
1191
- });
1192
- return { app, vite, runtime };
1193
- }
1194
-
1195
- // ../server/src/vite-plugin.ts
1196
- function resolveSetupFn(mod) {
1197
- if (typeof mod.default === "function") return mod.default;
1198
- if (typeof mod.setup === "function") return mod.setup;
1199
- const first = Object.values(mod).find((v) => typeof v === "function");
1200
- return first ?? null;
1201
- }
1202
- function matchRenderModeConfig(url, renderModes) {
1203
- if (!renderModes) return null;
1204
- const path = url.split("?")[0];
1205
- if (renderModes[path]) return renderModes[path];
1206
- for (const [pattern, mode] of Object.entries(renderModes)) {
1207
- if (pattern.includes("*")) {
1208
- const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
1209
- const re = new RegExp("^" + escaped.replace(/\*/g, ".*") + "$");
1210
- if (re.test(path)) return mode;
1211
- }
1212
- }
1213
- return null;
1214
- }
1215
- function finesoftFrontViteConfig(options = {}) {
1216
- const ssrEntry = options.ssr?.entry ?? "src/ssr.ts";
1217
- let root = process.cwd();
1218
- let resolvedCommand;
1219
- let resolvedResolve;
1220
- let resolvedCss;
1221
- const CSS_EXTENSIONS = /\.(css|scss|less|sass|styl|stylus|pcss|postcss)($|\?)/;
1222
- return {
1223
- name: "finesoft-front",
1224
- config(userConfig, env) {
1225
- const overrides = {
1226
- appType: "custom"
1227
- };
1228
- if (env.command === "build" && !process.env.__FINESOFT_SUB_BUILD__) {
1229
- overrides.build = {
1230
- outDir: userConfig.build?.outDir ?? "dist/client"
1231
- };
1232
- }
1233
- return overrides;
1234
- },
1235
- configResolved(config) {
1236
- resolvedCommand = config.command;
1237
- resolvedResolve = config.resolve;
1238
- resolvedCss = config.css;
1239
- root = config.root;
1240
- },
1241
- /**
1242
- * Dev 模式 CSS 内联 — 消除 SSR 首屏布局抖动
1243
- *
1244
- * Vite dev 模式下,global.scss 等非组件 CSS 通过 JS 模块系统异步加载,
1245
- * 导致 SSR HTML 初次渲染缺少布局关键样式(box-sizing、flex 布局、padding-top 等)。
1246
- *
1247
- * 此 hook 在 HTML 模板变换阶段(SSR 渲染之前):
1248
- * 1. 找到浏览器入口脚本(排除 /@vite/client 等内部脚本)
1249
- * 2. 编译入口脚本,填充 Vite 模块图
1250
- * 3. 遍历模块图收集所有 CSS 依赖(排除 .svelte 组件 CSS,由 SSR 渲染自行处理)
1251
- * 4. 通过 ssrLoadModule 获取编译后 CSS(SCSS→CSS)
1252
- * 5. 注入 <style data-vite-dev-id> 标签到 <head>
1253
- *
1254
- * data-vite-dev-id 确保 Vite HMR 客户端复用已有标签,避免重复注入。
1255
- */
1256
- transformIndexHtml: {
1257
- order: "pre",
1258
- async handler(html, ctx) {
1259
- const server = ctx.server;
1260
- if (!server) return;
1261
- const urlPath = (ctx.originalUrl || ctx.path || "").split(
1262
- "?"
1263
- )[0];
1264
- if (/\.\w+$/.test(urlPath) && !urlPath.endsWith(".html")) {
1265
- return;
1266
- }
1267
- const scripts = [
1268
- ...html.matchAll(
1269
- /<script\b[^>]*\bsrc=["']([^"']+)["'][^>]*>/g
1270
- )
1271
- ];
1272
- const appEntry = scripts.find((m) => !m[1].startsWith("/@"));
1273
- if (!appEntry) return;
1274
- const browserEntry = appEntry[1];
1275
- try {
1276
- await server.transformRequest(browserEntry);
1277
- } catch {
1278
- return;
1279
- }
1280
- const cssUrls = [];
1281
- const visited = /* @__PURE__ */ new Set();
1282
- function walk(mod) {
1283
- if (!mod?.url || visited.has(mod.url)) return;
1284
- visited.add(mod.url);
1285
- if (CSS_EXTENSIONS.test(mod.url) && !mod.url.includes(".svelte")) {
1286
- cssUrls.push(mod.url);
1287
- }
1288
- if (mod.importedModules) {
1289
- for (const imported of mod.importedModules) {
1290
- walk(imported);
1291
- }
1292
- }
1293
- }
1294
- const mg = server.moduleGraph;
1295
- const browserMod = await mg.getModuleByUrl(browserEntry);
1296
- if (browserMod) walk(browserMod);
1297
- if (cssUrls.length === 0) return;
1298
- const tags = [];
1299
- for (const url of cssUrls) {
1300
- try {
1301
- const mod = await server.ssrLoadModule(url);
1302
- const css = mod?.default;
1303
- if (typeof css === "string" && css.length > 0) {
1304
- tags.push({
1305
- tag: "style",
1306
- attrs: { "data-vite-dev-id": url },
1307
- children: css,
1308
- injectTo: "head"
1309
- });
1310
- }
1311
- } catch {
1312
- }
1313
- }
1314
- return tags;
1315
- }
1316
- },
1317
- // ─── Dev ───────────────────────────────────────────────
1318
- configureServer(server) {
1319
- return async () => {
1320
- const { Hono: HonoClass } = await import(
1321
- /* @vite-ignore */
1322
- "hono"
1323
- );
1324
- const { createSSRApp: createSSRApp2 } = await import("./app-XEMPAI6H.js");
1325
- const { getRequestListener } = await import(
1326
- /* @vite-ignore */
1327
- "@hono/node-server"
1328
- );
1329
- const app = new HonoClass();
1330
- if (options.proxies?.length) {
1331
- registerProxyRoutes(app, options.proxies);
1332
- }
1333
- if (typeof options.setup === "function") {
1334
- await options.setup(app);
1335
- } else if (typeof options.setup === "string") {
1336
- const mod = await server.ssrLoadModule("/" + options.setup);
1337
- const fn = resolveSetupFn(mod);
1338
- if (fn) await fn(app);
1339
- }
1340
- const ssrApp = createSSRApp2({
1341
- root,
1342
- vite: server,
1343
- isProduction: false,
1344
- ssrEntryPath: "/" + ssrEntry,
1345
- supportedLocales: options.locales,
1346
- defaultLocale: options.defaultLocale,
1347
- parentFetch: app.fetch.bind(app),
1348
- renderModes: options.renderModes
1349
- });
1350
- app.route("/", ssrApp);
1351
- const listener = getRequestListener(app.fetch);
1352
- server.middlewares.use((req, res) => {
1353
- listener(req, res);
1354
- });
1355
- };
1356
- },
1357
- // ─── Preview ───────────────────────────────────────────
1358
- configurePreviewServer(server) {
1359
- return async () => {
1360
- const { readFileSync } = await import(
1361
- /* @vite-ignore */
1362
- "fs"
1363
- );
1364
- const { resolve } = await import(
1365
- /* @vite-ignore */
1366
- "path"
1367
- );
1368
- const { pathToFileURL } = await import(
1369
- /* @vite-ignore */
1370
- "url"
1371
- );
1372
- const { Hono: HonoClass } = await import(
1373
- /* @vite-ignore */
1374
- "hono"
1375
- );
1376
- const { injectSSRContent: injectSSRContent2, injectCSRShell: injectCSRShell2 } = await import(
1377
- /* @vite-ignore */
1378
- "./src-XNC7QNVI.js"
1379
- );
1380
- const { parseAcceptLanguage: parseAcceptLanguage2 } = await import("./locale-CAZ4INCX.js");
1381
- const { getRequestListener } = await import(
1382
- /* @vite-ignore */
1383
- "@hono/node-server"
1384
- );
1385
- const app = new HonoClass();
1386
- const isrCache = /* @__PURE__ */ new Map();
1387
- if (options.proxies?.length) {
1388
- registerProxyRoutes(app, options.proxies);
1389
- }
1390
- if (typeof options.setup === "function") {
1391
- await options.setup(app);
1392
- } else if (typeof options.setup === "string") {
1393
- try {
1394
- const setupPath = pathToFileURL(
1395
- resolve(root, "dist/server/setup.mjs")
1396
- ).href;
1397
- const mod = await import(
1398
- /* @vite-ignore */
1399
- setupPath
1400
- );
1401
- const fn = resolveSetupFn(
1402
- mod
1403
- );
1404
- if (fn) await fn(app);
1405
- } catch {
1406
- console.warn(
1407
- "[finesoft] Could not load setup module for preview. API routes disabled."
1408
- );
1409
- }
1410
- }
1411
- const templatePath = resolve(root, "dist/client/index.html");
1412
- const template = readFileSync(templatePath, "utf-8");
1413
- const ssrPath = pathToFileURL(
1414
- resolve(root, "dist/server/ssr.js")
1415
- ).href;
1416
- const ssrModule = await import(
1417
- /* @vite-ignore */
1418
- ssrPath
1419
- );
1420
- app.get("*", async (c) => {
1421
- const ssrDepth = parseInt(
1422
- c.req.header(SSR_DEPTH_HEADER) ?? "0",
1423
- 10
1424
- );
1425
- if (ssrDepth >= MAX_SSR_DEPTH) {
1426
- return c.text("SSR recursion loop detected", 508);
1427
- }
1428
- const url = c.req.path + (c.req.url.includes("?") ? "?" + c.req.url.split("?")[1] : "");
1429
- try {
1430
- const locale = parseAcceptLanguage2(
1431
- c.req.header("accept-language"),
1432
- options.locales,
1433
- options.defaultLocale
1434
- );
1435
- const overrideMode = matchRenderModeConfig(
1436
- url,
1437
- options.renderModes
1438
- );
1439
- if (overrideMode === "csr") {
1440
- return c.html(injectCSRShell2(template, locale));
1441
- }
1442
- const cacheKey = `${locale}:${url}`;
1443
- const cached = isrCache.get(cacheKey);
1444
- if (cached) return c.html(cached);
1445
- const {
1446
- html: appHtml,
1447
- head,
1448
- css,
1449
- serverData,
1450
- renderMode
1451
- } = await ssrModule.render(url, locale, {
1452
- fetch: createInternalFetch(
1453
- app.fetch.bind(app),
1454
- ssrDepth + 1
1455
- )
1456
- });
1457
- if (renderMode === "csr") {
1458
- return c.html(injectCSRShell2(template, locale));
1459
- }
1460
- const serializedData = ssrModule.serializeServerData(serverData);
1461
- const finalHtml = injectSSRContent2({
1462
- template,
1463
- locale,
1464
- head,
1465
- css,
1466
- html: appHtml,
1467
- serializedData
1468
- });
1469
- if (renderMode === "prerender" || overrideMode === "prerender") {
1470
- isrCache.set(cacheKey, finalHtml);
1471
- }
1472
- return c.html(finalHtml);
1473
- } catch (e) {
1474
- console.error("[SSR Preview Error]", e);
1475
- return c.text("Internal Server Error", 500);
1476
- }
1477
- });
1478
- const listener = getRequestListener(app.fetch);
1479
- server.middlewares.use((req, res) => {
1480
- listener(req, res);
1481
- });
1482
- };
1483
- },
1484
- // ─── Build ─────────────────────────────────────────────
1485
- async closeBundle() {
1486
- if (process.env.__FINESOFT_SUB_BUILD__) return;
1487
- if (resolvedCommand !== "build") return;
1488
- process.env.__FINESOFT_SUB_BUILD__ = "1";
1489
- try {
1490
- const vite = await import(
1491
- /* @vite-ignore */
1492
- "vite"
1493
- );
1494
- const fs = await import(
1495
- /* @vite-ignore */
1496
- "fs"
1497
- );
1498
- const path = await import(
1499
- /* @vite-ignore */
1500
- "path"
1501
- );
1502
- console.log("\n Building SSR bundle...\n");
1503
- await vite.build({
1504
- root,
1505
- build: {
1506
- ssr: ssrEntry,
1507
- outDir: "dist/server"
1508
- },
1509
- resolve: resolvedResolve,
1510
- css: resolvedCss
1511
- });
1512
- if (typeof options.setup === "string") {
1513
- console.log(" Building setup module...\n");
1514
- await vite.build({
1515
- root,
1516
- build: {
1517
- ssr: options.setup,
1518
- outDir: "dist/server",
1519
- emptyOutDir: false,
1520
- rollupOptions: {
1521
- output: { entryFileNames: "setup.mjs" }
1522
- }
1523
- },
1524
- resolve: resolvedResolve
1525
- });
1526
- }
1527
- if (options.adapter) {
1528
- const adapter = resolveAdapter(options.adapter);
1529
- const locales = options.locales ?? ["zh", "en"];
1530
- const defaultLocale = options.defaultLocale ?? locales[0] ?? "en";
1531
- const templateHtml = fs.readFileSync(
1532
- path.resolve(root, "dist/client/index.html"),
1533
- "utf-8"
1534
- );
1535
- const ctx = {
1536
- root,
1537
- ssrEntry,
1538
- setupPath: typeof options.setup === "string" ? options.setup : void 0,
1539
- bootstrapEntry: options.bootstrapEntry,
1540
- locales,
1541
- defaultLocale,
1542
- templateHtml,
1543
- renderModes: options.renderModes,
1544
- proxies: options.proxies,
1545
- resolvedResolve,
1546
- resolvedCss,
1547
- vite,
1548
- fs,
1549
- path,
1550
- generateSSREntry(opts) {
1551
- return generateSSREntry(ctx, opts);
1552
- },
1553
- buildBundle(opts) {
1554
- return buildBundle(ctx, opts);
1555
- },
1556
- copyStaticAssets(destDir, opts) {
1557
- return copyStaticAssets(ctx, destDir, opts);
1558
- }
1559
- };
1560
- console.log(` Running adapter: ${adapter.name}...
1561
- `);
1562
- await adapter.build(ctx);
1563
- }
1564
- } finally {
1565
- delete process.env.__FINESOFT_SUB_BUILD__;
1566
- }
1567
- }
1568
- };
1569
- }
1570
- export {
1571
- ACTION_KINDS,
1572
- ActionDispatcher,
1573
- BaseController,
1574
- BaseLogger,
1575
- CompositeLogger,
1576
- CompositeLoggerFactory,
1577
- ConsoleLogger,
1578
- ConsoleLoggerFactory,
1579
- Container,
1580
- DEP_KEYS,
1581
- Framework,
1582
- History,
1583
- HttpClient,
1584
- HttpError,
1585
- IntentDispatcher,
1586
- LruMap,
1587
- PrefetchedIntents,
1588
- Router,
1589
- SSR_PLACEHOLDERS,
1590
- autoAdapter,
1591
- buildUrl,
1592
- cloudflareAdapter,
1593
- createBrowserContext,
1594
- createPrefetchedIntentsFromDom,
1595
- createSSRApp,
1596
- createSSRRender,
1597
- createServer,
1598
- createServerContext,
1599
- defineRoutes,
1600
- deny,
1601
- deserializeServerData,
1602
- detectRuntime,
1603
- finesoftFrontViteConfig,
1604
- generateProxyCode,
1605
- generateUuid,
1606
- getBaseUrl,
1607
- injectCSRShell,
1608
- injectSSRContent,
1609
- isCompoundAction,
1610
- isExternalUrlAction,
1611
- isFlowAction,
1612
- isNone,
1613
- isSome,
1614
- makeDependencies,
1615
- makeExternalUrlAction,
1616
- makeFlowAction,
1617
- mapEach,
1618
- netlifyAdapter,
1619
- next,
1620
- nodeAdapter,
1621
- parseAcceptLanguage,
1622
- pipe,
1623
- pipeAsync,
1624
- redirect,
1625
- registerActionHandlers,
1626
- registerExternalUrlHandler,
1627
- registerFlowActionHandler,
1628
- registerProxyRoutes,
1629
- removeHost,
1630
- removeQueryParams,
1631
- removeScheme,
1632
- resetFilterCache,
1633
- resolveAdapter,
1634
- resolveRoot,
1635
- rewrite,
1636
- runAfterLoadGuards,
1637
- runBeforeLoadGuards,
1638
- serializeServerData,
1639
- shouldLog,
1640
- ssrRender,
1641
- stableStringify,
1642
- startBrowserApp,
1643
- startServer,
1644
- staticAdapter,
1645
- tryScroll,
1646
- vercelAdapter
1647
- };
1648
- //# sourceMappingURL=index.js.map