@withl5e/l5e 0.3.3-alpha.4 → 1.0.0

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 (71) hide show
  1. package/README.md +1 -1
  2. package/dist/action.js +10 -9
  3. package/dist/action.js.map +1 -1
  4. package/dist/defineMiddleware-D017PWDc.js +8 -0
  5. package/dist/defineMiddleware-D017PWDc.js.map +1 -0
  6. package/dist/entry-server.js +161 -176
  7. package/dist/entry-server.js.map +1 -1
  8. package/dist/exceptions-D4OdiQjY.js +30 -0
  9. package/dist/exceptions-D4OdiQjY.js.map +1 -0
  10. package/dist/generateMetadata-DcdY-XC1.js +303 -0
  11. package/dist/generateMetadata-DcdY-XC1.js.map +1 -0
  12. package/dist/global-style-BhiGjxVU.js +21 -0
  13. package/dist/global-style-BhiGjxVU.js.map +1 -0
  14. package/dist/i18n.js +8 -11
  15. package/dist/i18n.js.map +1 -1
  16. package/dist/index.js +9 -55
  17. package/dist/island/client.js +2 -5
  18. package/dist/island/runtime.js +90 -107
  19. package/dist/island/runtime.js.map +1 -1
  20. package/dist/island.js +38 -56
  21. package/dist/island.js.map +1 -1
  22. package/dist/jsx-runtime-CI0Jmr-C.js +275 -0
  23. package/dist/jsx-runtime-CI0Jmr-C.js.map +1 -0
  24. package/dist/jsx-runtime.js +2 -31
  25. package/dist/middleware-CnDqZobD.js +217 -0
  26. package/dist/middleware-CnDqZobD.js.map +1 -0
  27. package/dist/middleware.js +3 -8
  28. package/dist/render-hUQUreah.js +152 -0
  29. package/dist/render-hUQUreah.js.map +1 -0
  30. package/dist/rolldown-runtime-B0aSnxlc.js +20 -0
  31. package/dist/router.js +72 -68
  32. package/dist/router.js.map +1 -1
  33. package/dist/seo.js +3 -7
  34. package/dist/server-5BEwGAL4.js +461 -0
  35. package/dist/server-5BEwGAL4.js.map +1 -0
  36. package/dist/server.js +2 -515
  37. package/dist/strategy-registry-wmHnsHQb.js +9 -0
  38. package/dist/strategy-registry-wmHnsHQb.js.map +1 -0
  39. package/dist/swap/server.js +11 -14
  40. package/dist/swap/server.js.map +1 -1
  41. package/dist/swap.js +109 -116
  42. package/dist/swap.js.map +1 -1
  43. package/dist/tooltip.js +145 -141
  44. package/dist/tooltip.js.map +1 -1
  45. package/dist/vite-plugin.js +315 -372
  46. package/dist/vite-plugin.js.map +1 -1
  47. package/package.json +8 -8
  48. package/src/core/bundler.ts +41 -25
  49. package/src/core/vite-plugin.ts +14 -15
  50. package/dist/client-D67hK4Yy.js +0 -9
  51. package/dist/client-D67hK4Yy.js.map +0 -1
  52. package/dist/defineMiddleware-VdHQuiUc.js +0 -7
  53. package/dist/defineMiddleware-VdHQuiUc.js.map +0 -1
  54. package/dist/exceptions-CHPz01DJ.js +0 -39
  55. package/dist/exceptions-CHPz01DJ.js.map +0 -1
  56. package/dist/generateMetadata-Cn8BIxq6.js +0 -144
  57. package/dist/generateMetadata-Cn8BIxq6.js.map +0 -1
  58. package/dist/global-style-DFvaBcuR.js +0 -27
  59. package/dist/global-style-DFvaBcuR.js.map +0 -1
  60. package/dist/index-CybB8Tdk.js +0 -315
  61. package/dist/index-CybB8Tdk.js.map +0 -1
  62. package/dist/index.js.map +0 -1
  63. package/dist/island/client.js.map +0 -1
  64. package/dist/jsx-runtime-DqAp8xlt.js +0 -296
  65. package/dist/jsx-runtime-DqAp8xlt.js.map +0 -1
  66. package/dist/jsx-runtime.js.map +0 -1
  67. package/dist/middleware.js.map +0 -1
  68. package/dist/render-CRag-5V7.js +0 -202
  69. package/dist/render-CRag-5V7.js.map +0 -1
  70. package/dist/seo.js.map +0 -1
  71. package/dist/server.js.map +0 -1
