@withl5e/l5e 1.1.0-alpha.1 → 1.1.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -0
- package/dist/index.js +2 -2
- package/dist/island/compact-runtime.js +20 -3
- package/dist/island/compact-runtime.js.map +1 -1
- package/dist/{server-BOdEiJoN.js → server-C35BtVu8.js} +157 -63
- package/dist/server-C35BtVu8.js.map +1 -0
- package/dist/server.js +1 -1
- package/dist/{vite-plugin-R3LFxv9a.js → vite-plugin-Bln1di66.js} +91 -71
- package/dist/vite-plugin-Bln1di66.js.map +1 -0
- package/dist/vite-plugin.js +1 -1
- package/package.json +1 -1
- package/src/core/bundler.ts +31 -18
- package/src/core/chunking.ts +68 -2
- package/src/core/script-bundle-policy.ts +42 -0
- package/src/core/server.ts +117 -16
- package/src/core/vite-plugin.ts +15 -3
- package/src/island/compact-runtime.ts +44 -7
- package/dist/server-BOdEiJoN.js.map +0 -1
- package/dist/vite-plugin-R3LFxv9a.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-C35BtVu8.js","names":["serialize"],"sources":["../src/core/bundler.ts","../src/core/script-bundle-policy.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';\nimport type { ScriptBundlePolicy } from './script-bundle-policy';\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\nexport interface ScriptBundleOptions {\n compact?: boolean;\n islands?: Array<{ key: string; script: string }>;\n renderer?: string;\n name?: 'global' | 'bundle' | 'shared' | 'renderer' | 'island';\n inlineStaticRootClosure?: boolean;\n sharedUrl?: string;\n globalUrl?: string;\n exportScripts?: string[];\n externalScripts?: Record<string, 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/** Inline page roots only; their emitted dependencies retain canonical URLs. */\nfunction preserveBuildChunksPlugin(policy: ScriptBundlePolicy): Plugin {\n return {\n name: 'preserve-build-chunks',\n resolveId(source, importer) {\n if (!importer || source === VIRTUAL_ENTRY_ID) return null;\n const file = path.isAbsolute(source)\n ? path.normalize(source)\n : source.startsWith('.')\n ? path.resolve(path.dirname(importer), source)\n : null;\n if (!file) return null;\n // The virtual entry is the only place where an unshared page entry may\n // be inlined. Never traverse an emitted dependency to re-bundle its body.\n if (importer === VIRTUAL_ENTRY_ID && !policy.isPreserved(file)) return null;\n return { id: policy.assetUrl(file), external: 'absolute' };\n },\n };\n}\n\nfunction compactBuildPlugin(\n policy: ScriptBundlePolicy,\n sharedUrl?: string,\n globalUrl?: string,\n eagerFiles = new Set<string>(),\n externalFiles = new Map<string, string>(),\n): Plugin {\n return {\n name: 'compact-build-graph',\n resolveId(source, importer) {\n if (!importer || source === VIRTUAL_ENTRY_ID) return null;\n const file = path.isAbsolute(source)\n ? path.normalize(source)\n : source.startsWith('/')\n ? policy.fileForAssetUrl(source)\n : source.startsWith('.')\n ? path.resolve(path.dirname(importer), source)\n : null;\n if (!file) return null;\n return externalFiles.has(file)\n ? { id: externalFiles.get(file)!, external: 'absolute' }\n : policy.isShared(file) && sharedUrl\n ? { id: sharedUrl, external: 'absolute' }\n : policy.isGlobalOwned(file) && globalUrl\n ? { id: globalUrl, external: 'absolute' }\n : policy.isLazy(file) && !eagerFiles.has(file)\n ? { id: policy.assetUrl(file), external: 'absolute' }\n : { id: file };\n },\n };\n}\n\nasync function runScriptBundle(\n uniquePaths: string[],\n policy: ScriptBundlePolicy,\n options: ScriptBundleOptions = {},\n): Promise<BundleResult> {\n const roots = uniquePaths.map((p) => policy.fileForScript(p));\n const compact = options.compact && policy.compact;\n const suffix = policy.inlineableRoots(roots);\n const prefixChunks = new Map(\n roots.flatMap((file, index) =>\n !policy.isPreserved(file) && !suffix.has(file) ? [[file, `entry-${index}`] as const] : [],\n ),\n );\n const islands = (options.islands || []).map(({ key, script }) => ({\n key,\n file: policy.fileForScript(script),\n }));\n const renderer = options.renderer ? policy.fileForScript(options.renderer) : undefined;\n const exportFiles = (options.exportScripts || []).map((script) => policy.fileForScript(script));\n const eagerFiles = options.inlineStaticRootClosure\n ? policy.staticClosure(roots)\n : new Set<string>();\n const externalFiles = new Map(\n Object.entries(options.externalScripts || {}).map(([script, url]) => [\n policy.fileForScript(script),\n url,\n ]),\n );\n const entryContent = [\n ...roots.map((filePath) =>\n options.name === 'renderer'\n ? `export { createElement, reactDomClient } from ${JSON.stringify(filePath)};`\n : options.name === 'island'\n ? `import * as __island from ${JSON.stringify(filePath)}; export * from ${JSON.stringify(filePath)}; export default __island.default;`\n : options.name === 'shared'\n ? `export * from ${JSON.stringify(filePath)};`\n : `import ${JSON.stringify(filePath)};`,\n ),\n ...exportFiles.map((filePath) => `export * from ${JSON.stringify(filePath)};`),\n ].join('\\n');\n\n const rolldownOptions: InputOptions = {\n input: VIRTUAL_ENTRY_ID,\n plugins: [\n virtualEntryPlugin(entryContent),\n compact\n ? compactBuildPlugin(policy, options.sharedUrl, options.globalUrl, eagerFiles, externalFiles)\n : preserveBuildChunksPlugin(policy),\n ],\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 // Emitted file imports are resolved by preserveBuildChunksPlugin.\n return false;\n },\n };\n\n const outputOptions: OutputOptions = {\n format: 'es',\n codeSplitting: compact\n ? false\n : { groups: [{ name: (id) => prefixChunks.get(id) ?? null }] },\n minify: false,\n entryFileNames: `${options.name || 'bundle'}-[hash].js`,\n strictExecutionOrder: compact,\n chunkFileNames: `bundle-${generateHash(JSON.stringify(roots))}-[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 const code = (chunk.code || '').replace(/^\\/\\/#(?:end)?region[^\\r\\n]*(?:\\r?\\n)?/gm, '');\n bundledFilesMap.set(chunk.fileName, {\n content: code,\n hash: generateHash(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 const entryFile = bundledFilesMap.get(entryChunk.fileName)!;\n\n return {\n hash: entryFile.hash,\n filename: entryChunk.fileName,\n content: entryFile.content,\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 policy?: ScriptBundlePolicy,\n options: ScriptBundleOptions = {},\n): Promise<BundleResult> {\n if (scriptPaths.length === 0) {\n return EMPTY_RESULT;\n }\n\n if (!policy || policy.directory !== path.resolve(distClientDir)) {\n console.warn('[bundler] No matching build manifest; serving original script entries.');\n return EMPTY_RESULT;\n }\n\n const uniquePaths = [...new Set(scriptPaths)];\n const cacheKey = `scripts:${policy.cacheKey}:${JSON.stringify([uniquePaths, options])}`;\n\n try {\n return await dedupe(cacheKey, () => runScriptBundle(uniquePaths, policy, options));\n } catch (error) {\n console.error('[bundler] Error bundling scripts:', error);\n return EMPTY_RESULT;\n }\n}\n\nasync function runCssBundle(uniquePaths: string[], distClientDir: string): 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(cssPaths: string[], distClientDir: string): Promise<BundleResult> {\n if (cssPaths.length === 0) {\n return EMPTY_RESULT;\n }\n\n const uniquePaths = [...new Set(cssPaths)].sort();\n const cacheKey = `css:${JSON.stringify([path.resolve(distClientDir), uniquePaths])}`;\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 { createHash } from 'node:crypto';\nimport { realpathSync } from 'node:fs';\nimport path from 'node:path';\nimport type { Manifest } from 'vite';\nimport { withAssetBase } from './global-style';\n\n/** Preserve the emitted module boundaries chosen by the application's build. */\nexport interface ChunkingReport {\n mode?: string;\n chunks?: Array<{\n file: string;\n kind: string;\n canonicalShared?: boolean;\n canonicalGlobal?: boolean;\n }>;\n}\n\nexport function createScriptBundlePolicy(\n manifest: Manifest,\n distClientDir: string,\n base = '/',\n report?: ChunkingReport,\n) {\n const directory = path.resolve(distClientDir);\n // Rolldown resolves entry importers through symlinks/junctions. Use the same\n // physical directory for identity while retaining the caller's output scope.\n const assetDirectory = realpathSync(directory);\n const files = new Set<string>();\n const preserved = new Set<string>();\n const staticImports = new Map<string, string[]>();\n const lazy = new Set<string>();\n const jsEntries = Object.entries(manifest).filter(([, entry]) => /\\.[cm]?js$/.test(entry.file));\n\n function absoluteFile(file: string) {\n const absolute = path.resolve(assetDirectory, file);\n const relative = path.relative(assetDirectory, absolute);\n if (\n !relative ||\n relative === '..' ||\n relative.startsWith(`..${path.sep}`) ||\n path.isAbsolute(relative)\n ) {\n throw new Error(`[bundler] Asset is outside the client output: ${file}`);\n }\n return absolute;\n }\n\n const shared = new Set(\n (report?.chunks || [])\n .filter((chunk) => report?.mode === 'compact' && chunk.canonicalShared)\n .map((chunk) => absoluteFile(chunk.file)),\n );\n const globalOwned = new Set(\n (report?.chunks || [])\n .filter((chunk) => report?.mode === 'compact' && chunk.canonicalGlobal)\n .map((chunk) => absoluteFile(chunk.file)),\n );\n\n for (const [key, entry] of jsEntries) {\n const file = absoluteFile(entry.file);\n files.add(file);\n if (\n !entry.isEntry ||\n entry.isDynamicEntry ||\n key === 'src/client.global.ts' ||\n /(?:^|\\/)react\\//.test(entry.src || key)\n )\n preserved.add(file);\n }\n\n // Index the whole build, not just this request's roots. This also protects an\n // entry imported by another entry, even when both are selected on this page.\n for (const [, entry] of jsEntries) {\n for (const key of [...(entry.imports || []), ...(entry.dynamicImports || [])]) {\n const dependency = manifest[key];\n if (!dependency || !files.has(absoluteFile(dependency.file))) {\n throw new Error(`[bundler] Missing JavaScript manifest dependency: ${key}`);\n }\n preserved.add(absoluteFile(dependency.file));\n }\n staticImports.set(\n absoluteFile(entry.file),\n (entry.imports || []).map((key) => absoluteFile(manifest[key].file)),\n );\n }\n\n\n // A runtime page bundle keeps dynamic roots and their static closure as emitted\n // assets. This preserves download/init boundaries while allowing the page's\n // transformed preload helper to start the known closure in parallel.\n const staticallyInitial = new Set<string>();\n const visitInitial = (key: string) => {\n const entry = manifest[key];\n if (!entry || !/\\.[cm]?js$/.test(entry.file)) return;\n const file = absoluteFile(entry.file);\n if (staticallyInitial.has(file)) return;\n staticallyInitial.add(file);\n for (const dependency of entry.imports || []) visitInitial(dependency);\n };\n for (const [key, entry] of jsEntries) {\n if (entry.isEntry && !entry.isDynamicEntry) visitInitial(key);\n }\n const visitLazy = (key: string) => {\n const entry = manifest[key];\n if (!entry || !/\\.[cm]?js$/.test(entry.file)) return;\n const file = absoluteFile(entry.file);\n if (lazy.has(file) || staticallyInitial.has(file)) return;\n lazy.add(file);\n for (const dependency of entry.imports || []) visitLazy(dependency);\n };\n for (const [, entry] of jsEntries) {\n for (const key of entry.dynamicImports || []) visitLazy(key);\n }\n\n const cacheKey = createHash('sha256')\n .update(JSON.stringify([directory, assetDirectory, base, manifest]))\n .digest('hex');\n\n return {\n cacheKey,\n compact: report?.mode === 'compact',\n directory,\n fileForScript(script: string) {\n const normalizedBase = base === '/' ? '/' : `/${base.replace(/^\\/+|\\/+$/g, '')}/`;\n const relative = script.startsWith(normalizedBase)\n ? script.slice(normalizedBase.length)\n : script.replace(/^\\/+/, '');\n const file = absoluteFile(relative);\n if (!files.has(file)) throw new Error(`[bundler] Script is missing from manifest: ${script}`);\n return file;\n },\n fileForAssetUrl(url: string) {\n const normalizedBase = base === '/' ? '/' : `/${base.replace(/^\\/+|\\/+$/g, '')}/`;\n const relative = url.startsWith(normalizedBase)\n ? url.slice(normalizedBase.length)\n : url.replace(/^\\/+/, '');\n const file = absoluteFile(relative);\n return files.has(file) ? file : undefined;\n },\n isPreserved(file: string) {\n return preserved.has(file);\n },\n isShared(file: string) {\n return shared.has(file);\n },\n isGlobalOwned(file: string) {\n return globalOwned.has(file);\n },\n isLazy(file: string) {\n return lazy.has(file);\n },\n staticClosure(roots: string[]) {\n const closure = new Set<string>();\n const visit = (file: string) => {\n if (closure.has(file)) return;\n closure.add(file);\n for (const dependency of staticImports.get(file) || []) visit(dependency);\n };\n roots.forEach(visit);\n return closure;\n },\n sharedScripts() {\n return [...shared].map((file) =>\n withAssetBase(base, path.relative(assetDirectory, file).replace(/\\\\/g, '/')),\n );\n },\n globalOwnedScripts() {\n return [...globalOwned].map((file) =>\n withAssetBase(base, path.relative(assetDirectory, file).replace(/\\\\/g, '/')),\n );\n },\n inlineableRoots(roots: string[]) {\n // External ESM imports execute before any inlined body. Isolate prefix\n // roots in runtime chunks when a later root introduces a dependency effect;\n // only the suffix after the last such boundary can share the entry chunk.\n const visited = new Set<string>();\n let suffixStart = 0;\n function visit(file: string, rootIndex: number) {\n if (visited.has(file)) return;\n visited.add(file);\n for (const dependency of staticImports.get(file) || []) visit(dependency, rootIndex);\n if (preserved.has(file)) suffixStart = rootIndex;\n }\n roots.forEach((file, index) => {\n visit(file, index);\n if (preserved.has(file)) suffixStart = index + 1;\n });\n return new Set(roots.slice(suffixStart).filter((file) => !preserved.has(file)));\n },\n assetUrl(file: string) {\n if (!files.has(file)) throw new Error(`[bundler] Import is missing from manifest: ${file}`);\n return withAssetBase(base, path.relative(assetDirectory, file).replace(/\\\\/g, '/'));\n },\n };\n}\n\nexport type ScriptBundlePolicy = ReturnType<typeof createScriptBundlePolicy>;\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, withAssetBase } from './global-style';\nimport {\n createScriptBundlePolicy,\n type ChunkingReport,\n type ScriptBundlePolicy,\n} from './script-bundle-policy';\nimport type { Manifest } from 'vite';\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 scriptPolicy,\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 scriptPolicy?: ScriptBundlePolicy;\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 let compactSharedUrl: string | undefined;\n let compactGlobalUrl: string | undefined;\n if (scriptPolicy?.compact) {\n const sharedScripts = scriptPolicy.sharedScripts();\n if (sharedScripts.length > 1) {\n throw new Error('[l5e chunking] Compact build has more than one canonical shared root.');\n }\n if (sharedScripts.length === 1) {\n const bundledShared = await bundleScripts(sharedScripts, distClientDir, scriptPolicy, {\n compact: true,\n name: 'shared',\n });\n if (!bundledShared.filename) {\n throw new Error('[l5e chunking] Compact shared bundle failed.');\n }\n compactSharedUrl = withAssetBase(assetBase, bundledShared.filename);\n }\n const compactGlobalEntry = manifest['src/client.global.ts'];\n if (compactGlobalEntry?.file) {\n const bundledGlobal = await bundleScripts(\n [`/${compactGlobalEntry.file}`],\n distClientDir,\n scriptPolicy,\n {\n compact: true,\n name: 'global',\n sharedUrl: compactSharedUrl,\n exportScripts: scriptPolicy.globalOwnedScripts(),\n },\n );\n if (!bundledGlobal.filename) {\n throw new Error('[l5e chunking] Compact global bundle failed.');\n }\n compactGlobalUrl = withAssetBase(assetBase, bundledGlobal.filename);\n globalScripts.push(compactGlobalUrl);\n }\n const imports: Record<string, string> = {};\n if (compactSharedUrl) {\n for (const original of sharedScripts) imports[original] = compactSharedUrl;\n }\n if (compactGlobalUrl) {\n for (const original of scriptPolicy.globalOwnedScripts()) {\n imports[original] = compactGlobalUrl;\n }\n }\n if (Object.keys(imports).length > 0) {\n extraHead += `<script type=\"importmap\">${serialize({ imports })}</script>`;\n }\n }\n scriptSrcList = scriptSrcList.filter(\n (src) => src.replace(/^\\//, '') !== 'src/client.global.ts',\n );\n cssSrcList = cssSrcList.filter((src) => !src.includes('.global.'));\n\n const cssFiles = new Set<string>();\n const preloadFiles = new Set<string>();\n\n const visitedEntries = new Set<string>();\n function collectFromEntry(entryKey: string): { file: string | null } {\n const entry = manifest![entryKey];\n if (!entry) return { file: null };\n if (!visitedEntries.has(entryKey)) {\n visitedEntries.add(entryKey);\n for (const css of entry.css || []) cssFiles.add(css);\n for (const key of entry.imports || []) {\n const dependency = collectFromEntry(key);\n if (dependency.file) preloadFiles.add(dependency.file);\n }\n }\n return { file: entry.file };\n }\n\n function activationPlan(entryKeys: string[], excluded = new Set<string>()) {\n const js = new Set<string>();\n const css = new Set<string>();\n const visited = new Set<string>();\n const visit = (entryKey: string) => {\n if (visited.has(entryKey)) return;\n visited.add(entryKey);\n const entry = manifest![entryKey];\n if (!entry) return;\n for (const file of entry.css || []) css.add(withAssetBase(assetBase, file));\n if (!excluded.has(entryKey) && entry.file && /\\.[cm]?js$/.test(entry.file)) {\n const absolute = scriptPolicy!.fileForScript(`/${entry.file}`);\n if (!scriptPolicy!.isShared(absolute) && !scriptPolicy!.isGlobalOwned(absolute)) {\n js.add(withAssetBase(assetBase, entry.file));\n }\n }\n for (const dependency of entry.imports || []) visit(dependency);\n };\n entryKeys.forEach(visit);\n return { js: [...js], css: [...css] };\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, scriptPolicy, {\n compact: scriptPolicy?.compact,\n name: 'bundle',\n sharedUrl: compactSharedUrl,\n globalUrl: compactGlobalUrl,\n });\n scriptSrcList = bundledScript.filename\n ? [withAssetBase(assetBase, bundledScript.filename)]\n : mappedScripts.map((file) => withAssetBase(assetBase, file));\n }\n\n if (scriptPolicy?.compact && islandEntries.length > 0) {\n const rendererEntry = Object.entries(manifest).find(\n ([key, entry]) => entry.isEntry && key.includes('l5e-compact-renderer'),\n );\n if (!rendererEntry?.[1].file) {\n throw new Error('[l5e chunking] Compact renderer entry is missing from the manifest.');\n }\n const rendererOwnedKeys = new Set<string>();\n rendererOwnedKeys.add(rendererEntry[0]);\n const rendererDependencies = (rendererEntry[1].imports || []).filter((dependency: string) =>\n manifest[dependency]?.file?.includes('compact-renderer'),\n );\n if (rendererDependencies.length !== 1) {\n throw new Error(\n `[l5e chunking] Compact renderer expected one canonical export chunk; found ${rendererDependencies.length}. Multiple chunks can have colliding emitted export aliases.`,\n );\n }\n rendererOwnedKeys.add(rendererDependencies[0]);\n const bundledRenderer = await bundleScripts(\n [`/${rendererEntry[1].file}`],\n distClientDir,\n scriptPolicy,\n {\n compact: true,\n name: 'renderer',\n sharedUrl: compactSharedUrl,\n globalUrl: compactGlobalUrl,\n inlineStaticRootClosure: true,\n exportScripts: [...rendererOwnedKeys]\n .filter((key) => key !== rendererEntry[0])\n .map((key) => `/${manifest[key].file}`),\n },\n );\n if (!bundledRenderer.filename) {\n throw new Error('[l5e chunking] Compact renderer bundle failed.');\n }\n const rendererUrl = withAssetBase(assetBase, bundledRenderer.filename);\n const rendererAliases = Object.fromEntries(\n [...rendererOwnedKeys]\n .filter((key) => manifest[key]?.file)\n .map((key) => [`/${manifest[key].file}`, rendererUrl]),\n );\n const rendererImports = Object.fromEntries(\n [...rendererOwnedKeys]\n .filter((key) => manifest[key]?.file)\n .map((key) => [withAssetBase(assetBase, manifest[key].file), rendererUrl]),\n );\n if (Object.keys(rendererImports).length > 0) {\n extraHead += `<script type=\"importmap\">${serialize({ imports: rendererImports })}</script>`;\n }\n const islandMap: Record<\n string,\n { module: string; renderer: string; js: string[]; css: string[] }\n > = {};\n for (const island of islandEntries) {\n const entry = manifest[island.src];\n if (!entry?.file) continue;\n const bundledIsland = await bundleScripts([`/${entry.file}`], distClientDir, scriptPolicy, {\n compact: true,\n name: 'island',\n sharedUrl: compactSharedUrl,\n globalUrl: compactGlobalUrl,\n inlineStaticRootClosure: true,\n externalScripts: rendererAliases,\n });\n if (!bundledIsland.filename) {\n throw new Error(`[l5e chunking] Compact island bundle failed: ${island.src}`);\n }\n const islandUrl = withAssetBase(assetBase, bundledIsland.filename);\n const plan = activationPlan([island.src], rendererOwnedKeys);\n islandMap[island.key] = {\n module: islandUrl,\n renderer: rendererUrl,\n js: [rendererUrl, islandUrl],\n css: plan.css,\n };\n }\n islandRegistryScript = `<script>Object.assign(window.__L5E_ISLANDS__||={},${serialize(islandMap)});window.__L5E_BOOT_ISLANDS__?.()</script>`;\n }\n\n if (cssFiles.size > 0) {\n const bundledCss = await bundleCss(\n [...cssFiles].map((file) => `/${file}`),\n distClientDir,\n );\n if (bundledCss.filename) {\n cssSrcList = [withAssetBase(assetBase, bundledCss.filename)];\n }\n }\n\n cssFiles.clear();\n const globalEntry = manifest['src/client.global.ts'];\n collectFromEntry('src/client.global.ts');\n for (const cssFile of cssFiles) appendStylesheet(withAssetBase(assetBase, cssFile), true);\n if (globalEntry) {\n if (globalEntry.css && globalEntry.css.length > 0) {\n globalEntry.css.forEach((cssFile: string) => {\n appendStylesheet(withAssetBase(assetBase, cssFile), true);\n });\n }\n if (globalEntry.file) {\n if (scriptPolicy?.compact) {\n // The compact global is built before the page bundle so page imports\n // can target its live export bridge.\n } else {\n globalScripts.push(withAssetBase(assetBase, globalEntry.file));\n }\n }\n }\n\n for (const file of scriptPolicy?.compact ? [] : preloadFiles) {\n extraHead += `<link rel=\"modulepreload\" crossorigin href=\"${escapeProp(withAssetBase(assetBase, file))}\">`;\n }\n\n if (islandEntries.length > 0 && !scriptPolicy?.compact) {\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] = withAssetBase(assetBase, 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 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 // A production server owns one immutable build. Share its manifest/policy\n // across requests, just like its cached HTML template and SSR module.\n const productionManifest: Manifest | undefined = isProduction\n ? JSON.parse(await fs.readFile(path.join(distClientDir, '.vite/manifest.json'), 'utf-8'))\n : undefined;\n let scriptPolicy: ScriptBundlePolicy | undefined;\n if (productionManifest) {\n try {\n let chunkingReport: ChunkingReport | undefined;\n const reportPath = path.join(distClientDir, '.vite/l5e-chunks.json');\n if (existsSync(reportPath)) {\n chunkingReport = JSON.parse(await fs.readFile(reportPath, 'utf-8'));\n }\n scriptPolicy = createScriptBundlePolicy(\n productionManifest,\n distClientDir,\n base,\n chunkingReport,\n );\n } catch (error) {\n console.warn('[bundler] Invalid build manifest; serving original script entries.', error);\n }\n }\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 [\n withAssetBase(base, 'global-:hash.:ext'),\n withAssetBase(base, 'bundle-:hash.:ext'),\n withAssetBase(base, 'shared-:hash.:ext'),\n withAssetBase(base, 'renderer-:hash.:ext'),\n withAssetBase(base, 'island-:hash.:ext'),\n ],\n async (req: ExpressRequest, res: ExpressResponse) => {\n try {\n const { hash, ext } = req.params;\n const kind = path.basename(req.path).split('-', 1)[0];\n const filename = `${kind}-${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'\n ? loadedMiddleware\n : (_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(\n payload,\n middlewareContext.request,\n middlewareContext.url,\n );\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 manifest = productionManifest;\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 scriptPolicy,\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":";;;;;;;;;;;;;mCASI,IAAmE;AAQvE,SAAS,IAAmD;CAY1D,OAXA,AACE,OAAyB,YAAY;EAEnC,IAAM,IADU,EAAc,YAAY,GACb,CAAC,CAAC,QAAQ,qBAAqB,GAEtD,IADm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,KAAK,GAErB,EAAI,OAAO,GAAG,CAAC,CAAC,IAAI,IAAe,0BAA0B,EAAE,KAAK;EACtE;CACF,CAAC,GAEM;EAAE;EAAK;CAAK;AACrB;AAEA,eAAsB,EAAY,IAAyB,CAAC,GAAkB;CAC5E,IAAM,IAAO,EAAQ,QAAQ,MAIvB,KAAW,MAAM,OAAO,WAAA,CAAY,SACpC,IAAM,EAAQ;CAGpB,AAAI,EAAQ,aACV,QAAQ,IAAI,UAAU,GACtB,MAAM,EAAQ,SAAS,CAAG;CAG5B,IAAM,EAAE,KAAK,MAAc,MAAM,EAAa;EAAE,GAAG;EAAS;CAAI,CAAC;CAEjE,EAAU,OAAO,SAAY;EAC3B,QAAQ,IAAI,sCAAsC,GAAM;CAC1D,CAAC;AACH;AAEA,IAAM,IAAW;AAEjB,SAAgB,EAAQ,GAAqB;CAE3C,IAAI,MAAQ,UACV,OAAO;CAGT,IAAI,IAAO;CACX,KAAK,IAAI,IAAI,GAAG,IAAI,EAAI,QAAQ,KAAK;EACnC,IAAM,IAAO,EAAI,WAAW,CAAC;EAE7B,AADA,KAAQ,KAAQ,KAAK,IAAO,GAC5B,KAAc;CAChB;CACA,OAAO,KAAK,IAAI,CAAI,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,UAAU,GAAG,CAAC;AACnD;AAEA,SAAgB,EAAkB,GAAwC;CAGxE,QAFc,MAAM,QAAQ,CAAI,IAAI,IAAO,CAAC,GAAG,CAAI,EAAA,CAC9B,MAAM,GAAG,CAAQ,CAAC,CAAC,IAAI,CAChC;AACd"}
|
package/dist/server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as e, i as t, n, r, t as i } from "./server-
|
|
1
|
+
import { a as e, i as t, n, r, t as i } from "./server-C35BtVu8.js";
|
|
2
2
|
export { i as applyHtmlLang, n as createServer, r as hashTag, t as optimizeCacheTags, e as startServer };
|
|
@@ -13,118 +13,138 @@ function _(e) {
|
|
|
13
13
|
return n[0].startsWith("@") ? n.slice(0, 2).join("/") : n[0];
|
|
14
14
|
}
|
|
15
15
|
function v(e = {}) {
|
|
16
|
-
let t = e.shared || [];
|
|
16
|
+
let t = e.shared || [], n = e.islandRuntime;
|
|
17
|
+
if (n && !n.packages?.length && !n.modules?.length) throw Error("[l5e chunking] islandRuntime needs packages or modules.");
|
|
17
18
|
if (e.mode === "compact" && t.length > 1) throw Error("[l5e chunking] Compact mode accepts one canonical shared group.");
|
|
18
|
-
let
|
|
19
|
-
for (let
|
|
20
|
-
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(
|
|
21
|
-
if (!
|
|
22
|
-
if (
|
|
23
|
-
if (e.mode === "compact" &&
|
|
24
|
-
|
|
19
|
+
let r = /* @__PURE__ */ new Set();
|
|
20
|
+
for (let n of t) {
|
|
21
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(n.name) || r.has(n.name)) throw Error(`[l5e chunking] Invalid or duplicate shared group: ${n.name}`);
|
|
22
|
+
if (!n.packages?.length && !n.modules?.length) throw Error(`[l5e chunking] Group ${n.name} needs packages or modules.`);
|
|
23
|
+
if (n.maxSize !== void 0 && (!Number.isFinite(n.maxSize) || n.maxSize <= 0)) throw Error(`[l5e chunking] Invalid maxSize for ${n.name}`);
|
|
24
|
+
if (e.mode === "compact" && n.maxSize !== void 0) throw Error(`[l5e chunking] Compact mode cannot use maxSize for ${n.name}; it would split the canonical shared file.`);
|
|
25
|
+
r.add(n.name);
|
|
25
26
|
}
|
|
26
|
-
let
|
|
27
|
+
let i = "", a = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Set(), s = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Set(), u = (e) => _(e) ? `npm:${h(e).split("/node_modules/").at(-1)}` : h(c.relative(i, e));
|
|
27
28
|
return {
|
|
28
|
-
async resolve(e,
|
|
29
|
-
|
|
29
|
+
async resolve(e, r) {
|
|
30
|
+
i = e, a.clear(), o = /* @__PURE__ */ new Set(), s.clear(), l.clear();
|
|
30
31
|
for (let e of t) {
|
|
31
32
|
let t = /* @__PURE__ */ new Set();
|
|
32
|
-
for (let
|
|
33
|
-
let a = await n
|
|
34
|
-
if (!a) throw Error(`[l5e chunking] Cannot resolve ${
|
|
33
|
+
for (let n of e.modules || []) {
|
|
34
|
+
let a = await r(n, c.join(i, "index.html"));
|
|
35
|
+
if (!a) throw Error(`[l5e chunking] Cannot resolve ${n} in ${e.name}`);
|
|
35
36
|
t.add(a);
|
|
36
37
|
}
|
|
37
|
-
|
|
38
|
+
a.set(e, t);
|
|
39
|
+
}
|
|
40
|
+
if (n) for (let e of n.modules || []) {
|
|
41
|
+
let t = await r(e, c.join(i, "index.html"));
|
|
42
|
+
if (!t) throw Error(`[l5e chunking] Cannot resolve ${e} in islandRuntime`);
|
|
43
|
+
o.add(t);
|
|
38
44
|
}
|
|
39
45
|
},
|
|
40
|
-
analyze(
|
|
41
|
-
|
|
42
|
-
let
|
|
46
|
+
analyze(r) {
|
|
47
|
+
s.clear();
|
|
48
|
+
let i = new Map(r.map((e) => [e.id, e]));
|
|
43
49
|
if (e.mode === "compact") {
|
|
44
50
|
let e = /* @__PURE__ */ new Map();
|
|
45
|
-
for (let t of
|
|
46
|
-
let n = (
|
|
47
|
-
let o = e.get(
|
|
51
|
+
for (let t of r.filter((e) => e.isEntry)) {
|
|
52
|
+
let n = (r, a) => {
|
|
53
|
+
let o = e.get(r) || /* @__PURE__ */ new Map(), s = o.get(t.id);
|
|
48
54
|
if (s === !1 || s === a) return;
|
|
49
|
-
o.set(t.id, a), e.set(
|
|
50
|
-
let c =
|
|
55
|
+
o.set(t.id, a), e.set(r, o);
|
|
56
|
+
let c = i.get(r);
|
|
51
57
|
c && (c.importedIds.forEach((e) => n(e, a)), c.dynamicallyImportedIds.forEach((e) => n(e, !0)));
|
|
52
58
|
};
|
|
53
59
|
n(t.id, !1);
|
|
54
60
|
}
|
|
55
|
-
let t =
|
|
61
|
+
let t = r.find((e) => e.isEntry && h(e.id).endsWith("/src/client.global.ts"));
|
|
56
62
|
if (t) {
|
|
57
|
-
for (let [n, r] of e) if (!/\.css(?:\?|$)/.test(h(n)) && r.get(t.id) === !0 && [...r.keys()].some((e) => e !== t.id)) throw Error(`[l5e chunking] Compact mode cannot bridge a dynamic-only global overlap: ${
|
|
63
|
+
for (let [n, r] of e) if (!/\.css(?:\?|$)/.test(h(n)) && r.get(t.id) === !0 && [...r.keys()].some((e) => e !== t.id)) throw Error(`[l5e chunking] Compact mode cannot bridge a dynamic-only global overlap: ${u(n)}. Import it statically from global or place state behind an explicit shared root.`);
|
|
58
64
|
}
|
|
59
65
|
}
|
|
60
|
-
let c =
|
|
66
|
+
let c = r.filter((e) => e.isEntry || e.dynamicImporters.length > 0), d = /* @__PURE__ */ new Map();
|
|
61
67
|
for (let e of c) {
|
|
62
|
-
let t = /* @__PURE__ */ new Set(), n = (
|
|
63
|
-
if (t.has(
|
|
64
|
-
t.add(
|
|
65
|
-
let a =
|
|
68
|
+
let t = /* @__PURE__ */ new Set(), n = (r) => {
|
|
69
|
+
if (t.has(r)) return;
|
|
70
|
+
t.add(r);
|
|
71
|
+
let a = i.get(r);
|
|
66
72
|
if (!a) return;
|
|
67
|
-
let o =
|
|
68
|
-
o.add(e.id),
|
|
73
|
+
let o = d.get(r) || /* @__PURE__ */ new Set();
|
|
74
|
+
o.add(e.id), d.set(r, o), a.importedIds.forEach(n);
|
|
69
75
|
};
|
|
70
76
|
n(e.id);
|
|
71
77
|
}
|
|
72
|
-
let
|
|
73
|
-
for (let
|
|
74
|
-
let
|
|
75
|
-
|
|
76
|
-
let
|
|
77
|
-
if (
|
|
78
|
-
|
|
78
|
+
let f = (e) => i.get(e).isEntry ? h(e).endsWith("/src/client.global.ts") ? 0 : h(e).includes("virtual:l5e-compact-renderer") || /\/react\//.test(h(e)) && !_(e) ? 2 : 1 : 3, p = /* @__PURE__ */ new Set();
|
|
79
|
+
for (let i of r) {
|
|
80
|
+
let r = [...d.get(i.id) || []].sort(), c = r.map(u).sort(), m = t.filter((e) => a.get(e)?.has(i.id) || e.packages?.includes(_(i.id) || "")).sort((e, t) => (t.priority || 0) - (e.priority || 0));
|
|
81
|
+
m.forEach((e) => p.add(e)), m.length > 1 && l.add(`${u(i.id)} matches ${m.map((e) => e.name).join(", ")}; using ${m[0].name}.`);
|
|
82
|
+
let v = null, y = "Private dependency stays with its entry or dynamic import.", b = _(i.id), x = o.has(i.id) || n?.packages?.includes(b || "") === !0;
|
|
83
|
+
if (e.mode === "compact" && h(i.id).includes("virtual:l5e-compact-renderer")) v = "lazy-react-runtime", y = "Renderer joins the canonical React runtime activation.";
|
|
84
|
+
else if (e.mode === "compact" && !i.isEntry && (b === "react" || b === "react-dom" || b === "scheduler") && r.length > 0 && r.every((e) => f(e) >= 2)) v = "lazy-react-runtime", y = "Canonical React runtime is fetched when the first island activates.";
|
|
85
|
+
else if (!i.isEntry && r.length && m.length) {
|
|
86
|
+
let t = Math.min(...r.map(f)), n = t === 3 ? `lazy-${g(JSON.stringify(c))}` : [
|
|
79
87
|
"global",
|
|
80
88
|
"page",
|
|
81
89
|
"island"
|
|
82
90
|
][t];
|
|
83
|
-
|
|
84
|
-
} else e.mode === "compact" && !
|
|
85
|
-
|
|
86
|
-
group:
|
|
87
|
-
rule:
|
|
91
|
+
v = e.mode === "compact" ? "shared" : `shared-${m[0].name}-${n}`, y = `Configured group ${m[0].name}; activation ${n}.`;
|
|
92
|
+
} else e.mode === "compact" && !i.isEntry && x ? (v = "lazy-react-runtime", y = "Configured canonical island runtime is fetched with the first island consumer.") : e.mode === "compact" && !i.isEntry && r.some((e) => f(e) === 0) && r.some((e) => f(e) > 0) ? (v = "global-owner", y = "Static global/page overlap is exported by the canonical global artifact.") : e.mode !== "compact" && !i.isEntry && r.length > 1 && (v = `shared-auto-${g(JSON.stringify(c))}`, y = "Shared by the same static consumers; preserves dynamic import roots.");
|
|
93
|
+
s.set(i.id, {
|
|
94
|
+
group: v,
|
|
95
|
+
rule: m[0]?.name,
|
|
88
96
|
consumers: c,
|
|
89
|
-
reason:
|
|
97
|
+
reason: y
|
|
90
98
|
});
|
|
91
99
|
}
|
|
92
|
-
for (let e of t)
|
|
93
|
-
return [...
|
|
100
|
+
for (let e of t) p.has(e) || l.add(`Group ${e.name} matched no modules in this client build.`);
|
|
101
|
+
return [...l];
|
|
94
102
|
},
|
|
95
103
|
groups() {
|
|
96
|
-
return [
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
104
|
+
return [
|
|
105
|
+
...t.map((t) => ({
|
|
106
|
+
name: (e) => {
|
|
107
|
+
let n = s.get(e);
|
|
108
|
+
return n?.rule === t.name ? n.group : null;
|
|
109
|
+
},
|
|
110
|
+
maxSize: t.maxSize,
|
|
111
|
+
includeDependenciesRecursively: e.mode === "compact"
|
|
112
|
+
})),
|
|
113
|
+
{
|
|
114
|
+
name: (e) => {
|
|
115
|
+
let t = s.get(e)?.group;
|
|
116
|
+
return t === "lazy-react-runtime" ? null : t || null;
|
|
117
|
+
},
|
|
118
|
+
includeDependenciesRecursively: !1
|
|
100
119
|
},
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
}];
|
|
120
|
+
{
|
|
121
|
+
name: (e) => s.get(e)?.group === "lazy-react-runtime" ? "lazy-react-runtime" : null,
|
|
122
|
+
includeDependenciesRecursively: !0
|
|
123
|
+
}
|
|
124
|
+
];
|
|
107
125
|
},
|
|
108
126
|
report(t) {
|
|
109
127
|
return {
|
|
110
128
|
version: 2,
|
|
111
129
|
mode: e.mode || "default",
|
|
112
|
-
warnings: [...
|
|
130
|
+
warnings: [...l],
|
|
113
131
|
chunks: Object.values(t).flatMap((t) => {
|
|
114
132
|
if (t.type !== "chunk") return [];
|
|
115
|
-
let n =
|
|
133
|
+
let n = new Set(Object.keys(t.modules).map((e) => s.get(e)?.group));
|
|
134
|
+
if (e.mode === "compact" && n.has("global-owner") && n.has("lazy-react-runtime")) throw Error(`[l5e chunking] ${t.fileName} mixes global-owned and lazy island runtime modules. Keep eager owners separate before recursively collecting the lazy runtime.`);
|
|
135
|
+
let r = t.facadeModuleId ? u(t.facadeModuleId) : null, i = r === "src/client.global.ts" ? "global" : r && /(?:^|\/)react\//.test(r) ? "island" : t.isEntry || t.isDynamicEntry ? "page" : "shared";
|
|
116
136
|
return [{
|
|
117
137
|
file: t.fileName,
|
|
118
|
-
kind:
|
|
138
|
+
kind: i,
|
|
119
139
|
canonicalShared: e.mode === "compact" && t.name === "shared",
|
|
120
140
|
canonicalGlobal: e.mode === "compact" && t.name === "global-owner",
|
|
121
|
-
source:
|
|
141
|
+
source: r,
|
|
122
142
|
bytes: Buffer.byteLength(t.code),
|
|
123
143
|
imports: t.imports,
|
|
124
144
|
dynamicImports: t.dynamicImports,
|
|
125
145
|
modules: Object.keys(t.modules).map((e) => ({
|
|
126
|
-
id:
|
|
127
|
-
...
|
|
146
|
+
id: u(e),
|
|
147
|
+
...s.get(e)
|
|
128
148
|
}))
|
|
129
149
|
}];
|
|
130
150
|
})
|
|
@@ -385,7 +405,7 @@ function R(e = {}) {
|
|
|
385
405
|
...s
|
|
386
406
|
} : a.input;
|
|
387
407
|
return e.chunking && e.chunking.mode === "compact" && (u["l5e-compact-renderer"] = T), { build: {
|
|
388
|
-
...e.chunking && e.chunking.mode === "compact" ? { modulePreload: { resolveDependencies: (e, t) => t.filter((e) => !/\.[cm]?js(?:\?|$)/.test(e)) } } : {},
|
|
408
|
+
...e.chunking && e.chunking.mode === "compact" ? { modulePreload: { resolveDependencies: (e, t, n) => n.hostType === "html" ? t.filter((e) => !/\.[cm]?js(?:\?|$)/.test(e)) : t } } : {},
|
|
389
409
|
rolldownOptions: {
|
|
390
410
|
...t.build?.rolldownOptions,
|
|
391
411
|
input: Object.keys(u).length > 0 ? u : void 0,
|
|
@@ -398,7 +418,7 @@ function R(e = {}) {
|
|
|
398
418
|
let t = e.facadeModuleId?.replace(/\\/g, "/") || "";
|
|
399
419
|
return t.endsWith("/src/client.global.ts") ? "assets/global-[hash].js" : /\/react\//.test(t) ? e.name.startsWith("island-") ? "assets/[name]-[hash].js" : "assets/island-[name]-[hash].js" : "assets/bundle-[name]-[hash].js";
|
|
400
420
|
},
|
|
401
|
-
chunkFileNames: (e) => e.name.startsWith("shared-") ? "assets/[name]-[hash].js" : e.name === "shared" ? "assets/shared-[hash].js" : e.isDynamicEntry ? "assets/bundle-[name]-[hash].js" : "assets/shared-[name]-[hash].js"
|
|
421
|
+
chunkFileNames: (e) => e.name.startsWith("shared-") ? "assets/[name]-[hash].js" : e.name === "shared" ? "assets/shared-[hash].js" : e.name === "lazy-react-runtime" ? "assets/lazy-react-runtime-[hash].js" : e.isDynamicEntry ? "assets/bundle-[name]-[hash].js" : "assets/shared-[name]-[hash].js"
|
|
402
422
|
} } : {}
|
|
403
423
|
}
|
|
404
424
|
} };
|
|
@@ -406,12 +426,12 @@ function R(e = {}) {
|
|
|
406
426
|
resolveId(e) {
|
|
407
427
|
return e === y ? "\0virtual:l5e-views" : e === b ? "\0virtual:l5e-route" : e === x ? "\0virtual:l5e-ssr-entry" : e === S ? "\0virtual:l5e-global-loader" : e === C ? "\0virtual:l5e-island-strategies" : e === w ? "\0virtual:l5e-islands" : e === T ? "\0virtual:l5e-compact-renderer" : e === E ? "\0virtual:l5e-actions" : e === D ? "\0virtual:l5e-middleware" : null;
|
|
408
428
|
},
|
|
409
|
-
async transform(t, n,
|
|
410
|
-
if (n.replace(/\\/g, "/").endsWith("src/client.global.ts") && !
|
|
411
|
-
code: `import '@withl5e/l5e/island/${e.chunking && e.chunking.mode === "compact" ? "compact-runtime" : "runtime"}';\n${t}`,
|
|
429
|
+
async transform(t, n, a) {
|
|
430
|
+
if (n.replace(/\\/g, "/").endsWith("src/client.global.ts") && !a?.ssr) return {
|
|
431
|
+
code: `import '@withl5e/l5e/island/${i && e.chunking && e.chunking.mode === "compact" ? "compact-runtime" : "runtime"}';\n${t}`,
|
|
412
432
|
map: null
|
|
413
433
|
};
|
|
414
|
-
if (!
|
|
434
|
+
if (!a?.ssr) {
|
|
415
435
|
let e = n.replace(/\\/g, "/").match(/\/src\/(.+)\/actions\.(ts|tsx)$/);
|
|
416
436
|
if (e) {
|
|
417
437
|
let n = e[1], r = /export\s+const\s+(\w+)\s*=\s*defineAction\s*\(/g, i = [], a;
|
|
@@ -461,7 +481,7 @@ function R(e = {}) {
|
|
|
461
481
|
} catch (e) {
|
|
462
482
|
throw console.error(`[l5e] Failed to transform JSX in ${n}:`, e), e;
|
|
463
483
|
}
|
|
464
|
-
if (
|
|
484
|
+
if (a?.ssr) {
|
|
465
485
|
let e = t, n = !1;
|
|
466
486
|
if (e = e.replace(/import\.meta\.env\.([a-zA-Z_][a-zA-Z0-9_]*)/g, (e, t) => O.has(t) ? e : (n = !0, `process.env.${t}`)), e = e.replace(/import\.meta\.env\[(['"`])([^'"`]+)\1\]/g, (e, t, r) => O.has(r) ? e : (n = !0, `process.env[${t}${r}${t}]`)), n) return {
|
|
467
487
|
code: e,
|
|
@@ -494,4 +514,4 @@ export const actionRegistry = ${JSON.stringify(e)};`;
|
|
|
494
514
|
//#endregion
|
|
495
515
|
export { R as t };
|
|
496
516
|
|
|
497
|
-
//# sourceMappingURL=vite-plugin-
|
|
517
|
+
//# sourceMappingURL=vite-plugin-Bln1di66.js.map
|