@@ -0,0 +1,461 @@
1
+ import { r as e } from "./rolldown-runtime-B0aSnxlc.js";
2
+ import { a as t, n } from "./render-hUQUreah.js";
3
+ import { i as r, r as i, t as a } from "./middleware-CnDqZobD.js";
4
+ import { n as o } from "./global-style-BhiGjxVU.js";
5
+ import { existsSync as s } from "fs";
6
+ import c from "node:fs/promises";
7
+ import l from "node:path";
8
+ import { pathToFileURL as u } from "node:url";
9
+ import d from "request-ip";
10
+ import { createHash as f } from "node:crypto";
11
+ import { createRequire as p } from "node:module";
12
+ //#region src/core/bundler.ts
13
+ var m = /* @__PURE__ */ e(t(), 1), h = null;
14
+ function g() {
15
+ return h ||= (async () => {
16
+ let e = p(import.meta.url).resolve("@withl5e/l5e/server"), t = p(e).resolve("rolldown");
17
+ return await import(
18
+ /* @vite-ignore */
19
+ u(t).href
20
+ );
21
+ })(), h;
22
+ }
23
+ var _ = {
24
+ hash: "",
25
+ filename: "",
26
+ content: ""
27
+ }, v = /* @__PURE__ */ new Map(), y = /* @__PURE__ */ new Map();
28
+ function b(e, t) {
29
+ let n = y.get(e);
30
+ if (n) return n;
31
+ let r = t().catch((t) => {
32
+ throw y.delete(e), t;
33
+ });
34
+ return y.set(e, r), r;
35
+ }
36
+ function x(e) {
37
+ return f("sha256").update(e).digest("hex").substring(0, 16);
38
+ }
39
+ var S = "\0l5e:bundle-entry";
40
+ function C(e) {
41
+ return {
42
+ name: "l5e-virtual-entry",
43
+ resolveId(e) {
44
+ return e === S ? S : null;
45
+ },
46
+ load(t) {
47
+ return t === S ? e : null;
48
+ }
49
+ };
50
+ }
51
+ function w(e) {
52
+ let t = (t) => "/" + l.relative(e, t).replace(/\\/g, "/");
53
+ return {
54
+ name: "vendor-path-rewriter",
55
+ resolveId(e, n) {
56
+ return !e.includes("vendor-") && !e.includes("chunk-") && !e.includes(".global") ? null : l.isAbsolute(e) ? {
57
+ id: t(e),
58
+ external: "absolute"
59
+ } : n && e.startsWith(".") ? {
60
+ id: t(l.resolve(l.dirname(n), e)),
61
+ external: "absolute"
62
+ } : null;
63
+ }
64
+ };
65
+ }
66
+ async function T(e, t) {
67
+ let n = {
68
+ input: S,
69
+ plugins: [C(e.map((e) => {
70
+ let n = e.startsWith("/") ? l.join(t, e.substring(1)) : l.join(t, e);
71
+ return `import ${JSON.stringify(n)};`;
72
+ }).join("\n")), w(t)],
73
+ platform: "neutral",
74
+ tsconfig: !1,
75
+ treeshake: { moduleSideEffects: () => !0 },
76
+ external: (e) => !e.startsWith(".") && !l.isAbsolute(e) && e !== S
77
+ }, r = {
78
+ format: "es",
79
+ codeSplitting: !0,
80
+ minify: !1,
81
+ entryFileNames: "bundle-[hash].js",
82
+ chunkFileNames: "bundle-[hash].js"
83
+ }, { rolldown: i } = await g(), a = await i(n), o;
84
+ try {
85
+ ({output: o} = await a.generate(r));
86
+ } finally {
87
+ await a.close();
88
+ }
89
+ for (let e of o) e.type === "chunk" && v.set(e.fileName, {
90
+ content: e.code || "",
91
+ hash: x(e.code || ""),
92
+ filename: e.fileName,
93
+ mimeType: "application/javascript"
94
+ });
95
+ let s = o.find((e) => e.type === "chunk" && e.isEntry && e.facadeModuleId === S);
96
+ if (!s) throw Error("[bundler] rolldown produced no entry chunk");
97
+ return {
98
+ hash: x(s.code || ""),
99
+ filename: s.fileName,
100
+ content: s.code || ""
101
+ };
102
+ }
103
+ async function E(e, t) {
104
+ if (e.length === 0) return _;
105
+ let n = [...new Set(e)].sort(), r = `scripts:${n.join(",")}`;
106
+ try {
107
+ return await b(r, () => T(n, t));
108
+ } catch (e) {
109
+ return console.error("[bundler] Error bundling scripts:", e), _;
110
+ }
111
+ }
112
+ async function D(e, t) {
113
+ let n = [];
114
+ for (let r of e) {
115
+ let e = r.startsWith("/") ? l.join(t, r.substring(1)) : l.join(t, r);
116
+ try {
117
+ let t = await c.readFile(e, "utf-8");
118
+ n.push(`/* ${r} */\n${t}\n`);
119
+ } catch (e) {
120
+ console.warn(`[bundler] Failed to read CSS file: ${r}`, e);
121
+ }
122
+ }
123
+ let r = n.join("\n\n"), i = x(r), a = `bundle-${i}.css`;
124
+ return v.set(a, {
125
+ content: r,
126
+ hash: i,
127
+ filename: a,
128
+ mimeType: "text/css"
129
+ }), {
130
+ hash: i,
131
+ filename: a,
132
+ content: r
133
+ };
134
+ }
135
+ async function O(e, t) {
136
+ if (e.length === 0) return _;
137
+ let n = [...new Set(e)].sort(), r = `css:${n.join(",")}`;
138
+ try {
139
+ return await b(r, () => D(n, t));
140
+ } catch (e) {
141
+ return console.error("[bundler] Error bundling CSS:", e), _;
142
+ }
143
+ }
144
+ function k(e) {
145
+ return v.get(e);
146
+ }
147
+ //#endregion
148
+ //#region src/core/server.ts
149
+ function A(e, t) {
150
+ let r = n(t);
151
+ return e.replace(/<html\b([^>]*)>/i, (e, t) => /\blang\s*=/i.test(t) ? e.replace(/lang\s*=\s*"[^"]*"/i, () => `lang="${r}"`) : `<html lang="${r}"${t}>`);
152
+ }
153
+ function j(e) {
154
+ return new URL(`${e.protocol}://${e.get("host")}${e.originalUrl}`);
155
+ }
156
+ function M(e, t) {
157
+ return `${e.pathname}${e.search}`.replace(t, "") || "/";
158
+ }
159
+ function N(e) {
160
+ let t = {
161
+ method: e.method,
162
+ headers: i(e)
163
+ };
164
+ return e.method !== "GET" && e.method !== "HEAD" && (t.body = e, t.duplex = "half"), new globalThis.Request(j(e).href, t);
165
+ }
166
+ function P(e, t, n, i) {
167
+ let a = new URL(t.url), o = M(a, n), s = o.startsWith("/") ? o : `/${o}`, c = {};
168
+ return t.headers.forEach((e, t) => {
169
+ c[t] = e;
170
+ }), {
171
+ url: a,
172
+ path: s,
173
+ pathname: a.pathname,
174
+ method: t.method,
175
+ headers: c,
176
+ cookies: r(t.headers.get("cookie") ?? void 0),
177
+ query: Object.fromEntries(a.searchParams.entries()),
178
+ ip: d.getClientIp(e) ?? void 0,
179
+ locals: i
180
+ };
181
+ }
182
+ function F(e, t, n) {
183
+ return e ? e instanceof globalThis.Request ? e : e instanceof URL ? new globalThis.Request(e.href, t.clone()) : new globalThis.Request(new URL(e, n).href, t.clone()) : t;
184
+ }
185
+ async function I(e, t, n) {
186
+ t.status(n.status);
187
+ let r = L(n.headers);
188
+ if (n.headers.forEach((e, n) => {
189
+ n.toLowerCase() !== "set-cookie" && t.setHeader(n, e);
190
+ }), r.length > 0 && t.setHeader("Set-Cookie", r), e.method === "HEAD") {
191
+ t.end();
192
+ return;
193
+ }
194
+ let i = Buffer.from(await n.arrayBuffer());
195
+ t.send(i);
196
+ }
197
+ function L(e) {
198
+ let t = e.getSetCookie;
199
+ if (typeof t == "function") return t.call(e);
200
+ let n = e.raw?.();
201
+ if (n?.["set-cookie"]) return n["set-cookie"];
202
+ let r = e.get("set-cookie");
203
+ return r ? R(r) : [];
204
+ }
205
+ function R(e) {
206
+ let t = [], n = 0;
207
+ for (let r = 0; r < e.length; r++) {
208
+ if (e[r] !== ",") continue;
209
+ let i = e.slice(r + 1);
210
+ /^\s*[^=;,]+=/.test(i) && (t.push(e.slice(n, r).trim()), n = r + 1);
211
+ }
212
+ return t.push(e.slice(n).trim()), t.filter(Boolean);
213
+ }
214
+ function z(e) {
215
+ if (!e.rawResponse) return null;
216
+ let { body: t, contentType: n, statusCode: r, headers: i } = e.rawResponse, a = new Headers(i);
217
+ return a.set("Content-Type", n), new globalThis.Response(t, {
218
+ status: r || 200,
219
+ headers: a
220
+ });
221
+ }
222
+ async function B({ rendered: e, template: t, manifest: r, root: i, distClientDir: a, isProduction: c, assetBase: u }) {
223
+ let d = z(e);
224
+ if (d) return d;
225
+ if (e.redirect) return new globalThis.Response(null, {
226
+ status: e.redirect.statusCode,
227
+ headers: { Location: e.redirect.url }
228
+ });
229
+ let f = e.scripts || [], p = e.styles || [], h = e.islands || [], g = e.cacheTags || [], _ = e.maxAge, v = e.sMaxAge, y = e.swr, b = "", x = /* @__PURE__ */ new Set(), S = (e, t = !1) => {
230
+ x.has(e) || (x.add(e), b += `<link rel="stylesheet"${t ? " crossorigin" : ""} href="${n(e)}">`);
231
+ }, C = [], w = "", T = o({
232
+ root: i,
233
+ manifest: r,
234
+ isProduction: c,
235
+ base: u
236
+ });
237
+ T && S(T, c);
238
+ let D = "";
239
+ if (e.islandData && e.islandData.length > 0 && (D = `<script type="application/json" id="_l5e_data_">${(0, m.default)(e.islandData, { isJSON: !0 })}<\/script>`), c && r) {
240
+ f = f.filter((e) => !e.includes(".global.")), p = p.filter((e) => !e.includes(".global."));
241
+ let e = /* @__PURE__ */ new Set(), t = /* @__PURE__ */ new Set();
242
+ function n(n) {
243
+ let i = r[n];
244
+ return i ? (i.css && i.css.forEach((t) => e.add(t)), i.imports && i.imports.forEach((n) => {
245
+ let i = r[n];
246
+ i?.file && t.add(i.file), i?.css && i.css.forEach((t) => e.add(t)), i?.imports && i.imports.forEach((n) => {
247
+ let i = r[n];
248
+ i?.file && t.add(i.file), i?.css && i.css.forEach((t) => e.add(t));
249
+ });
250
+ }), { file: i.file }) : { file: null };
251
+ }
252
+ let i = [];
253
+ for (let e of f) {
254
+ let { file: t } = n(e.replace(/^\//, ""));
255
+ t && i.push(`/${t}`);
256
+ }
257
+ let o = [];
258
+ for (let t of p) {
259
+ let { file: r } = n(t.replace(/^\//, ""));
260
+ r && (o.push(`/${r}`), e.add(r));
261
+ }
262
+ if (i.length > 0) {
263
+ let e = await E(i, a);
264
+ f = e.filename ? [`/${e.filename}`] : i;
265
+ }
266
+ if (o.length > 0) {
267
+ let e = await O(o, a);
268
+ e.filename && (p = [`/${e.filename}`]);
269
+ }
270
+ let s = r["src/client.global.ts"];
271
+ if (s && (s.css && s.css.length > 0 && s.css.forEach((e) => {
272
+ S(`/${e}`, !0);
273
+ }), s.file && C.push(`/${s.file}`)), h.length > 0) {
274
+ let e = {};
275
+ for (let t of h) {
276
+ let n = r[t.src];
277
+ n?.file && (e[t.key] = `/${n.file}`);
278
+ }
279
+ Object.keys(e).length > 0 && (w = `<script>window.__L5E_ISLANDS__=${(0, m.default)(e)}<\/script>`);
280
+ }
281
+ p.length > 0 && p.forEach((e) => S(e, !0));
282
+ }
283
+ c || [...new Set(p)].forEach((e) => S(e));
284
+ let k = [...C, ...f];
285
+ if (!c) {
286
+ let e = l.join(i, "src", "client.global.ts");
287
+ if (s(e) && (k = ["/src/client.global.ts", ...k]), k = [...new Set(k)], h.length > 0) {
288
+ let e = {};
289
+ for (let t of h) e[t.key] = `/${t.src}`;
290
+ w = `<script>window.__L5E_ISLANDS__=${(0, m.default)(e)}<\/script>`;
291
+ }
292
+ }
293
+ let j = D + w + k.map((e) => `<script type="module" src="${e}"><\/script>`).join(""), M = e.lang ? A(t, e.lang) : t, N = e.rawHtml ? e.html || "" : M.replace("<!--app-head-->", () => (e.head ?? "") + b).replace("<!--app-html-->", () => e.html ?? "").replace("<!--app-scripts-->", () => j), P = new Headers({ "Content-Type": "text/html" }), F = [], I = [];
294
+ return _ !== void 0 && (F.push(`max-age=${_}`), I.push(`max-age=${_}`)), v !== void 0 && I.push(`s-maxage=${v}`), y !== void 0 && I.push(`stale-while-revalidate=${y}`), (F.length > 0 || I.length > 0) && c && (F.push("public"), F.push("must-revalidate"), I.push("public"), P.set("Cache-Control", F.join(", ")), P.set("CDN-Cache-Control", I.join(", "))), process.env.NODE_ENV === "production" && (g = G(g)), P.set("Cache-Tag", ["global", ...g].join(",")), new globalThis.Response(N, {
295
+ status: e.statusCode || 200,
296
+ headers: P
297
+ });
298
+ }
299
+ async function V(e = {}) {
300
+ let t = e.root || process.cwd(), n = e.base || "/", i = process.env.NODE_ENV === "production", o = e.externalizeIslandProps ?? !0, f = i ? await c.readFile(l.join(t, "./index.html"), "utf-8") : "", p = (await import("express")).default, m = e.app || p();
301
+ if (e.publicDir) {
302
+ let n = l.isAbsolute(e.publicDir) ? e.publicDir : l.join(t, e.publicDir);
303
+ s(n) && m.use(p.static(n));
304
+ }
305
+ let h, g = l.join(t, "./dist/client");
306
+ if (i) {
307
+ let e = (await import("compression")).default, t = (await import("sirv")).default;
308
+ m.use(e()), m.use(n, t(g, { extensions: [] })), m.get(`${n === "/" ? "" : n}/bundle-:hash.:ext`, async (e, t) => {
309
+ try {
310
+ let { hash: n, ext: r } = e.params, i = k(`bundle-${n}.${r}`);
311
+ if (!i) return t.status(404).send("Bundled file not found");
312
+ t.set({
313
+ "Content-Type": i.mimeType,
314
+ "Cache-Control": "public, max-age=31536000, immutable"
315
+ }), t.send(i.content);
316
+ } catch (e) {
317
+ console.error("[server] Error serving bundled file:", e), t.status(500).end("Internal server error");
318
+ }
319
+ });
320
+ } else {
321
+ let { createServer: e } = await import("vite");
322
+ h = await e({
323
+ root: t,
324
+ configFile: l.join(t, "vite.config.js"),
325
+ server: { middlewareMode: !0 },
326
+ appType: "custom",
327
+ base: n,
328
+ optimizeDeps: { exclude: ["@withl5e/l5e", "file-type"] },
329
+ ssr: { resolve: { conditions: ["development", "default"] } },
330
+ resolve: { conditions: ["development", "default"] }
331
+ }), m.use(h.middlewares);
332
+ }
333
+ m.use("/_l5e/action", p.json({ limit: "100kb" }));
334
+ let _ = /^[a-zA-Z]\w+_[0-9a-f]{1,4}$/, v = null, y = null;
335
+ async function b() {
336
+ if (!i) return (await h.ssrLoadModule("virtual:l5e-actions")).actionRegistry || {};
337
+ if (!v) {
338
+ let e = l.join(t, "./dist/server/action-registry.json"), n = await c.readFile(e, "utf-8");
339
+ v = JSON.parse(n);
340
+ }
341
+ return v;
342
+ }
343
+ async function x() {
344
+ if (!i) return (await h.ssrLoadModule("virtual:l5e-actions")).viewActions || {};
345
+ if (!y) {
346
+ let e = l.join(t, "./dist/server/entry-server.js");
347
+ y = (await import(u(e).href)).viewActions || {};
348
+ }
349
+ return y;
350
+ }
351
+ return m.all("/_l5e/action/:actionKey", async (e, r) => {
352
+ try {
353
+ let { actionKey: o } = e.params;
354
+ if (!_.test(o)) return r.status(400).send("Invalid action key");
355
+ let s = (await b())[o];
356
+ if (!s) return r.status(404).send("Action not found");
357
+ let { modulePath: c, actionName: f } = s, p;
358
+ if (i) {
359
+ let e = await x(), t = e[`/src/${c}/actions.tsx`] ? `/src/${c}/actions.tsx` : e[`/src/${c}/actions.ts`] ? `/src/${c}/actions.ts` : null;
360
+ if (!t) return r.status(404).send("Action module not found");
361
+ p = await e[t]();
362
+ } else try {
363
+ p = await h.ssrLoadModule(`/src/${c}/actions.tsx`);
364
+ } catch {
365
+ p = await h.ssrLoadModule(`/src/${c}/actions.ts`);
366
+ }
367
+ if (!Object.prototype.hasOwnProperty.call(p, f)) return r.status(404).send("Action not found");
368
+ let m = p[f];
369
+ if (!m || !m.handler) return r.status(404).send("Action not found");
370
+ let g = (m.method || "GET").toUpperCase();
371
+ if (e.method.toUpperCase() !== g) return r.status(405).set("Allow", g).send("Method Not Allowed");
372
+ let v = l.join(t, "./dist/server/entry-server.js"), y = i ? await import(u(v).href) : await h.ssrLoadModule("@withl5e/l5e/entry-server"), { runInRenderContext: S } = await (i ? import(u(v).href) : h.ssrLoadModule("@withl5e/l5e/jsx-runtime")), { renderJsxToHtmlString: C } = await (i ? import(u(v).href) : h.ssrLoadModule("@withl5e/l5e")), w = {}, T = N(e), E = a({
373
+ request: T,
374
+ locals: w,
375
+ clientAddress: d.getClientIp(e) ?? void 0
376
+ }), D = await y.loadMiddleware?.();
377
+ await I(e, r, await (typeof D == "function" ? D : (e, t) => t())(E, async (t) => {
378
+ let r = {
379
+ ...P(e, F(t, E.request, E.url), n, w),
380
+ path: e.originalUrl,
381
+ body: e.body
382
+ }, i = await S(async () => {
383
+ let e = await m.handler(r);
384
+ return C(e);
385
+ }, r, c);
386
+ return new Response(i, { headers: { "Content-Type": "text/html" } });
387
+ }));
388
+ } catch (e) {
389
+ h?.ssrFixStacktrace?.(e), console.error("[l5e] Action error:", e.stack || e), r.status(500).send("Internal server error");
390
+ }
391
+ }), m.use(async (e, s) => {
392
+ try {
393
+ let p = e.originalUrl.replace(n, ""), m, _, v, y;
394
+ if (i) {
395
+ m = f;
396
+ let e = l.join(t, "./dist/server/entry-server.js"), n = await import(u(e).href);
397
+ _ = n.render, v = n.loadMiddleware;
398
+ let r = await c.readFile(l.join(t, "./dist/client/.vite/manifest.json"), "utf-8");
399
+ y = JSON.parse(r);
400
+ } else {
401
+ m = await c.readFile(l.join(t, "./index.html"), "utf-8"), m = await h.transformIndexHtml(p, m), m.includes("@vite/client") || (m = m.replace("</head>", "<script type=\"module\" src=\"/@vite/client\"><\/script></head>"));
402
+ let e = await h.ssrLoadModule("@withl5e/l5e/entry-server");
403
+ _ = e.render, v = e.loadMiddleware;
404
+ }
405
+ let b = await v?.(), x = typeof b == "function" ? b : (e, t) => t(), S = {}, C = N(e), w = a({
406
+ request: C,
407
+ requestInfo: P(e, C, n, S),
408
+ locals: S,
409
+ clientAddress: d.getClientIp(e)
410
+ }), T = async (r) => {
411
+ let a = P(e, r, n, S), s = M(a.url, n);
412
+ return B({
413
+ rendered: await _(s, a, { externalizeIslandProps: o }),
414
+ template: m,
415
+ manifest: y,
416
+ root: t,
417
+ distClientDir: g,
418
+ isProduction: i,
419
+ assetBase: i ? n : h.config.base
420
+ });
421
+ }, E = async (t) => {
422
+ let i = F(t, w.request, w.url);
423
+ return w.request = i, w.url = new URL(i.url), w.cookies = r(i.headers.get("cookie") ?? void 0), w.requestInfo = P(e, i, n, S), T(i);
424
+ };
425
+ w.rewrite = (e) => E(e), await I(e, s, await x(w, E));
426
+ } catch (e) {
427
+ h?.ssrFixStacktrace?.(e), console.error(e.stack), s.status(500).end(i ? "Internal Server Error" : e.stack);
428
+ }
429
+ }), {
430
+ app: m,
431
+ vite: h
432
+ };
433
+ }
434
+ async function H(e = {}) {
435
+ let t = e.port || 5173, n = (await import("express")).default, r = n();
436
+ e.setupApp && (console.log("setupApp"), await e.setupApp(r));
437
+ let { app: i } = await V({
438
+ ...e,
439
+ app: r
440
+ });
441
+ i.listen(t, () => {
442
+ console.log(`Server started at http://localhost:${t}`);
443
+ });
444
+ }
445
+ var U = 1e3;
446
+ function W(e) {
447
+ if (e === "global") return "global";
448
+ let t = 0;
449
+ for (let n = 0; n < e.length; n++) {
450
+ let r = e.charCodeAt(n);
451
+ t = (t << 5) - t + r, t &= t;
452
+ }
453
+ return Math.abs(t).toString(36).substring(0, 8);
454
+ }
455
+ function G(e) {
456
+ return (Array.isArray(e) ? e : [...e]).slice(0, U).map(W);
457
+ }
458
+ //#endregion
459
+ export { H as a, G as i, V as n, W as r, A as t };
460
+
461
+ //# sourceMappingURL=server-5BEwGAL4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-5BEwGAL4.js","names":["serialize"],"sources":["../src/core/bundler.ts","../src/core/server.ts"],"sourcesContent":["/// <reference path=\"./jsx-types.d.ts\" />\nimport { createHash } from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { InputOptions, OutputChunk, OutputOptions, Plugin } from 'rolldown';\n\nlet rolldownModulePromise: Promise<typeof import('rolldown')> | null = null;\n\n/**\n * Resolve Rolldown lazily from the installed framework package. A bare static\n * import can be hoisted when the framework is bundled into a consumer's SSR\n * output, which breaks pnpm's strict dependency layout. Anchoring resolution at\n * @withl5e/l5e keeps the runtime dependency owned by the package that declares it.\n */\nfunction loadRolldown(): Promise<typeof import('rolldown')> {\n if (!rolldownModulePromise) {\n rolldownModulePromise = (async () => {\n const require = createRequire(import.meta.url);\n const frameworkEntry = require.resolve('@withl5e/l5e/server');\n const frameworkRequire = createRequire(frameworkEntry);\n const rolldownPath = frameworkRequire.resolve('rolldown');\n return (await import(\n /* @vite-ignore */ pathToFileURL(rolldownPath).href\n )) as typeof import('rolldown');\n })();\n }\n return rolldownModulePromise;\n}\n\ninterface BundledFile {\n content: string;\n hash: string;\n filename: string;\n mimeType: string;\n}\n\ninterface BundleResult {\n hash: string;\n filename: string;\n content: string;\n}\n\nconst EMPTY_RESULT: BundleResult = { hash: '', filename: '', content: '' };\n\n// Memory map để lưu bundled files\nconst bundledFilesMap = new Map<string, BundledFile>();\n\n/**\n * Single-flight map: cacheKey → promise của lần bundle đang chạy (hoặc đã xong).\n * Vì promise được giữ lại sau khi resolve, map này vừa là in-flight dedup vừa là\n * result cache. Bundle lỗi bị xoá khỏi map để request sau được thử lại.\n */\nconst bundlePromises = new Map<string, Promise<BundleResult>>();\n\n/**\n * Chạy `work` đúng một lần cho mỗi cacheKey, kể cả khi nhiều request đến đồng thời.\n */\nfunction dedupe(cacheKey: string, work: () => Promise<BundleResult>): Promise<BundleResult> {\n const pending = bundlePromises.get(cacheKey);\n if (pending) {\n return pending;\n }\n\n const promise = work().catch((error) => {\n bundlePromises.delete(cacheKey);\n throw error;\n });\n bundlePromises.set(cacheKey, promise);\n return promise;\n}\n\n/**\n * Generate hash từ content\n */\nfunction generateHash(content: string): string {\n return createHash('sha256').update(content).digest('hex').substring(0, 16);\n}\n\n// Rolldown coi id bắt đầu bằng \\0 là virtual — nó sẽ không cố đọc từ đĩa.\nconst VIRTUAL_ENTRY_ID = '\\0l5e:bundle-entry';\n\n/**\n * Entry của mỗi lần bundle chỉ là một danh sách import. Giữ nó trong memory thay\n * vì ghi ra đĩa: hai request đồng thời cùng một tập script sinh ra cùng nội dung\n * entry, nên file tạm dùng chung path sẽ bị request này xoá trong lúc Rolldown của\n * request kia còn đang đọc.\n */\nfunction virtualEntryPlugin(entryContent: string): Plugin {\n return {\n name: 'l5e-virtual-entry',\n resolveId(source) {\n return source === VIRTUAL_ENTRY_ID ? VIRTUAL_ENTRY_ID : null;\n },\n load(id) {\n return id === VIRTUAL_ENTRY_ID ? entryContent : null;\n },\n };\n}\n\n/**\n * Rewrite vendor/chunk/global imports thành web path và để chúng external.\n * Global files (*.global.*) đã được client.global.ts load — bundle lại sẽ tạo\n * module instance trùng (vd nanostores).\n */\nfunction vendorPathRewriterPlugin(distClientDir: string): Plugin {\n const toWebPath = (absolutePath: string) =>\n '/' + path.relative(distClientDir, absolutePath).replace(/\\\\/g, '/');\n\n return {\n name: 'vendor-path-rewriter',\n resolveId(source, importer) {\n if (\n !source.includes('vendor-') &&\n !source.includes('chunk-') &&\n !source.includes('.global')\n ) {\n return null;\n }\n\n if (path.isAbsolute(source)) {\n // e.g. C:\\...\\dist\\client\\assets\\vendor-react-XXX.js -> /assets/vendor-react-XXX.js\n return { id: toWebPath(source), external: 'absolute' };\n }\n\n if (importer && source.startsWith('.')) {\n // Relative path như ./auth.global-BOVr81Z5.js — resolve từ importer\n return {\n id: toWebPath(path.resolve(path.dirname(importer), source)),\n external: 'absolute',\n };\n }\n\n return null;\n },\n };\n}\n\nasync function runScriptBundle(\n uniquePaths: string[],\n distClientDir: string,\n): Promise<BundleResult> {\n const entryContent = uniquePaths\n .map((p) => {\n const filePath = p.startsWith('/')\n ? path.join(distClientDir, p.substring(1))\n : path.join(distClientDir, p);\n return `import ${JSON.stringify(filePath)};`;\n })\n .join('\\n');\n\n const rolldownOptions: InputOptions = {\n input: VIRTUAL_ENTRY_ID,\n plugins: [virtualEntryPlugin(entryContent), vendorPathRewriterPlugin(distClientDir)],\n platform: 'neutral',\n tsconfig: false,\n // Runtime scripts are imported for their side effects. Do not let an app's\n // package.json sideEffects flag erase those entry imports.\n // Rolldown 1.2 still consults package metadata for boolean `true`, so use\n // an explicit callback to override consumer `sideEffects: false`.\n treeshake: { moduleSideEffects: () => true },\n external: (id) => {\n // External node_modules\n if (!id.startsWith('.') && !path.isAbsolute(id) && id !== VIRTUAL_ENTRY_ID) {\n return true;\n }\n\n // Vendor/chunk/global do plugin resolveId lo phần rewrite path\n return false;\n },\n };\n\n const outputOptions: OutputOptions = {\n format: 'es',\n codeSplitting: true,\n minify: false,\n entryFileNames: 'bundle-[hash].js',\n chunkFileNames: 'bundle-[hash].js',\n };\n\n const { rolldown } = await loadRolldown();\n const bundle = await rolldown(rolldownOptions);\n let output;\n try {\n ({ output } = await bundle.generate(outputOptions));\n } finally {\n await bundle.close();\n }\n\n for (const chunk of output) {\n if (chunk.type !== 'chunk') {\n continue;\n }\n bundledFilesMap.set(chunk.fileName, {\n content: chunk.code || '',\n hash: generateHash(chunk.code || ''),\n filename: chunk.fileName,\n mimeType: 'application/javascript',\n });\n }\n\n const entryChunk = output.find(\n (item): item is OutputChunk =>\n item.type === 'chunk' && item.isEntry && item.facadeModuleId === VIRTUAL_ENTRY_ID,\n );\n if (!entryChunk) {\n throw new Error('[bundler] rolldown produced no entry chunk');\n }\n\n return {\n hash: generateHash(entryChunk.code || ''),\n filename: entryChunk.fileName,\n content: entryChunk.code || '',\n };\n}\n\n/**\n * Bundle JavaScript files từ dist/client thành 1 file\n * Trong production, các file đã được build sẵn trong dist/client\n */\nexport async function bundleScripts(\n scriptPaths: string[],\n distClientDir: string,\n): Promise<BundleResult> {\n if (scriptPaths.length === 0) {\n return EMPTY_RESULT;\n }\n\n const uniquePaths = [...new Set(scriptPaths)].sort();\n const cacheKey = `scripts:${uniquePaths.join(',')}`;\n\n try {\n return await dedupe(cacheKey, () => runScriptBundle(uniquePaths, distClientDir));\n } catch (error) {\n console.error('[bundler] Error bundling scripts:', error);\n return EMPTY_RESULT;\n }\n}\n\nasync function runCssBundle(\n uniquePaths: string[],\n distClientDir: string,\n): Promise<BundleResult> {\n const cssContents: string[] = [];\n\n for (const cssPath of uniquePaths) {\n // cssPath có thể là \"/assets/xxx.css\" hoặc từ manifest\n const filePath = cssPath.startsWith('/')\n ? path.join(distClientDir, cssPath.substring(1))\n : path.join(distClientDir, cssPath);\n\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n cssContents.push(`/* ${cssPath} */\\n${content}\\n`);\n } catch (err) {\n console.warn(`[bundler] Failed to read CSS file: ${cssPath}`, err);\n }\n }\n\n const bundledContent = cssContents.join('\\n\\n');\n const hash = generateHash(bundledContent);\n const filename = `bundle-${hash}.css`;\n\n bundledFilesMap.set(filename, {\n content: bundledContent,\n hash,\n filename,\n mimeType: 'text/css',\n });\n\n return { hash, filename, content: bundledContent };\n}\n\n/**\n * Bundle CSS files từ dist/client thành 1 file\n * Trong production, các file đã được build sẵn trong dist/client\n */\nexport async function bundleCss(\n cssPaths: string[],\n distClientDir: string,\n): Promise<BundleResult> {\n if (cssPaths.length === 0) {\n return EMPTY_RESULT;\n }\n\n const uniquePaths = [...new Set(cssPaths)].sort();\n const cacheKey = `css:${uniquePaths.join(',')}`;\n\n try {\n return await dedupe(cacheKey, () => runCssBundle(uniquePaths, distClientDir));\n } catch (error) {\n console.error('[bundler] Error bundling CSS:', error);\n return EMPTY_RESULT;\n }\n}\n\n/**\n * Get bundled file từ map\n */\nexport function getBundledFile(filename: string): BundledFile | undefined {\n return bundledFilesMap.get(filename);\n}\n\n/**\n * Clear bundled files map (useful for testing)\n */\nexport function clearBundledFiles(): void {\n bundledFilesMap.clear();\n bundlePromises.clear();\n}\n","import type { Request as ExpressRequest, Response as ExpressResponse } from 'express';\nimport { existsSync } from 'fs';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport requestIp from 'request-ip';\nimport serialize from 'serialize-javascript';\nimport type { ViteDevServer } from 'vite';\nimport { createContext, type MiddlewareHandler, type RewritePayload } from '../middleware';\nimport { bundleCss, bundleScripts, getBundledFile } from './bundler';\nimport type { RenderResult, RequestInfo } from './entry-server';\nimport { resolveGlobalStyleHref } from './global-style';\nimport { escapeProp } from './render';\nimport { createHeadersFromExpressRequest, parseCookies } from './request';\n\nexport interface ServerOptions {\n root?: string;\n port?: number;\n base?: string;\n publicDir?: string;\n setupApp?: (app: any) => void | Promise<void>;\n app?: any; // Express\n /**\n * Externalize React island props into a single `<script id=\"_l5e_data_\">` at\n * the end of the document (referenced by `data-island-idx`) instead of inlining\n * a large `data-island-props` attribute on each element — keeps the SSR HTML\n * lean so crawlers read content first. Default true; set false for the legacy\n * inline behavior.\n */\n externalizeIslandProps?: boolean;\n}\n\nexport interface ServerContext {\n app: any; // Express app\n vite?: ViteDevServer;\n}\n\n/**\n * Apply or replace lang attribute on <html> tag\n */\nexport function applyHtmlLang(template: string, lang: string): string {\n // Escape so a loader-supplied lang (possibly derived from user input) cannot\n // break out of the attribute / <html> tag (XSS). escapeProp handles \", <, >, &.\n const safeLang = escapeProp(lang);\n return template.replace(/<html\\b([^>]*)>/i, (match, attrs) => {\n // Check if lang already exists\n if (/\\blang\\s*=/i.test(attrs)) {\n // Replace existing lang value (function replacer avoids $-pattern issues)\n return match.replace(/lang\\s*=\\s*\"[^\"]*\"/i, () => `lang=\"${safeLang}\"`);\n } else {\n // Add lang attribute\n return `<html lang=\"${safeLang}\"${attrs}>`;\n }\n });\n}\n\ntype EntryServerModule = {\n render: (\n url: string,\n requestInfo?: RequestInfo,\n options?: { externalizeIslandProps?: boolean },\n ) => Promise<RenderResult>;\n loadMiddleware?: () => Promise<MiddlewareHandler | undefined>;\n};\n\nfunction getRequestUrl(req: ExpressRequest): URL {\n return new URL(`${req.protocol}://${req.get('host')}${req.originalUrl}`);\n}\n\nfunction getRenderUrl(urlObject: URL, base: string): string {\n const requestPath = `${urlObject.pathname}${urlObject.search}`;\n return requestPath.replace(base, '') || '/';\n}\n\nfunction createWebRequestFromExpress(req: ExpressRequest): globalThis.Request {\n const init: RequestInit & { duplex?: 'half' } = {\n method: req.method,\n headers: createHeadersFromExpressRequest(req),\n };\n\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n init.body = req as unknown as BodyInit;\n init.duplex = 'half';\n }\n\n return new globalThis.Request(getRequestUrl(req).href, init);\n}\n\nfunction createRequestInfo(\n req: ExpressRequest,\n webRequest: globalThis.Request,\n base: string,\n locals: Record<string, unknown>,\n): RequestInfo {\n const urlObject = new URL(webRequest.url);\n const renderUrl = getRenderUrl(urlObject, base);\n const normalizedPath = renderUrl.startsWith('/') ? renderUrl : `/${renderUrl}`;\n const headers: Record<string, string> = {};\n webRequest.headers.forEach((value, key) => {\n headers[key] = value;\n });\n\n return {\n url: urlObject,\n path: normalizedPath,\n pathname: urlObject.pathname,\n method: webRequest.method,\n headers,\n cookies: parseCookies(webRequest.headers.get('cookie') ?? undefined),\n query: Object.fromEntries(urlObject.searchParams.entries()),\n ip: requestIp.getClientIp(req) ?? undefined,\n locals,\n };\n}\n\nfunction createRewriteRequest(\n payload: RewritePayload | undefined,\n currentRequest: globalThis.Request,\n currentUrl: URL,\n): globalThis.Request {\n if (!payload) {\n return currentRequest;\n }\n\n if (payload instanceof globalThis.Request) {\n return payload;\n }\n\n if (payload instanceof URL) {\n return new globalThis.Request(payload.href, currentRequest.clone());\n }\n\n return new globalThis.Request(new URL(payload, currentUrl).href, currentRequest.clone());\n}\n\nasync function sendWebResponse(\n req: ExpressRequest,\n res: ExpressResponse,\n response: globalThis.Response,\n): Promise<void> {\n res.status(response.status);\n const setCookieValues = getSetCookieHeaders(response.headers);\n response.headers.forEach((value, key) => {\n if (key.toLowerCase() === 'set-cookie') {\n return;\n }\n res.setHeader(key, value);\n });\n if (setCookieValues.length > 0) {\n res.setHeader('Set-Cookie', setCookieValues);\n }\n\n if (req.method === 'HEAD') {\n res.end();\n return;\n }\n\n const body = Buffer.from(await response.arrayBuffer());\n res.send(body);\n}\n\nfunction getSetCookieHeaders(headers: Headers): string[] {\n const getSetCookie = (headers as Headers & { getSetCookie?: () => string[] }).getSetCookie;\n if (typeof getSetCookie === 'function') {\n return getSetCookie.call(headers);\n }\n\n const raw = (headers as Headers & { raw?: () => Record<string, string[]> }).raw?.();\n if (raw?.['set-cookie']) {\n return raw['set-cookie'];\n }\n\n const value = headers.get('set-cookie');\n return value ? splitSetCookieHeader(value) : [];\n}\n\nfunction splitSetCookieHeader(value: string): string[] {\n const cookies: string[] = [];\n let start = 0;\n\n for (let i = 0; i < value.length; i++) {\n if (value[i] !== ',') continue;\n\n const rest = value.slice(i + 1);\n if (/^\\s*[^=;,]+=/.test(rest)) {\n cookies.push(value.slice(start, i).trim());\n start = i + 1;\n }\n }\n\n cookies.push(value.slice(start).trim());\n return cookies.filter(Boolean);\n}\n\nfunction createRawResponse(rendered: RenderResult): globalThis.Response | null {\n if (!rendered.rawResponse) {\n return null;\n }\n\n const { body, contentType, statusCode, headers } = rendered.rawResponse;\n const responseHeaders = new Headers(headers);\n responseHeaders.set('Content-Type', contentType);\n\n return new globalThis.Response(body as BodyInit, {\n status: statusCode || 200,\n headers: responseHeaders,\n });\n}\n\nasync function createPageResponse({\n rendered,\n template,\n manifest,\n root,\n distClientDir,\n isProduction,\n assetBase,\n}: {\n rendered: RenderResult;\n template: string;\n manifest?: Record<string, any>;\n root: string;\n distClientDir: string;\n isProduction: boolean;\n assetBase: string;\n}): Promise<globalThis.Response> {\n const rawResponse = createRawResponse(rendered);\n if (rawResponse) {\n return rawResponse;\n }\n\n if (rendered.redirect) {\n return new globalThis.Response(null, {\n status: rendered.redirect.statusCode,\n headers: {\n Location: rendered.redirect.url,\n },\n });\n }\n\n let scriptSrcList: string[] = rendered.scripts || [];\n let cssSrcList: string[] = rendered.styles || [];\n const islandEntries = rendered.islands || [];\n let cacheTags: string[] = rendered.cacheTags || [];\n const maxAge: number | undefined = rendered.maxAge;\n const sMaxAge: number | undefined = rendered.sMaxAge;\n const swr: number | undefined = rendered.swr;\n\n let extraHead = '';\n const emittedStyles = new Set<string>();\n const appendStylesheet = (href: string, crossorigin = false) => {\n if (emittedStyles.has(href)) return;\n emittedStyles.add(href);\n extraHead += `<link rel=\"stylesheet\"${crossorigin ? ' crossorigin' : ''} href=\"${escapeProp(href)}\">`;\n };\n let globalScripts: string[] = [];\n let islandRegistryScript = '';\n\n const globalStyleHref = resolveGlobalStyleHref({\n root,\n manifest,\n isProduction,\n base: assetBase,\n });\n if (globalStyleHref) appendStylesheet(globalStyleHref, isProduction);\n\n // Externalized island props → a single JSON script at the end of the document.\n // serialize-javascript with isJSON escapes `<`, `>`, `&` (and U+2028/2029) so the\n // props can't break out of the <script> block or inject markup (XSS). The runtime\n // reads it via `document.getElementById('_l5e_data_')` + JSON.parse.\n let islandDataScript = '';\n if (rendered.islandData && rendered.islandData.length > 0) {\n islandDataScript = `<script type=\"application/json\" id=\"_l5e_data_\">${serialize(\n rendered.islandData,\n { isJSON: true },\n )}</script>`;\n }\n\n if (isProduction && manifest) {\n scriptSrcList = scriptSrcList.filter((src) => !src.includes('.global.'));\n cssSrcList = cssSrcList.filter((src) => !src.includes('.global.'));\n\n const cssFiles = new Set<string>();\n const preloadFiles = new Set<string>();\n\n function collectFromEntry(entryKey: string): { file: string | null } {\n const entry = manifest![entryKey];\n if (!entry) return { file: null };\n\n if (entry.css) entry.css.forEach((css: string) => cssFiles.add(css));\n if (entry.imports) {\n entry.imports.forEach((importKey: string) => {\n const importedChunk = manifest![importKey];\n if (importedChunk?.file) preloadFiles.add(importedChunk.file);\n if (importedChunk?.css) {\n importedChunk.css.forEach((css: string) => cssFiles.add(css));\n }\n if (importedChunk?.imports) {\n importedChunk.imports.forEach((key: string) => {\n const chunk = manifest![key];\n if (chunk?.file) preloadFiles.add(chunk.file);\n if (chunk?.css) chunk.css.forEach((css: string) => cssFiles.add(css));\n });\n }\n });\n }\n\n return { file: entry.file };\n }\n\n const mappedScripts: string[] = [];\n for (const src of scriptSrcList) {\n const entryKey = src.replace(/^\\//, '');\n const { file } = collectFromEntry(entryKey);\n if (file) mappedScripts.push(`/${file}`);\n }\n\n const mappedCssFiles: string[] = [];\n for (const src of cssSrcList) {\n const entryKey = src.replace(/^\\//, '');\n const { file } = collectFromEntry(entryKey);\n if (file) {\n mappedCssFiles.push(`/${file}`);\n cssFiles.add(file);\n }\n }\n\n if (mappedScripts.length > 0) {\n const bundledScript = await bundleScripts(mappedScripts, distClientDir);\n scriptSrcList = bundledScript.filename ? [`/${bundledScript.filename}`] : mappedScripts;\n }\n\n if (mappedCssFiles.length > 0) {\n const bundledCss = await bundleCss(mappedCssFiles, distClientDir);\n if (bundledCss.filename) {\n cssSrcList = [`/${bundledCss.filename}`];\n }\n }\n\n const globalEntry = manifest['src/client.global.ts'];\n if (globalEntry) {\n if (globalEntry.css && globalEntry.css.length > 0) {\n globalEntry.css.forEach((cssFile: string) => {\n appendStylesheet(`/${cssFile}`, true);\n });\n }\n if (globalEntry.file) {\n globalScripts.push(`/${globalEntry.file}`);\n }\n }\n\n if (islandEntries.length > 0) {\n const islandMap: Record<string, string> = {};\n for (const island of islandEntries) {\n const entry = manifest[island.src];\n if (entry?.file) {\n islandMap[island.key] = `/${entry.file}`;\n }\n }\n if (Object.keys(islandMap).length > 0) {\n islandRegistryScript = `<script>window.__L5E_ISLANDS__=${serialize(islandMap)}</script>`;\n }\n }\n\n if (cssSrcList.length > 0) {\n cssSrcList.forEach((file) => appendStylesheet(file, true));\n }\n }\n\n if (!isProduction) {\n // Registry đã dedupe, nhưng vẫn lọc lại ở đây để dev không bao giờ ra thẻ trùng\n [...new Set(cssSrcList)].forEach((src) => appendStylesheet(src));\n }\n\n let allScripts = [...globalScripts, ...scriptSrcList];\n\n if (!isProduction) {\n const globalTsPath = path.join(root, 'src', 'client.global.ts');\n if (existsSync(globalTsPath)) {\n allScripts = ['/src/client.global.ts', ...allScripts];\n }\n\n // useClientJs('/src/client.global.ts') do user tự gọi sẽ trùng với entry\n // được prepend ở trên — registry không bắt được ca này nên dedupe lại\n allScripts = [...new Set(allScripts)];\n\n if (islandEntries.length > 0) {\n const islandMap: Record<string, string> = {};\n for (const island of islandEntries) {\n islandMap[island.key] = `/${island.src}`;\n }\n islandRegistryScript = `<script>window.__L5E_ISLANDS__=${serialize(islandMap)}</script>`;\n }\n }\n\n const scriptsHtml =\n islandDataScript +\n islandRegistryScript +\n allScripts.map((src) => `<script type=\"module\" src=\"${src}\"></script>`).join('');\n\n const templateWithLang = rendered.lang ? applyHtmlLang(template, rendered.lang) : template;\n\n // Replacer fns (not strings) so `$`-sequences in rendered HTML — e.g. an SSR\n // island body or user text containing \"$$\" / \"$&\" — aren't interpreted as\n // special String.replace replacement patterns.\n const html = rendered.rawHtml\n ? rendered.html || ''\n : templateWithLang\n .replace(`<!--app-head-->`, () => (rendered.head ?? '') + extraHead)\n .replace(`<!--app-html-->`, () => rendered.html ?? '')\n .replace(`<!--app-scripts-->`, () => scriptsHtml);\n\n const headers = new Headers({\n 'Content-Type': 'text/html',\n });\n\n const cacheControlParts: string[] = [];\n const cdnCacheControlParts: string[] = [];\n if (maxAge !== undefined) {\n cacheControlParts.push(`max-age=${maxAge}`);\n cdnCacheControlParts.push(`max-age=${maxAge}`);\n }\n\n if (sMaxAge !== undefined) {\n cdnCacheControlParts.push(`s-maxage=${sMaxAge}`);\n }\n\n // ko cho phép browser swr\n if (swr !== undefined) {\n cdnCacheControlParts.push(`stale-while-revalidate=${swr}`);\n }\n\n if ((cacheControlParts.length > 0 || cdnCacheControlParts.length > 0) && isProduction) {\n cacheControlParts.push('public');\n cacheControlParts.push('must-revalidate');\n\n cdnCacheControlParts.push('public');\n\n\n headers.set('Cache-Control', cacheControlParts.join(', '));\n headers.set('CDN-Cache-Control', cdnCacheControlParts.join(', '));\n }\n\n if (process.env.NODE_ENV === 'production') {\n cacheTags = optimizeCacheTags(cacheTags);\n }\n headers.set('Cache-Tag', ['global', ...cacheTags].join(','));\n\n return new globalThis.Response(html, {\n status: rendered.statusCode || 200,\n headers,\n });\n}\n\nexport async function createServer(options: ServerOptions = {}): Promise<ServerContext> {\n const root = options.root || process.cwd();\n const base = options.base || '/';\n const isProduction = process.env.NODE_ENV === 'production';\n const externalizeIslandProps = options.externalizeIslandProps ?? true;\n\n // Cached production assets\n const templateHtml = isProduction\n ? await fs.readFile(path.join(root, './index.html'), 'utf-8')\n : '';\n\n // Create http server\n // @ts-ignore\n const express = (await import('express')).default;\n const app = options.app || express();\n\n // Serve static files from public directory\n if (options.publicDir) {\n const publicPath = path.isAbsolute(options.publicDir)\n ? options.publicDir\n : path.join(root, options.publicDir);\n\n if (existsSync(publicPath)) {\n app.use(express.static(publicPath));\n }\n }\n\n // Add Vite or respective production middlewares\n let vite: ViteDevServer | undefined;\n const distClientDir = path.join(root, './dist/client');\n\n if (!isProduction) {\n const { createServer } = await import('vite');\n const configFile = path.join(root, 'vite.config.js');\n vite = await createServer({\n root,\n configFile,\n server: { middlewareMode: true },\n appType: 'custom',\n base,\n optimizeDeps: {\n exclude: ['@withl5e/l5e', 'file-type'],\n },\n ssr: {\n resolve: {\n conditions: ['development', 'default'],\n },\n },\n resolve: {\n conditions: ['development', 'default'],\n },\n });\n app.use(vite.middlewares);\n } else {\n // @ts-ignore\n const compression = (await import('compression')).default;\n // @ts-ignore\n const sirv = (await import('sirv')).default;\n app.use(compression());\n app.use(base, sirv(distClientDir, { extensions: [] }));\n\n // Route để serve bundled files từ memory map\n // Đặt route này trước route HTML để catch request trước\n app.get(\n `${base === '/' ? '' : base}/bundle-:hash.:ext`,\n async (req: ExpressRequest, res: ExpressResponse) => {\n try {\n const { hash, ext } = req.params;\n const filename = `bundle-${hash}.${ext}`;\n const bundledFile = getBundledFile(filename);\n\n if (!bundledFile) {\n return res.status(404).send('Bundled file not found');\n }\n\n res.set({\n 'Content-Type': bundledFile.mimeType,\n 'Cache-Control': 'public, max-age=31536000, immutable',\n });\n res.send(bundledFile.content);\n } catch (e: any) {\n console.error('[server] Error serving bundled file:', e);\n res.status(500).end('Internal server error');\n }\n },\n );\n }\n\n // Action routes — JSON body parsing scoped to action endpoints only\n app.use('/_l5e/action', express.json({ limit: '100kb' }));\n\n // Validate action key format: actionName_hexHash\n const ACTION_KEY_RE = /^[a-zA-Z]\\w+_[0-9a-f]{1,4}$/;\n\n // Load action registry and viewActions glob from virtual module (dev) or built bundle (prod)\n let prodActionRegistry: Record<string, { modulePath: string; actionName: string }> | null = null;\n let prodViewActions: Record<string, () => Promise<any>> | null = null;\n\n async function getActionRegistry(): Promise<\n Record<string, { modulePath: string; actionName: string }>\n > {\n if (!isProduction) {\n const mod = await vite!.ssrLoadModule('virtual:l5e-actions');\n return mod.actionRegistry || {};\n }\n if (!prodActionRegistry) {\n const registryPath = path.join(root, './dist/server/action-registry.json');\n const json = await fs.readFile(registryPath, 'utf-8');\n prodActionRegistry = JSON.parse(json);\n }\n return prodActionRegistry!;\n }\n\n async function getViewActions(): Promise<Record<string, () => Promise<any>>> {\n if (!isProduction) {\n const mod = await vite!.ssrLoadModule('virtual:l5e-actions');\n return mod.viewActions || {};\n }\n if (!prodViewActions) {\n const entryServerPath = path.join(root, './dist/server/entry-server.js');\n const mod = await import(pathToFileURL(entryServerPath).href);\n prodViewActions = mod.viewActions || {};\n }\n return prodViewActions!;\n }\n\n // Action route handler — hashed action keys\n // URL: /_l5e/action/:actionKey (e.g., /_l5e/action/loadMoreComments_a1b2)\n app.all('/_l5e/action/:actionKey', async (req: ExpressRequest, res: ExpressResponse) => {\n try {\n const { actionKey } = req.params;\n\n // Validate action key format\n if (!ACTION_KEY_RE.test(actionKey)) {\n return res.status(400).send('Invalid action key');\n }\n\n // Look up action in registry\n const registry = await getActionRegistry();\n const entry = registry[actionKey];\n if (!entry) {\n return res.status(404).send('Action not found');\n }\n\n const { modulePath, actionName } = entry;\n\n // Import action module via viewActions glob (works in both dev and prod)\n let actionModule: any;\n if (!isProduction) {\n try {\n actionModule = await vite!.ssrLoadModule(`/src/${modulePath}/actions.tsx`);\n } catch {\n actionModule = await vite!.ssrLoadModule(`/src/${modulePath}/actions.ts`);\n }\n } else {\n const viewActions = await getViewActions();\n // Find matching glob entry by modulePath\n const globKey = viewActions[`/src/${modulePath}/actions.tsx`]\n ? `/src/${modulePath}/actions.tsx`\n : viewActions[`/src/${modulePath}/actions.ts`]\n ? `/src/${modulePath}/actions.ts`\n : null;\n if (!globKey) {\n return res.status(404).send('Action module not found');\n }\n actionModule = await viewActions[globKey]();\n }\n\n // Look up exported action — use hasOwnProperty to avoid prototype pollution\n if (!Object.prototype.hasOwnProperty.call(actionModule, actionName)) {\n return res.status(404).send('Action not found');\n }\n const action = actionModule[actionName];\n if (!action || !action.handler) {\n return res.status(404).send('Action not found');\n }\n\n // Enforce the action's declared HTTP method. Previously `app.all` accepted\n // any method and `action.method` was ignored, so a state-changing POST\n // action could be triggered via GET (e.g. <img src>) — a CSRF vector.\n const allowedMethod = (action.method || 'GET').toUpperCase();\n if (req.method.toUpperCase() !== allowedMethod) {\n return res.status(405).set('Allow', allowedMethod).send('Method Not Allowed');\n }\n\n // Run the request through the middleware chain first — same as the HTML\n // handler — so `locals` (locale, country, preview flags, ...) is\n // populated for actions too. Previously this endpoint built its own\n // bare `requestInfo` and never invoked middleware at all, so `locals`\n // (and thus `getLocale()`) was always empty inside an action handler.\n //\n // Crucially, the action must run *inside* the `next` callback passed to\n // the middleware — not after `await`ing the middleware call — because a\n // middleware like `fromFetchMiddleware(paraglideMiddleware)` calls\n // `next()` synchronously inside a library-owned `AsyncLocalStorage.run()`\n // scope. Running the action afterward, once that scope has already\n // closed, would silently lose the library's own ambient `getLocale()`.\n const entryServerPath = path.join(root, './dist/server/entry-server.js');\n const entryServerModule: EntryServerModule = isProduction\n ? await import(pathToFileURL(entryServerPath).href)\n : await vite!.ssrLoadModule('@withl5e/l5e/entry-server');\n const { runInRenderContext } = await (isProduction\n ? import(pathToFileURL(entryServerPath).href)\n : vite!.ssrLoadModule('@withl5e/l5e/jsx-runtime'));\n const { renderJsxToHtmlString } = await (isProduction\n ? import(pathToFileURL(entryServerPath).href)\n : vite!.ssrLoadModule('@withl5e/l5e'));\n\n const locals: Record<string, unknown> = {};\n const initialRequest = createWebRequestFromExpress(req);\n const middlewareContext = createContext({\n request: initialRequest,\n locals,\n clientAddress: requestIp.getClientIp(req) ?? undefined,\n });\n\n const loadedMiddleware = await entryServerModule.loadMiddleware?.();\n const middlewareHandler: MiddlewareHandler =\n typeof loadedMiddleware === 'function' ? loadedMiddleware : (_ctx, dummyNext) => dummyNext();\n\n // If middleware short-circuits (returns its own Response — a redirect, a\n // 403, ...) instead of calling `next`, this callback never runs and that\n // response wins, same as it would for a page request.\n const response = await middlewareHandler(middlewareContext, async (payload) => {\n const nextRequest = createRewriteRequest(payload, middlewareContext.request, middlewareContext.url);\n const requestInfo = {\n ...createRequestInfo(req, nextRequest, base, locals),\n path: req.originalUrl,\n body: req.body,\n };\n\n const html = await runInRenderContext(\n async () => {\n const jsx = await action.handler(requestInfo);\n return renderJsxToHtmlString(jsx);\n },\n requestInfo,\n modulePath,\n );\n\n return new Response(html, { headers: { 'Content-Type': 'text/html' } });\n });\n\n await sendWebResponse(req, res, response);\n } catch (e: any) {\n vite?.ssrFixStacktrace?.(e);\n console.error('[l5e] Action error:', e.stack || e);\n res.status(500).send('Internal server error');\n }\n });\n\n // Serve HTML\n app.use(async (req: ExpressRequest, res: ExpressResponse) => {\n try {\n const url = req.originalUrl.replace(base, '');\n\n let template: string;\n let render: (\n url: string,\n requestInfo?: any,\n options?: { externalizeIslandProps?: boolean },\n ) => Promise<any>;\n let loadMiddleware: EntryServerModule['loadMiddleware'];\n let manifest: Record<string, any> | undefined;\n\n if (!isProduction) {\n // Always read fresh template in development\n template = await fs.readFile(path.join(root, './index.html'), 'utf-8');\n template = await vite!.transformIndexHtml(url, template);\n\n // Inject Vite HMR client for hot reload\n if (!template.includes('@vite/client')) {\n template = template.replace(\n '</head>',\n '<script type=\"module\" src=\"/@vite/client\"></script></head>',\n );\n }\n\n const entryServer = (await vite!.ssrLoadModule(\n '@withl5e/l5e/entry-server',\n )) as EntryServerModule;\n render = entryServer.render;\n loadMiddleware = entryServer.loadMiddleware;\n } else {\n template = templateHtml;\n const entryServerPath = path.join(root, './dist/server/entry-server.js');\n const entryServer = (await import(\n pathToFileURL(entryServerPath).href\n )) as EntryServerModule;\n render = entryServer.render;\n loadMiddleware = entryServer.loadMiddleware;\n // Read manifest to map hashed assets\n const manifestJson = await fs.readFile(\n path.join(root, './dist/client/.vite/manifest.json'),\n 'utf-8',\n );\n manifest = JSON.parse(manifestJson);\n }\n\n const loadedMiddleware = await loadMiddleware?.();\n const handler: MiddlewareHandler =\n typeof loadedMiddleware === 'function' ? loadedMiddleware : (_ctx, next) => next();\n\n const locals: Record<string, unknown> = {};\n const initialRequest = createWebRequestFromExpress(req);\n const context = createContext({\n request: initialRequest,\n requestInfo: createRequestInfo(req, initialRequest, base, locals),\n locals,\n clientAddress: requestIp.getClientIp(req),\n });\n\n const renderResponse = async (webRequest: globalThis.Request) => {\n const nextRequestInfo = createRequestInfo(req, webRequest, base, locals);\n const nextUrl = getRenderUrl(nextRequestInfo.url!, base);\n const nextRendered = await render(nextUrl, nextRequestInfo, {\n externalizeIslandProps,\n });\n return createPageResponse({\n rendered: nextRendered,\n template,\n manifest,\n root,\n distClientDir,\n isProduction,\n assetBase: isProduction ? base : vite!.config.base,\n });\n };\n\n const next = async (payload?: RewritePayload) => {\n const nextRequest = createRewriteRequest(payload, context.request, context.url);\n context.request = nextRequest;\n context.url = new URL(nextRequest.url);\n context.cookies = parseCookies(nextRequest.headers.get('cookie') ?? undefined);\n context.requestInfo = createRequestInfo(req, nextRequest, base, locals);\n return renderResponse(nextRequest);\n };\n\n context.rewrite = (payload: RewritePayload) => next(payload);\n\n const response = await handler(context, next);\n await sendWebResponse(req, res, response);\n } catch (e: any) {\n vite?.ssrFixStacktrace?.(e);\n console.error(e.stack);\n // Never leak stack traces to the client in production (info disclosure).\n res.status(500).end(isProduction ? 'Internal Server Error' : e.stack);\n }\n });\n\n return { app, vite };\n}\n\nexport async function startServer(options: ServerOptions = {}): Promise<void> {\n const port = options.port || 5173;\n\n // Create Express app first\n // @ts-ignore\n const express = (await import('express')).default;\n const app = express();\n\n // Call callback if provided to allow custom routes before setting up L5E server\n if (options.setupApp) {\n console.log('setupApp');\n await options.setupApp(app);\n }\n\n const { app: serverApp } = await createServer({ ...options, app });\n\n serverApp.listen(port, () => {\n console.log(`Server started at http://localhost:${port}`);\n });\n}\n\nconst MAX_TAGS = 1000;\n\nexport function hashTag(tag: string): string {\n // global tag is not hashed, better for ci/cd\n if (tag === 'global') {\n return 'global';\n }\n\n let hash = 0;\n for (let i = 0; i < tag.length; i++) {\n const char = tag.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash; // Convert to 32bit integer\n }\n return Math.abs(hash).toString(36).substring(0, 8);\n}\n\nexport function optimizeCacheTags(tags: Set<string> | string[]): string[] {\n const _tags = Array.isArray(tags) ? tags : [...tags];\n const result = _tags.slice(0, MAX_TAGS).map(hashTag);\n return result;\n}\n"],"mappings":";;;;;;;;;;;;mCAQI,IAAmE;AAQvE,SAAS,IAAmD;CAY1D,OAXA,AACE,OAAyB,YAAY;EAEnC,IAAM,IADU,EAAc,YAAY,GACb,CAAC,CAAC,QAAQ,qBAAqB,GAEtD,IADmB,EAAc,CACH,CAAC,CAAC,QAAQ,UAAU;EAC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