@blinkk/root 1.0.0-rc.0 → 1.0.0-rc.2
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/dist/{chunk-LTNLNQWC.js → chunk-CY3DVKXO.js} +4 -3
- package/dist/chunk-CY3DVKXO.js.map +1 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +1 -1
- package/dist/core.d.ts +6 -6
- package/dist/functions.js +1 -1
- package/dist/middleware.d.ts +2 -2
- package/dist/node.d.ts +1 -1
- package/dist/render.d.ts +1 -1
- package/dist/render.js +58 -28
- package/dist/render.js.map +1 -1
- package/dist/{types-6dd5c0c0.d.ts → types-9209ea89.d.ts} +15 -15
- package/package.json +24 -25
- package/dist/chunk-LTNLNQWC.js.map +0 -1
|
@@ -436,8 +436,9 @@ async function build(rootProjectDir, options) {
|
|
|
436
436
|
}
|
|
437
437
|
},
|
|
438
438
|
outDir: path3.join(distDir, "routes"),
|
|
439
|
-
ssr:
|
|
440
|
-
ssrManifest:
|
|
439
|
+
ssr: true,
|
|
440
|
+
ssrManifest: true,
|
|
441
|
+
ssrEmitAssets: true,
|
|
441
442
|
manifest: true,
|
|
442
443
|
cssCodeSplit: true,
|
|
443
444
|
target: "esnext",
|
|
@@ -1295,4 +1296,4 @@ export {
|
|
|
1295
1296
|
start,
|
|
1296
1297
|
createProdServer
|
|
1297
1298
|
};
|
|
1298
|
-
//# sourceMappingURL=chunk-
|
|
1299
|
+
//# sourceMappingURL=chunk-CY3DVKXO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/commands/build.ts","../src/node/element-graph.ts","../src/render/asset-map/build-asset-map.ts","../src/utils/batch.ts","../src/cli/commands/dev.ts","../src/middleware/hooks.ts","../src/render/asset-map/dev-asset-map.ts","../src/utils/ports.ts","../src/utils/rand.ts","../src/cli/commands/preview.ts","../src/cli/commands/start.ts"],"sourcesContent":["/* eslint-disable no-control-regex */\nimport path from 'node:path';\nimport {fileURLToPath} from 'node:url';\n\nimport fsExtra from 'fs-extra';\nimport {dim, cyan} from 'kleur/colors';\nimport glob from 'tiny-glob';\nimport {build as viteBuild, Manifest, ManifestChunk, UserConfig} from 'vite';\n\nimport {getVitePlugins} from '../../core/plugin.js';\nimport {Route} from '../../core/types.js';\nimport {getElements} from '../../node/element-graph.js';\nimport {loadRootConfig} from '../../node/load-config.js';\nimport {BuildAssetMap} from '../../render/asset-map/build-asset-map.js';\nimport {htmlMinify} from '../../render/html-minify.js';\nimport {htmlPretty} from '../../render/html-pretty.js';\nimport {batchAsyncCalls} from '../../utils/batch.js';\nimport {\n copyGlob,\n fileExists,\n isDirectory,\n isJsFile,\n loadJson,\n makeDir,\n rmDir,\n writeFile,\n} from '../../utils/fsutils.js';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\ntype RenderModule = typeof import('../../render/render.js');\n\ninterface BuildOptions {\n ssrOnly?: boolean;\n mode?: string;\n concurrency?: number;\n}\n\nexport async function build(rootProjectDir?: string, options?: BuildOptions) {\n const mode = options?.mode || 'production';\n process.env.NODE_ENV = mode;\n\n const rootDir = path.resolve(rootProjectDir || process.cwd());\n const rootConfig = await loadRootConfig(rootDir, {command: 'build'});\n const distDir = path.join(rootDir, 'dist');\n const ssrOnly = options?.ssrOnly || false;\n\n console.log();\n console.log(`${dim('┃')} project: ${rootDir}`);\n console.log(`${dim('┃')} output: ${distDir}/html`);\n console.log(`${dim('┃')} mode: ${mode}`);\n console.log();\n\n await rmDir(distDir);\n await makeDir(distDir);\n\n const routeFiles: string[] = [];\n if (await isDirectory(path.join(rootDir, 'routes'))) {\n const pageFiles = await glob('routes/**/*', {cwd: rootDir});\n pageFiles.forEach((file) => {\n const parts = path.parse(file);\n if (!parts.name.startsWith('_') && isJsFile(parts.base)) {\n routeFiles.push(path.resolve(rootDir, file));\n }\n });\n }\n\n const elementGraph = await getElements(rootConfig);\n const elements = Object.values(elementGraph.sourceFiles).map((sourceFile) => {\n return sourceFile.filePath;\n });\n\n const bundleScripts: string[] = [];\n if (await isDirectory(path.join(rootDir, 'bundles'))) {\n const bundleFiles = await glob('bundles/*', {cwd: rootDir});\n bundleFiles.forEach((file) => {\n const parts = path.parse(file);\n if (isJsFile(parts.base)) {\n bundleScripts.push(path.resolve(rootDir, file));\n }\n });\n }\n\n const rootPlugins = rootConfig.plugins || [];\n const viteConfig = rootConfig.vite || {};\n const vitePlugins = [\n ...(viteConfig.plugins || []),\n ...getVitePlugins(rootPlugins),\n ];\n\n const baseConfig: UserConfig = {\n ...viteConfig,\n root: rootDir,\n mode: mode,\n esbuild: {\n ...viteConfig.esbuild,\n jsx: 'automatic',\n jsxImportSource: 'preact',\n treeShaking: true,\n },\n plugins: vitePlugins,\n };\n\n // Bundle the render.js file with vite along with any plugins `ssrInput()`\n // config values. These inputs are bundled through vite and support things\n // like `input.meta.glob()`.\n const ssrInput = {\n render: path.resolve(__dirname, './render.js'),\n };\n rootPlugins.forEach((plugin) => {\n if (plugin.ssrInput) {\n Object.assign(ssrInput, plugin.ssrInput());\n }\n });\n const noExternalConfig = viteConfig.ssr?.noExternal;\n const noExternal: Array<string | RegExp> = [];\n if (noExternalConfig) {\n if (Array.isArray(noExternalConfig)) {\n noExternal.push(...noExternalConfig);\n } else {\n noExternal.push(noExternalConfig as string | RegExp);\n }\n }\n await viteBuild({\n ...baseConfig,\n publicDir: false,\n build: {\n ...viteConfig?.build,\n rollupOptions: {\n ...viteConfig?.build?.rollupOptions,\n input: ssrInput,\n output: {\n format: 'esm',\n chunkFileNames: 'chunks/[hash].min.js',\n assetFileNames: 'assets/[name].[hash][extname]',\n sanitizeFileName: sanitizeFileName,\n },\n },\n outDir: path.join(distDir, 'server'),\n ssr: true,\n ssrManifest: false,\n cssCodeSplit: true,\n target: 'esnext',\n minify: false,\n modulePreload: {polyfill: false},\n reportCompressedSize: false,\n },\n ssr: {\n ...viteConfig.ssr,\n target: 'node',\n noExternal: ['@blinkk/root', ...noExternal],\n },\n });\n\n // Pre-render CSS deps from /routes/.\n await viteBuild({\n ...baseConfig,\n publicDir: false,\n build: {\n ...viteConfig?.build,\n rollupOptions: {\n ...viteConfig?.build?.rollupOptions,\n input: [...routeFiles],\n output: {\n format: 'esm',\n entryFileNames: 'assets/[name].[hash].min.js',\n assetFileNames: 'assets/[name].[hash][extname]',\n chunkFileNames: 'chunks/[hash].min.js',\n sanitizeFileName: sanitizeFileName,\n ...viteConfig?.build?.rollupOptions?.output,\n },\n },\n outDir: path.join(distDir, 'routes'),\n ssr: true,\n ssrManifest: true,\n ssrEmitAssets: true,\n manifest: true,\n cssCodeSplit: true,\n target: 'esnext',\n minify: true,\n modulePreload: {polyfill: false},\n reportCompressedSize: false,\n },\n });\n\n // Pre-render /elements/ and /bundles/.\n const clientInput = [...elements, ...bundleScripts];\n if (clientInput.length > 0) {\n await viteBuild({\n ...baseConfig,\n publicDir: false,\n build: {\n ...viteConfig?.build,\n rollupOptions: {\n ...viteConfig?.build?.rollupOptions,\n input: [...elements, ...bundleScripts],\n output: {\n format: 'esm',\n entryFileNames: 'assets/[name].[hash].min.js',\n assetFileNames: 'assets/[name].[hash][extname]',\n chunkFileNames: 'chunks/[hash].min.js',\n sanitizeFileName: sanitizeFileName,\n ...viteConfig?.build?.rollupOptions?.output,\n },\n },\n outDir: path.join(distDir, 'client'),\n ssr: false,\n ssrManifest: false,\n manifest: true,\n cssCodeSplit: true,\n target: 'esnext',\n minify: true,\n modulePreload: {polyfill: false},\n reportCompressedSize: false,\n },\n });\n } else {\n await writeFile(path.join(distDir, 'client/manifest.json'), '{}');\n }\n\n // Copy CSS files from dist/routes/**/*.css to dist/client/ and flatten the\n // routes manifest to ignore imported modules. Then add the route assets to\n // the client manifest.\n await copyGlob(\n '**/*.css',\n path.join(distDir, 'routes'),\n path.join(distDir, 'client')\n );\n const routesManifest = await loadJson<Manifest>(\n path.join(distDir, 'routes/manifest.json')\n );\n const clientManifest = await loadJson<Manifest>(\n path.join(distDir, 'client/manifest.json')\n );\n function collectRouteCss(\n asset: ManifestChunk,\n cssDeps: Set<string>,\n visited: Set<string>\n ) {\n if (!asset || !asset.file || visited.has(asset.file)) {\n return;\n }\n visited.add(asset.file);\n if (asset.css) {\n asset.css.forEach((dep) => cssDeps.add(dep));\n }\n if (asset.imports) {\n asset.imports.forEach((manifestKey) => {\n collectRouteCss(routesManifest[manifestKey], cssDeps, visited);\n });\n }\n }\n Object.keys(routesManifest).forEach((manifestKey) => {\n const asset = routesManifest[manifestKey];\n if (asset.isEntry) {\n const visited = new Set<string>();\n const cssDeps = new Set<string>();\n collectRouteCss(asset, cssDeps, visited);\n asset.css = Array.from(cssDeps);\n asset.imports = [];\n clientManifest[manifestKey] = asset;\n } else if (asset.file.endsWith('.css')) {\n clientManifest[manifestKey] = asset;\n }\n });\n\n // Use the output of the client build to generate an asset map, which is used\n // by the renderer for automatically injecting dependencies for a page.\n const assetMap = BuildAssetMap.fromViteManifest(\n rootConfig,\n clientManifest,\n elementGraph\n );\n\n // Save the asset map to `dist/client` for use by the prod SSR server.\n const rootManifest = assetMap.toJson();\n await writeFile(\n path.join(distDir, 'client/root-manifest.json'),\n JSON.stringify(rootManifest, null, 2)\n );\n\n // Save the element graph to `dist/client` for use by the prod SSR server.\n const elementGraphJson = elementGraph.toJson();\n await writeFile(\n path.join(distDir, 'client/root-element-graph.json'),\n JSON.stringify(elementGraphJson, null, 2)\n );\n\n // Write SSG output to `dist/html`.\n const buildDir = path.join(distDir, 'html');\n\n // Recursively copy files from `public` to `dist/html`.\n const publicDir = path.join(rootDir, 'public');\n if (fsExtra.existsSync(path.join(rootDir, 'public'))) {\n fsExtra.copySync(publicDir, buildDir, {dereference: true});\n } else {\n await makeDir(buildDir);\n }\n\n // Copy files from `dist/client/{assets,chunks}` to `dist/html` using the\n // root manifest. Ignore route files.\n console.log('\\njs/css output:');\n await Promise.all(\n Object.keys(rootManifest).map(async (src) => {\n // Don't expose route files in the final output. If any client-side code\n // relies on route dependencies, it should probably be broken out into a\n // shared component instead.\n if (isRouteFile(src)) {\n return;\n }\n const assetData = rootManifest[src];\n // Ignore files with no assetUrl, which can sometimes occur if a source\n // file is empty.\n if (!assetData.assetUrl) {\n return;\n }\n const assetRelPath = assetData.assetUrl.slice(1);\n const assetFrom = path.join(distDir, 'client', assetRelPath);\n const assetTo = path.join(buildDir, assetRelPath);\n // Ignore assets that don't exist. This is because build artifacts from\n // the routes/ folder are not copied to dist/client (only css deps are).\n if (!(await fileExists(assetFrom))) {\n console.log(`${assetFrom} does not exist`);\n return;\n }\n await fsExtra.copy(assetFrom, assetTo);\n printFileOutput(fileSize(assetTo), 'dist/html/', assetRelPath);\n })\n );\n\n // Pre-render HTML pages (SSG).\n if (!ssrOnly) {\n const render: RenderModule = await import(\n path.join(distDir, 'server/render.js')\n );\n const renderer = new render.Renderer(rootConfig, {assetMap, elementGraph});\n const sitemap = await renderer.getSitemap();\n\n console.log('\\nhtml output:');\n const batchSize = Number(options?.concurrency || 10);\n await batchAsyncCalls(Object.keys(sitemap), batchSize, async (urlPath) => {\n const {route, params} = sitemap[urlPath];\n try {\n const data = await renderer.renderRoute(route, {\n routeParams: params,\n });\n if (data.notFound) {\n return;\n }\n\n // The renderer currently assumes that all paths serve HTML.\n // TODO(stevenle): support non-HTML routes using `routes/[name].[ext].ts`.\n let outFilePath = path.join(urlPath.slice(1), 'index.html');\n if (outFilePath.endsWith('404/index.html')) {\n outFilePath = outFilePath.replace('404/index.html', '404.html');\n }\n const outPath = path.join(buildDir, outFilePath);\n\n let html = data.html || '';\n if (rootConfig.prettyHtml !== false) {\n html = await htmlPretty(html, rootConfig.prettyHtmlOptions);\n }\n // HTML minification is `true` by default. Set to `false` to disable.\n if (rootConfig.minifyHtml !== false) {\n html = await htmlMinify(html, rootConfig.minifyHtmlOptions);\n }\n await writeFile(outPath, html);\n\n printFileOutput(fileSize(outPath), 'dist/html/', outFilePath);\n } catch (e) {\n logBuildError({route, params, urlPath}, e);\n throw new Error(\n `BuildError: ${urlPath} (${route.src}) failed to build.`\n );\n }\n });\n }\n}\n\nfunction isRouteFile(filepath: string) {\n return filepath.startsWith('routes') && isJsFile(filepath);\n}\n\nfunction fileSize(filepath: string) {\n const stats = fsExtra.statSync(filepath);\n const bytes = stats.size;\n\n const k = 1024;\n if (bytes < k) {\n return (bytes / k).toFixed(2) + ' kB';\n }\n const units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + units[i];\n}\n\nfunction printFileOutput(\n fileSize: string,\n outputDir: string,\n outputFile: string\n) {\n const indent = ' '.repeat(2);\n const paddedSize = fileSize.padStart(9, ' ');\n console.log(\n `${indent}${dim(paddedSize)} ${dim(outputDir)}${cyan(outputFile)}`\n );\n}\n\nfunction sanitizeFileName(name: string): string {\n return (\n name\n // Remove placeholder vars from paths like routes/[...var].tsx.\n .replaceAll('...', '')\n .replaceAll('_', '')\n .replaceAll('[', '')\n .replaceAll(']', '')\n // Remove non-ascii chars and null bytes.\n .replace(/[^\\x00-\\x7F]/g, '')\n .replace(/\\x00/g, '')\n .toLowerCase()\n );\n}\n\ninterface BuildContext {\n route: Route;\n params: Record<string, string>;\n urlPath: string;\n}\n\nfunction logBuildError(ctx: BuildContext, e: Error) {\n const {route, params, urlPath} = ctx;\n const errorString = String(e.stack || e);\n console.error();\n if (Object.keys(params).length > 0) {\n console.error(\n `An error occurred building ${urlPath} (${route.src}) with params:\n${formatParams(params)}\n\nThe error was:\n ${errorString}\n `.trim()\n );\n } else {\n console.error(\n `An error occurred building ${urlPath} (${route.src})\n\nThe error was:\n ${errorString}`\n );\n }\n}\n\nfunction formatParams(params: Record<string, string>) {\n return Object.entries(params)\n .map(([key, value]) => {\n return ` ${key}: ${value}`;\n })\n .join('\\n');\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport glob from 'tiny-glob';\nimport {searchForWorkspaceRoot} from 'vite';\n\nimport {RootConfig} from '../core/config';\nimport {isValidTagName, parseTagNames} from '../utils/elements';\nimport {directoryContains, isDirectory, isJsFile} from '../utils/fsutils';\n\ninterface ElementSourceFile {\n /** Full file path. */\n filePath: string;\n /** Path relative to the root project directory. */\n relPath: string;\n}\n\n/**\n * Dependency graph for element files to capture which other elements are used\n * by any particular element.\n */\nexport class ElementGraph {\n /**\n * Element tagName => sourceFile.\n */\n readonly sourceFiles: {[tagName: string]: ElementSourceFile} = {};\n\n /**\n * Element tagName => set of element tagName dependencies.\n */\n private deps: Record<string, string[]> = {};\n\n constructor(sourceFiles: {[tagName: string]: ElementSourceFile}) {\n this.sourceFiles = sourceFiles;\n }\n\n toJson() {\n for (const tagName in this.sourceFiles) {\n this.deps[tagName] ??= this.parseDepsFromSource(tagName);\n }\n return {\n sourceFiles: this.sourceFiles,\n deps: this.deps,\n };\n }\n\n static fromJson(data: {deps: any; sourceFiles: any}) {\n const graph = new ElementGraph(data.sourceFiles);\n graph.deps = data.deps;\n return graph;\n }\n\n getDeps(tagName: string, visited?: Set<string>): string[] {\n visited ??= new Set();\n if (visited.has(tagName)) {\n return [];\n }\n\n visited.add(tagName);\n this.deps[tagName] ??= this.parseDepsFromSource(tagName);\n\n const deps = new Set(this.deps[tagName]);\n for (const depTagName of this.deps[tagName]) {\n for (const childDep of this.getDeps(depTagName, visited)) {\n deps.add(childDep);\n }\n }\n return Array.from(deps);\n }\n\n /**\n * Parses an element's source file for usage of other custom elements.\n */\n private parseDepsFromSource(tagName: string): string[] {\n const srcFile = this.sourceFiles[tagName];\n if (!srcFile) {\n throw new Error(`could not find file path for tagName <${tagName}>`);\n }\n const src = fs.readFileSync(srcFile.filePath, 'utf-8');\n const tagNames = parseTagNames(src);\n const deps = new Set<string>();\n for (const depTagName of tagNames) {\n if (depTagName !== tagName && depTagName in this.sourceFiles) {\n deps.add(depTagName);\n }\n }\n return Array.from(deps);\n }\n}\n\n/**\n * Returns a map of all the element file definitions in the project.\n */\nexport async function getElements(\n rootConfig: RootConfig\n): Promise<ElementGraph> {\n const rootDir = rootConfig.rootDir;\n\n const elementsDirs = getElementsDirs(rootConfig);\n const excludePatterns = rootConfig.elements?.exclude || [];\n const excludeElement = (moduleId: string) => {\n return excludePatterns.some((pattern) => Boolean(moduleId.match(pattern)));\n };\n\n const elementFilePaths: {[tagName: string]: ElementSourceFile} = {};\n for (const dirPath of elementsDirs) {\n if (await isDirectory(dirPath)) {\n const files = await glob('**/*', {cwd: dirPath});\n files.forEach((file) => {\n const parts = path.parse(file);\n if (isJsFile(parts.base) && isValidTagName(parts.name)) {\n const tagName = parts.name;\n const filePath = path.join(dirPath, file);\n const relPath = path.relative(rootDir, filePath);\n if (!excludeElement(relPath)) {\n elementFilePaths[tagName] = {filePath, relPath};\n }\n }\n });\n }\n }\n\n const graph = new ElementGraph(elementFilePaths);\n return graph;\n}\n\n/**\n * Get all element dirs.\n */\nexport function getElementsDirs(rootConfig: RootConfig) {\n const rootDir = rootConfig.rootDir;\n const workspaceRoot = searchForWorkspaceRoot(rootDir);\n\n const elementsDirs = [path.join(rootDir, 'elements')];\n const elementsInclude = rootConfig.elements?.include || [];\n\n for (const dirPath of elementsInclude) {\n const elementsDir = path.resolve(rootDir, dirPath);\n if (!directoryContains(rootDir, elementsDir)) {\n throw new Error(\n `the elements dir (${dirPath}) should be within the project's workspace (${workspaceRoot})`\n );\n }\n elementsDirs.push(elementsDir);\n }\n\n return elementsDirs;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport {Manifest} from 'vite';\n\nimport {RootConfig} from '../../core/config';\nimport {ElementGraph} from '../../node/element-graph';\nimport {isJsFile} from '../../utils/fsutils';\n\nimport {Asset, AssetMap} from './asset-map';\n\nexport type BuildAssetManifest = Record<\n string,\n {\n src: string;\n assetUrl: string;\n importedModules: string[];\n importedCss: string[];\n isElement: boolean;\n }\n>;\n\nexport class BuildAssetMap implements AssetMap {\n private rootConfig: RootConfig;\n private srcToAsset: Map<string, BuildAsset>;\n\n constructor(rootConfig: RootConfig) {\n this.rootConfig = rootConfig;\n this.srcToAsset = new Map();\n }\n\n async get(src: string): Promise<Asset | null> {\n const asset = this.srcToAsset.get(src);\n if (asset) {\n return asset;\n }\n // Try resolving the realpath of the asset, following symlinks.\n const realSrc = realPathRelativeTo(this.rootConfig.rootDir, src);\n if (realSrc !== src) {\n const asset = this.srcToAsset.get(realSrc);\n if (asset) {\n return asset;\n }\n }\n console.log(`could not find build asset: ${src}`);\n return null;\n }\n\n private add(asset: BuildAsset) {\n this.srcToAsset.set(asset.src, asset);\n }\n\n toJson(): BuildAssetManifest {\n const result: BuildAssetManifest = {};\n for (const src of this.srcToAsset.keys()) {\n result[src] = this.srcToAsset.get(src)!.toJson();\n }\n return result;\n }\n\n static fromViteManifest(\n rootConfig: RootConfig,\n clientManifest: Manifest,\n elementsGraph: ElementGraph\n ) {\n const assetMap = new BuildAssetMap(rootConfig);\n\n const elementFiles = new Set();\n Object.values(elementsGraph.sourceFiles).forEach((elementSource) => {\n elementFiles.add(elementSource.relPath);\n // Vite will resolve symlinks, so we need to follow the src and add the\n // realpath to the element files.\n const realSrc = realPathRelativeTo(\n rootConfig.rootDir,\n elementSource.relPath\n );\n if (realSrc !== elementSource.filePath) {\n elementFiles.add(realSrc);\n }\n });\n\n Object.keys(clientManifest).forEach((manifestKey) => {\n const src = manifestKey;\n const manifestChunk = clientManifest[manifestKey];\n const isElement = elementFiles.has(src);\n // NOTES(stevenle): routes/ files are included in the manifest so for\n // their CSS deps, but do not have an asset URL.\n const assetUrl =\n src.startsWith('routes/') && isJsFile(src)\n ? ''\n : `/${manifestChunk.file}`;\n const assetData = {\n src: src,\n assetUrl: assetUrl,\n importedModules: manifestChunk.imports || [],\n importedCss: (manifestChunk.css || []).map((relPath) => `/${relPath}`),\n isElement: isElement,\n };\n assetMap.add(new BuildAsset(assetMap, assetData));\n });\n\n return assetMap;\n }\n\n static fromRootManifest(\n rootConfig: RootConfig,\n rootManifest: BuildAssetManifest\n ) {\n const assetMap = new BuildAssetMap(rootConfig);\n Object.keys(rootManifest).forEach((moduleId) => {\n const assetData = rootManifest[moduleId];\n assetMap.add(new BuildAsset(assetMap, assetData));\n });\n return assetMap;\n }\n}\n\n/**\n * Returns the realpath of a src file, relative to the rootDir.\n */\nfunction realPathRelativeTo(rootDir: string, src: string) {\n const fullPath = path.resolve(rootDir, src);\n if (!fs.existsSync(fullPath)) {\n return src;\n }\n const realpath = fs.realpathSync(path.resolve(rootDir, src));\n return path.relative(rootDir, realpath);\n}\n\nexport class BuildAsset {\n src: string;\n assetUrl: string;\n private assetMap: BuildAssetMap;\n private importedModules: string[];\n private importedCss: string[];\n isElement: boolean;\n\n constructor(\n assetMap: BuildAssetMap,\n assetData: {\n src: string;\n assetUrl: string;\n importedModules: string[];\n importedCss: string[];\n isElement: boolean;\n }\n ) {\n this.assetMap = assetMap;\n this.src = assetData.src;\n this.assetUrl = assetData.assetUrl;\n this.importedModules = assetData.importedModules;\n this.importedCss = assetData.importedCss;\n this.isElement = assetData.isElement;\n }\n\n async getCssDeps(): Promise<string[]> {\n const visited = new Set<string>();\n const deps = new Set<string>();\n await this.collectCss(this, deps, visited);\n return Array.from(deps);\n }\n\n async getJsDeps(): Promise<string[]> {\n const visited = new Set<string>();\n const deps = new Set<string>();\n await this.collectJs(this, deps, visited);\n return Array.from(deps);\n }\n\n private async collectJs(\n asset: BuildAsset | null,\n urls: Set<string>,\n visited: Set<string>\n ) {\n if (!asset) {\n return;\n }\n if (!asset.src) {\n return;\n }\n if (visited.has(asset.src)) {\n return;\n }\n visited.add(asset.src);\n if (asset.isElement) {\n urls.add(asset.assetUrl);\n }\n await Promise.all(\n asset.importedModules.map(async (src) => {\n const importedAsset = (await this.assetMap.get(src)) as BuildAsset;\n this.collectJs(importedAsset, urls, visited);\n })\n );\n }\n\n private async collectCss(\n asset: BuildAsset | null,\n urls: Set<string>,\n visited: Set<string>\n ) {\n if (!asset) {\n return;\n }\n if (!asset.src) {\n return;\n }\n if (visited.has(asset.src)) {\n return;\n }\n visited.add(asset.src);\n if (asset.importedCss) {\n asset.importedCss.forEach((cssUrl) => urls.add(cssUrl));\n }\n await Promise.all(\n asset.importedModules.map(async (moduleId) => {\n const importedAsset = (await this.assetMap.get(moduleId)) as BuildAsset;\n this.collectCss(importedAsset, urls, visited);\n })\n );\n }\n\n toJson() {\n return {\n src: this.src,\n assetUrl: this.assetUrl,\n importedModules: this.importedModules,\n importedCss: this.importedCss,\n isElement: this.isElement,\n };\n }\n}\n","export async function batchAsyncCalls<T, U>(\n data: T[],\n batchSize: number,\n asyncFunction: (item: T) => Promise<U>\n): Promise<U[]> {\n const result: U[] = [];\n const batches = Math.ceil(data.length / batchSize);\n for (let i = 0; i < batches; i++) {\n const batch = data.slice(i * batchSize, (i + 1) * batchSize);\n const batchResults = await Promise.all(batch.map(asyncFunction));\n result.push(...batchResults);\n }\n return result;\n}\n","import path from 'node:path';\nimport {fileURLToPath} from 'node:url';\n\nimport cookieParser from 'cookie-parser';\nimport {default as express} from 'express';\nimport {dim} from 'kleur/colors';\nimport sirv from 'sirv';\nimport glob from 'tiny-glob';\n\nimport {RootConfig} from '../../core/config.js';\nimport {configureServerPlugins} from '../../core/plugin.js';\nimport {Server, Request, Response, NextFunction} from '../../core/types.js';\nimport {hooksMiddleware} from '../../middleware/hooks.js';\nimport {\n rootProjectMiddleware,\n trailingSlashMiddleware,\n} from '../../middleware/middleware.js';\nimport {sessionMiddleware} from '../../middleware/session.js';\nimport {getElements, getElementsDirs} from '../../node/element-graph.js';\nimport {loadRootConfig} from '../../node/load-config.js';\nimport {createViteServer} from '../../node/vite.js';\nimport {DevServerAssetMap} from '../../render/asset-map/dev-asset-map.js';\nimport {dirExists, isDirectory, isJsFile} from '../../utils/fsutils.js';\nimport {findOpenPort} from '../../utils/ports.js';\nimport {randString} from '../../utils/rand.js';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\ntype RenderModule = typeof import('../../render/render.js');\n\nexport interface DevOptions {\n host?: string;\n}\n\nexport async function dev(rootProjectDir?: string, options?: DevOptions) {\n process.env.NODE_ENV = 'development';\n const rootDir = path.resolve(rootProjectDir || process.cwd());\n const defaultPort = parseInt(process.env.PORT || '4007');\n const host = options?.host || 'localhost';\n const port = await findOpenPort(defaultPort, defaultPort + 10);\n console.log();\n console.log(`${dim('┃')} project: ${rootDir}`);\n console.log(`${dim('┃')} server: http://${host}:${port}`);\n console.log(`${dim('┃')} mode: development`);\n console.log();\n const server = await createDevServer({rootDir, port});\n server.listen(port, host);\n}\n\nexport async function createDevServer(options?: {\n rootDir?: string;\n port?: number;\n}): Promise<Server> {\n const rootDir = path.resolve(options?.rootDir || process.cwd());\n const rootConfig = await loadRootConfig(rootDir, {command: 'dev'});\n const port = options?.port;\n\n const server: Server = express();\n server.disable('x-powered-by');\n\n // Inject req context vars.\n server.use(rootProjectMiddleware({rootConfig}));\n server.use(await viteServerMiddleware({rootConfig, port}));\n server.use(hooksMiddleware());\n\n // Session middleware for handling session cookies.\n const sessionCookieSecret =\n rootConfig.server?.sessionCookieSecret || randString(36);\n server.use(cookieParser(sessionCookieSecret));\n server.use(sessionMiddleware());\n\n const plugins = rootConfig.plugins || [];\n await configureServerPlugins(\n server,\n async () => {\n // Add user-configured middlewares from `root.config.ts`.\n const userMiddlewares = rootConfig.server?.middlewares || [];\n for (const middleware of userMiddlewares) {\n server.use(middleware);\n }\n\n // Add static file middleware.\n const publicDir = path.join(rootDir, 'public');\n if (await dirExists(publicDir)) {\n server.use(sirv(publicDir, {dev: false}));\n }\n\n // Add the root.js dev server middlewares.\n server.use(trailingSlashMiddleware({rootConfig}));\n server.use(rootDevServerMiddleware());\n server.use(rootDevServer404Middleware());\n server.use(rootDevServer500Middleware());\n },\n plugins,\n {type: 'dev', rootConfig}\n );\n\n return server;\n}\n\n/**\n * Middleware that initializes a vite server and injects it into the request\n * context.\n */\nasync function viteServerMiddleware(options: {\n rootConfig: RootConfig;\n port?: number;\n}) {\n const rootConfig = options.rootConfig;\n const rootDir = rootConfig.rootDir;\n\n let elementGraph = await getElements(rootConfig);\n const elements = Object.values(elementGraph.sourceFiles).map((sourceFile) => {\n return sourceFile.relPath;\n });\n\n const bundleScripts: string[] = [];\n if (await isDirectory(path.join(rootDir, 'bundles'))) {\n const bundleFiles = await glob('bundles/*', {cwd: rootDir});\n bundleFiles.forEach((file) => {\n const parts = path.parse(file);\n if (isJsFile(parts.base)) {\n bundleScripts.push(file);\n }\n });\n }\n\n const optimizeDeps = [...elements, ...bundleScripts];\n const viteServer = await createViteServer(rootConfig, {\n port: options.port,\n optimizeDeps: optimizeDeps,\n });\n\n // Watch for file changes and re-generate the elements graph if any elements\n // are added or deleted.\n function isInElementsDir(changedFilePath: string) {\n const filePath = path.resolve(changedFilePath);\n const elementsDirs = getElementsDirs(rootConfig);\n return elementsDirs.some((dirPath) => filePath.startsWith(dirPath));\n }\n viteServer.watcher.on('add', async (filePath: string) => {\n if (isInElementsDir(filePath)) {\n // Re-generate the elements graph.\n elementGraph = await getElements(rootConfig);\n console.log(`element added: ${filePath}`);\n }\n });\n viteServer.watcher.on('unlink', async (filePath: string) => {\n if (isInElementsDir(filePath)) {\n // Re-generate the elements graph.\n elementGraph = await getElements(rootConfig);\n console.log(`element deleted: ${filePath}`);\n }\n });\n\n return async (req: Request, res: Response, next: NextFunction) => {\n try {\n // Add the viteServer to the req.\n req.viteServer = viteServer;\n // Dynamically import the render.js module using vite's SSR import loader.\n const renderModulePath = path.resolve(__dirname, './render.js');\n const render = (await viteServer.ssrLoadModule(\n renderModulePath\n )) as RenderModule;\n // Create a dev asset map using Vite dev server's module graph.\n const assetMap = new DevServerAssetMap(\n rootConfig,\n viteServer.moduleGraph\n );\n // Add a renderer object to the req for plugins and other middleware to\n // use.\n req.renderer = new render.Renderer(rootConfig, {assetMap, elementGraph});\n // Run the viteServer middlewares to handle vite-specific endpoints.\n viteServer.middlewares(req, res, next);\n } catch (e) {\n next(e);\n }\n };\n}\n\nfunction rootDevServerMiddleware() {\n return async (req: Request, res: Response, next: NextFunction) => {\n const renderer = req.renderer!;\n const viteServer = req.viteServer!;\n try {\n await renderer.handle(req, res, next);\n } catch (err) {\n // If an error is caught, let Vite fix the stack trace so it maps back to\n // your actual source code.\n viteServer.ssrFixStacktrace(err);\n next(err);\n }\n };\n}\n\nfunction rootDevServer404Middleware() {\n return async (req: Request, res: Response) => {\n console.error(`❓ 404 ${req.originalUrl}`);\n if (req.renderer) {\n const url = req.path;\n const ext = path.extname(url);\n if (!ext) {\n const renderer = req.renderer;\n const data = await renderer.renderDevServer404(req);\n const html = data.html || '';\n res.status(404).set({'Content-Type': 'text/html'}).end(html);\n return;\n }\n }\n res.status(404).set({'Content-Type': 'text/plain'}).end('404');\n };\n}\n\nfunction rootDevServer500Middleware() {\n return async (err: any, req: Request, res: Response, next: NextFunction) => {\n console.error(`❗ 500 ${req.originalUrl}`);\n console.error(String(err.stack || err));\n if (req.renderer) {\n const url = req.path;\n const ext = path.extname(url);\n if (!ext) {\n const renderer = req.renderer;\n const data = await renderer.renderDevServer500(req, err);\n const html = data.html || '';\n res.status(500).set({'Content-Type': 'text/html'}).end(html);\n return;\n }\n }\n next(err);\n };\n}\n","import {Request, Response, NextFunction} from '../core/types';\n\nexport function hooksMiddleware() {\n return (req: Request, res: Response, next: NextFunction) => {\n req.hooks = new Hooks();\n next();\n };\n}\n\nexport type HooksCallbackFn = (...args: any[]) => any;\n\nexport class Hooks {\n private callbacks: {[name: string]: HooksCallbackFn[]} = {};\n\n add(name: string, cb: (...args: any[]) => any) {\n this.callbacks[name] ??= [];\n this.callbacks[name].push(cb);\n }\n\n trigger(name: string, ...args: any[]) {\n const callbacks = this.callbacks[name] || [];\n callbacks.forEach((cb) => {\n cb(...args);\n });\n }\n}\n","import path from 'node:path';\n\nimport {ModuleGraph, ModuleNode, searchForWorkspaceRoot} from 'vite';\n\nimport {RootConfig} from '../../core/config';\nimport {directoryContains} from '../../utils/fsutils';\n\nimport {Asset, AssetMap} from './asset-map';\n\nexport class DevServerAssetMap implements AssetMap {\n private rootConfig: RootConfig;\n private moduleGraph: ModuleGraph;\n\n constructor(rootConfig: RootConfig, moduleGraph: ModuleGraph) {\n this.rootConfig = rootConfig;\n this.moduleGraph = moduleGraph;\n }\n\n async get(src: string): Promise<Asset | null> {\n const file = path.resolve(this.rootConfig.rootDir, src);\n\n const viteModules = this.moduleGraph.getModulesByFile(file);\n if (viteModules && viteModules.size > 0) {\n const [viteModule] = viteModules;\n return new DevServerAsset(src, {\n assetMap: this,\n viteModule: viteModule,\n });\n }\n\n // On dev, in some cases the module doesn't make it into the module graph\n // so return a generic asset.\n if (file.startsWith(this.rootConfig.rootDir)) {\n const assetUrl = file.slice(this.rootConfig.rootDir.length);\n return {\n src: src,\n assetUrl: assetUrl,\n getCssDeps: async () => [],\n getJsDeps: async () => [assetUrl],\n };\n }\n const workspaceRoot = searchForWorkspaceRoot(this.rootConfig.rootDir);\n if (await directoryContains(workspaceRoot, file)) {\n const assetUrl = `/@fs/${file}`;\n return {\n src: src,\n assetUrl: assetUrl,\n getCssDeps: async () => [],\n getJsDeps: async () => [assetUrl],\n };\n }\n\n console.log(`could not find asset in asset map: ${src}`);\n return null;\n }\n\n filePathToSrc(file: string) {\n return path.relative(this.rootConfig.rootDir, file);\n }\n}\n\nexport class DevServerAsset implements Asset {\n src: string;\n moduleId: string;\n assetUrl: string;\n private assetMap: DevServerAssetMap;\n private viteModule: ModuleNode;\n\n constructor(\n src: string,\n options: {\n assetMap: DevServerAssetMap;\n viteModule: ModuleNode;\n }\n ) {\n this.src = src;\n this.assetMap = options.assetMap;\n this.viteModule = options.viteModule;\n this.moduleId = this.viteModule.id!;\n this.assetUrl = this.viteModule.url;\n }\n\n async getCssDeps(): Promise<string[]> {\n const visited = new Set<string>();\n const deps = new Set<string>();\n this.collectCss(this, deps, visited);\n return Array.from(deps);\n }\n\n async getJsDeps(): Promise<string[]> {\n const visited = new Set<string>();\n const deps = new Set<string>();\n this.collectJs(this, deps, visited);\n return Array.from(deps);\n }\n\n getImportedModules() {\n return this.viteModule.importedModules;\n }\n\n private collectJs(\n asset: DevServerAsset | null,\n urls: Set<string>,\n visited: Set<string>\n ) {\n if (!asset) {\n return;\n }\n if (!asset.moduleId) {\n return;\n }\n if (visited.has(asset.moduleId)) {\n return;\n }\n visited.add(asset.moduleId);\n const parts = path.parse(asset.assetUrl);\n if (\n ['.js', '.jsx', '.ts', '.tsx'].includes(parts.ext) &&\n asset.moduleId.includes('/elements/')\n ) {\n urls.add(asset.assetUrl);\n }\n asset.getImportedModules().forEach((viteModule) => {\n if (viteModule.file) {\n const src = this.assetMap.filePathToSrc(viteModule.file);\n const importedAsset = new DevServerAsset(src, {\n assetMap: this.assetMap,\n viteModule: viteModule,\n });\n this.collectJs(importedAsset, urls, visited);\n }\n });\n }\n\n private collectCss(\n asset: DevServerAsset | null,\n urls: Set<string>,\n visited: Set<string>\n ) {\n if (!asset) {\n return;\n }\n if (!asset.assetUrl) {\n return;\n }\n if (visited.has(asset.assetUrl)) {\n return;\n }\n visited.add(asset.assetUrl);\n if (asset.src.endsWith('.scss')) {\n const parts = path.parse(asset.src);\n if (!parts.name.startsWith('_')) {\n urls.add(asset.assetUrl);\n }\n }\n asset.getImportedModules().forEach((viteModule) => {\n if (viteModule.file) {\n const src = this.assetMap.filePathToSrc(viteModule.file);\n const importedAsset = new DevServerAsset(src, {\n assetMap: this.assetMap,\n viteModule: viteModule,\n });\n this.collectCss(importedAsset, urls, visited);\n }\n });\n }\n}\n","import {createServer} from 'node:net';\n\n/**\n * Checks whether a port is open.\n */\nexport function isPortOpen(port: number): Promise<boolean> {\n return new Promise((resolve, reject) => {\n const server = createServer();\n server.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EADDRINUSE') {\n resolve(false);\n return;\n }\n reject(err);\n });\n server.on('close', () => {\n resolve(true);\n });\n server.listen(port, () => {\n server.close((err) => {\n if (err) {\n console.log(`error closing server: ${err}`);\n reject(err);\n }\n });\n });\n });\n}\n\n/**\n * Finds the first open port between two values.\n */\nexport async function findOpenPort(min: number, max: number): Promise<number> {\n let port = min;\n while (port <= max) {\n const isOpen = await isPortOpen(port);\n if (isOpen) {\n return port;\n }\n port += 1;\n }\n throw new Error(`no ports open between ${min} and ${max}`);\n}\n","export function randString(len: number): string {\n const result = [];\n const chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n for (let i = 0; i < len; i++) {\n const rand = Math.floor(Math.random() * chars.length);\n result.push(chars.charAt(rand));\n }\n return result.join('');\n}\n","import path from 'node:path';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport {default as express} from 'express';\nimport {dim} from 'kleur/colors';\nimport sirv from 'sirv';\n\nimport {RootConfig} from '../../core/config';\nimport {configureServerPlugins} from '../../core/plugin';\nimport {Request, Response, NextFunction, Server} from '../../core/types.js';\nimport {hooksMiddleware} from '../../middleware/hooks';\nimport {\n rootProjectMiddleware,\n trailingSlashMiddleware,\n} from '../../middleware/middleware';\nimport {sessionMiddleware} from '../../middleware/session';\nimport {ElementGraph} from '../../node/element-graph.js';\nimport {loadRootConfig} from '../../node/load-config';\nimport {\n BuildAssetManifest,\n BuildAssetMap,\n} from '../../render/asset-map/build-asset-map';\nimport {fileExists, loadJson} from '../../utils/fsutils';\nimport {randString} from '../../utils/rand';\n\ntype RenderModule = typeof import('../../render/render.js');\n\nexport interface PreviewOptions {\n host?: string;\n}\n\nexport async function preview(\n rootProjectDir?: string,\n options?: PreviewOptions\n) {\n // TODO(stevenle): figure out standard practice for NODE_ENV when using the\n // preview command.\n process.env.NODE_ENV = 'development';\n const rootDir = path.resolve(rootProjectDir || process.cwd());\n const server = await createPreviewServer({rootDir});\n const port = parseInt(process.env.PORT || '4007');\n const host = options?.host || 'localhost';\n console.log();\n console.log(`${dim('┃')} project: ${rootDir}`);\n console.log(`${dim('┃')} server: http://${host}:${port}`);\n console.log(`${dim('┃')} mode: preview`);\n console.log();\n server.listen(port, host);\n}\n\nexport async function createPreviewServer(options: {\n rootDir: string;\n}): Promise<Server> {\n const rootDir = options.rootDir;\n const rootConfig = await loadRootConfig(rootDir, {command: 'preview'});\n const distDir = path.join(rootDir, 'dist');\n\n const server: Server = express();\n server.disable('x-powered-by');\n server.use(compression());\n\n // Inject request context vars.\n server.use(rootProjectMiddleware({rootConfig}));\n server.use(await rootPreviewRendererMiddleware({rootConfig, distDir}));\n server.use(hooksMiddleware());\n\n // Session middleware for handling session cookies.\n const sessionCookieSecret =\n rootConfig.server?.sessionCookieSecret || randString(36);\n server.use(cookieParser(sessionCookieSecret));\n server.use(sessionMiddleware());\n\n const plugins = rootConfig.plugins || [];\n configureServerPlugins(\n server,\n async () => {\n // Add user-configured middlewares from `root.config.ts`.\n const userMiddlewares = rootConfig.server?.middlewares || [];\n userMiddlewares.forEach((middleware) => {\n server.use(middleware);\n });\n\n // Add static file middleware.\n const publicDir = path.join(distDir, 'html');\n server.use(sirv(publicDir, {dev: false}));\n\n // Add the root.js preview server middlewares.\n server.use(trailingSlashMiddleware({rootConfig}));\n server.use(rootPreviewServerMiddleware());\n\n // Add error handlers.\n server.use(rootPreviewServer404Middleware());\n server.use(rootPreviewServer500Middleware());\n },\n plugins,\n {type: 'preview', rootConfig}\n );\n return server;\n}\n\n/**\n * Injects a renderer into the request.\n */\nasync function rootPreviewRendererMiddleware(options: {\n rootConfig: RootConfig;\n distDir: string;\n}) {\n const {distDir, rootConfig} = options;\n const render: RenderModule = await import(\n path.join(distDir, 'server/render.js')\n );\n const manifestPath = path.join(distDir, 'client/root-manifest.json');\n if (!(await fileExists(manifestPath))) {\n throw new Error(\n `could not find ${manifestPath}. run \\`root build\\` before \\`root preview\\`.`\n );\n }\n const elementGraphJsonPath = path.join(\n distDir,\n 'client/root-element-graph.json'\n );\n if (!(await fileExists(elementGraphJsonPath))) {\n throw new Error(\n `could not find ${elementGraphJsonPath}. run \\`root build\\` before \\`root start\\`.`\n );\n }\n const rootManifest = await loadJson<BuildAssetManifest>(manifestPath);\n const assetMap = BuildAssetMap.fromRootManifest(rootConfig, rootManifest);\n const elementGraphJson = await loadJson<any>(elementGraphJsonPath);\n const elementGraph = ElementGraph.fromJson(elementGraphJson);\n const renderer = new render.Renderer(rootConfig, {assetMap, elementGraph});\n return async (req: Request, _: Response, next: NextFunction) => {\n req.renderer = renderer;\n next();\n };\n}\n\n/**\n * Preview server request handler.\n */\nfunction rootPreviewServerMiddleware() {\n return async (req: Request, res: Response, next: NextFunction) => {\n const renderer = req.renderer!;\n try {\n await renderer.handle(req, res, next);\n } catch (e) {\n try {\n console.error(`error rendering ${req.originalUrl}`);\n console.error(e.stack || e);\n const {html} = await renderer.renderError(e);\n res.status(500).set({'Content-Type': 'text/html'}).end(html);\n } catch (e2) {\n console.error('failed to render custom error');\n console.error(e2);\n next(e);\n }\n }\n };\n}\n\nfunction rootPreviewServer404Middleware() {\n return async (req: Request, res: Response) => {\n console.error(`❓ 404 ${req.originalUrl}`);\n if (req.renderer) {\n const url = req.path;\n const ext = path.extname(url);\n if (!ext) {\n const renderer = req.renderer;\n const data = await renderer.render404({currentPath: url});\n const html = data.html || '';\n res.status(404).set({'Content-Type': 'text/html'}).end(html);\n return;\n }\n }\n res.status(404).set({'Content-Type': 'text/plain'}).end('404');\n };\n}\n\nfunction rootPreviewServer500Middleware() {\n return async (err: any, req: Request, res: Response, next: NextFunction) => {\n console.error(`❗ 500 ${req.originalUrl}`);\n console.error(String(err.stack || err));\n if (req.renderer) {\n const url = req.path;\n const ext = path.extname(url);\n if (!ext) {\n const renderer = req.renderer;\n const data = await renderer.renderDevServer500(req, err);\n const html = data.html || '';\n res.status(500).set({'Content-Type': 'text/html'}).end(html);\n return;\n }\n }\n next(err);\n };\n}\n","import path from 'node:path';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport {default as express} from 'express';\nimport {dim} from 'kleur/colors';\nimport sirv from 'sirv';\n\nimport {RootConfig} from '../../core/config';\nimport {configureServerPlugins} from '../../core/plugin';\nimport {Request, Response, NextFunction, Server} from '../../core/types.js';\nimport {hooksMiddleware} from '../../middleware/hooks';\nimport {\n rootProjectMiddleware,\n trailingSlashMiddleware,\n} from '../../middleware/middleware';\nimport {sessionMiddleware} from '../../middleware/session';\nimport {ElementGraph} from '../../node/element-graph';\nimport {loadRootConfig} from '../../node/load-config';\nimport {\n BuildAssetManifest,\n BuildAssetMap,\n} from '../../render/asset-map/build-asset-map';\nimport {fileExists, loadJson} from '../../utils/fsutils';\nimport {randString} from '../../utils/rand';\n\ntype RenderModule = typeof import('../../render/render.js');\n\nexport interface StartOptions {\n host?: string;\n}\n\nexport async function start(rootProjectDir?: string, options?: StartOptions) {\n process.env.NODE_ENV = 'production';\n const rootDir = path.resolve(rootProjectDir || process.cwd());\n const server = await createProdServer({rootDir});\n const port = parseInt(process.env.PORT || '4007');\n const host = options?.host || 'localhost';\n console.log();\n console.log(`${dim('┃')} project: ${rootDir}`);\n console.log(`${dim('┃')} server: http://${host}:${port}`);\n console.log(`${dim('┃')} mode: production`);\n console.log();\n server.listen(port, host);\n}\n\nexport async function createProdServer(options: {\n rootDir: string;\n}): Promise<Server> {\n const rootDir = options.rootDir;\n const rootConfig = await loadRootConfig(rootDir, {command: 'start'});\n const distDir = path.join(rootDir, 'dist');\n\n const server: Server = express();\n server.disable('x-powered-by');\n server.use(compression());\n\n // Inject request context vars.\n server.use(rootProjectMiddleware({rootConfig}));\n server.use(await rootProdRendererMiddleware({rootConfig, distDir}));\n server.use(hooksMiddleware());\n\n // Session middleware for handling session cookies.\n const sessionCookieSecret =\n rootConfig.server?.sessionCookieSecret || randString(36);\n server.use(cookieParser(sessionCookieSecret));\n server.use(sessionMiddleware());\n\n const plugins = rootConfig.plugins || [];\n configureServerPlugins(\n server,\n async () => {\n // Add user-configured middlewares from `root.config.ts`.\n const userMiddlewares = rootConfig.server?.middlewares || [];\n userMiddlewares.forEach((middleware) => {\n server.use(middleware);\n });\n\n // Add static file middleware.\n const publicDir = path.join(distDir, 'html');\n server.use(sirv(publicDir, {dev: false}));\n\n // Add the root.js preview server middlewares.\n server.use(trailingSlashMiddleware({rootConfig}));\n server.use(rootProdServerMiddleware());\n\n // Add error handlers.\n server.use(rootProdServer404Middleware());\n server.use(rootProdServer500Middleware());\n },\n plugins,\n {type: 'prod', rootConfig}\n );\n return server;\n}\n\n/**\n * Injects a renderer into the request.\n */\nasync function rootProdRendererMiddleware(options: {\n rootConfig: RootConfig;\n distDir: string;\n}) {\n const {distDir, rootConfig} = options;\n const render: RenderModule = await import(\n path.join(distDir, 'server/render.js')\n );\n const manifestPath = path.join(distDir, 'client/root-manifest.json');\n if (!(await fileExists(manifestPath))) {\n throw new Error(\n `could not find ${manifestPath}. run \\`root build\\` before \\`root start\\`.`\n );\n }\n const elementGraphJsonPath = path.join(\n distDir,\n 'client/root-element-graph.json'\n );\n if (!(await fileExists(elementGraphJsonPath))) {\n throw new Error(\n `could not find ${elementGraphJsonPath}. run \\`root build\\` before \\`root start\\`.`\n );\n }\n const rootManifest = await loadJson<BuildAssetManifest>(manifestPath);\n const assetMap = BuildAssetMap.fromRootManifest(rootConfig, rootManifest);\n const elementGraphJson = await loadJson<any>(elementGraphJsonPath);\n const elementGraph = ElementGraph.fromJson(elementGraphJson);\n const renderer = new render.Renderer(rootConfig, {assetMap, elementGraph});\n return async (req: Request, _: Response, next: NextFunction) => {\n req.renderer = renderer;\n next();\n };\n}\n\n/**\n * Prod server request handler.\n */\nfunction rootProdServerMiddleware() {\n return async (req: Request, res: Response, next: NextFunction) => {\n const renderer = req.renderer!;\n try {\n await renderer.handle(req, res, next);\n } catch (e) {\n try {\n console.error(`error rendering ${req.originalUrl}`);\n console.error(e.stack || e);\n const {html} = await renderer.renderError(e);\n res.status(500).set({'Content-Type': 'text/html'}).end(html);\n } catch (e2) {\n console.error('failed to render custom error');\n console.error(e2);\n next(e);\n }\n }\n };\n}\n\nfunction rootProdServer404Middleware() {\n return async (req: Request, res: Response) => {\n console.error(`❓ 404 ${req.originalUrl}`);\n if (req.renderer) {\n const url = req.path;\n const ext = path.extname(url);\n if (!ext) {\n const renderer = req.renderer;\n const data = await renderer.render404({currentPath: url});\n const html = data.html || '';\n res.status(404).set({'Content-Type': 'text/html'}).end(html);\n return;\n }\n }\n res.status(404).set({'Content-Type': 'text/plain'}).end('404');\n };\n}\n\nfunction rootProdServer500Middleware() {\n return async (err: any, req: Request, res: Response, next: NextFunction) => {\n console.error(`❗ 500 ${req.originalUrl}`);\n console.error(String(err.stack || err));\n if (req.renderer) {\n const url = req.path;\n const ext = path.extname(url);\n if (!ext) {\n const renderer = req.renderer;\n const data = await renderer.renderError(err);\n const html = data.html || '';\n res.status(500).set({'Content-Type': 'text/html'}).end(html);\n return;\n }\n }\n next(err);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAAOA,WAAU;AACjB,SAAQ,qBAAoB;AAE5B,OAAO,aAAa;AACpB,SAAQ,KAAK,YAAW;AACxB,OAAOC,WAAU;AACjB,SAAQ,SAAS,iBAAqD;;;ACPtE,OAAO,QAAQ;AACf,OAAO,UAAU;AAEjB,OAAO,UAAU;AACjB,SAAQ,8BAA6B;AAiB9B,IAAM,eAAN,MAAM,cAAa;AAAA,EAWxB,YAAY,aAAqD;AAPjE;AAAA;AAAA;AAAA,SAAS,cAAsD,CAAC;AAKhE;AAAA;AAAA;AAAA,SAAQ,OAAiC,CAAC;AAGxC,SAAK,cAAc;AAAA,EACrB;AAAA,EAEA,SAAS;AACP,eAAW,WAAW,KAAK,aAAa;AACtC,WAAK,KAAK,OAAO,MAAM,KAAK,oBAAoB,OAAO;AAAA,IACzD;AACA,WAAO;AAAA,MACL,aAAa,KAAK;AAAA,MAClB,MAAM,KAAK;AAAA,IACb;AAAA,EACF;AAAA,EAEA,OAAO,SAAS,MAAqC;AACnD,UAAM,QAAQ,IAAI,cAAa,KAAK,WAAW;AAC/C,UAAM,OAAO,KAAK;AAClB,WAAO;AAAA,EACT;AAAA,EAEA,QAAQ,SAAiB,SAA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,EAAE,IAAI,EAAC,gBAAgB,YAAW,CAAC,EAAE,IAAI,IAAI;AAC3D;AAAA,MACF;AAAA,IACF;AACA,SAAK,GAAG;AAAA,EACV;AACF;","names":["path","glob","fs","path","asset","path","fs","path","glob","fileSize","path","fileURLToPath","dim","glob","path","searchForWorkspaceRoot","path","searchForWorkspaceRoot","__dirname","path","fileURLToPath","dim","_a","glob","path","cookieParser","express","dim","sirv","path","dim","express","cookieParser","_a","sirv","path","compression","cookieParser","express","dim","sirv","path","dim","express","compression","cookieParser","_a","sirv"]}
|
package/dist/cli.d.ts
CHANGED
package/dist/cli.js
CHANGED
package/dist/core.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { R as Route } from './types-
|
|
2
|
-
export { C as ConfigureServerHook, f as ConfigureServerOptions, j as GetStaticPaths, G as GetStaticProps, n as Handler, H as HandlerContext, q as HandlerRenderFn, p as HandlerRenderOptions, L as LocaleGroup, M as MultipartFile, N as NextFunction, P as Plugin, l as Request, k as RequestMiddleware, m as Response, b as RootConfig, c as RootI18nConfig, d as RootServerConfig, a as RootUserConfig, o as RouteModule, i as RouteParams, S as Server, g as configureServerPlugins, e as defineConfig, h as getVitePlugins } from './types-
|
|
1
|
+
import { R as Route } from './types-9209ea89.js';
|
|
2
|
+
export { C as ConfigureServerHook, f as ConfigureServerOptions, j as GetStaticPaths, G as GetStaticProps, n as Handler, H as HandlerContext, q as HandlerRenderFn, p as HandlerRenderOptions, L as LocaleGroup, M as MultipartFile, N as NextFunction, P as Plugin, l as Request, k as RequestMiddleware, m as Response, b as RootConfig, c as RootI18nConfig, d as RootServerConfig, a as RootUserConfig, o as RouteModule, i as RouteParams, S as Server, g as configureServerPlugins, e as defineConfig, h as getVitePlugins } from './types-9209ea89.js';
|
|
3
3
|
import * as preact$1 from 'preact';
|
|
4
4
|
import { FunctionalComponent, ComponentChildren } from 'preact';
|
|
5
5
|
import 'express';
|
|
@@ -7,7 +7,7 @@ import 'vite';
|
|
|
7
7
|
import 'html-minifier-terser';
|
|
8
8
|
import 'js-beautify';
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
type BodyProps = preact.JSX.HTMLAttributes<HTMLBodyElement> & {
|
|
11
11
|
children?: ComponentChildren;
|
|
12
12
|
};
|
|
13
13
|
/**
|
|
@@ -30,7 +30,7 @@ declare type BodyProps = preact.JSX.HTMLAttributes<HTMLBodyElement> & {
|
|
|
30
30
|
*/
|
|
31
31
|
declare const Body: FunctionalComponent<BodyProps>;
|
|
32
32
|
|
|
33
|
-
|
|
33
|
+
type HeadProps = preact.JSX.HTMLAttributes<HTMLHeadElement> & {
|
|
34
34
|
children?: ComponentChildren;
|
|
35
35
|
};
|
|
36
36
|
/**
|
|
@@ -56,7 +56,7 @@ interface HtmlContext {
|
|
|
56
56
|
scriptDeps: Array<preact$1.JSX.HTMLAttributes<HTMLScriptElement>>;
|
|
57
57
|
}
|
|
58
58
|
declare const HTML_CONTEXT: preact$1.Context<HtmlContext | null>;
|
|
59
|
-
|
|
59
|
+
type HtmlProps = preact$1.JSX.HTMLAttributes<HTMLHtmlElement> & {
|
|
60
60
|
children?: ComponentChildren;
|
|
61
61
|
};
|
|
62
62
|
/**
|
|
@@ -72,7 +72,7 @@ declare type HtmlProps = preact$1.JSX.HTMLAttributes<HTMLHtmlElement> & {
|
|
|
72
72
|
*/
|
|
73
73
|
declare const Html: FunctionalComponent<HtmlProps>;
|
|
74
74
|
|
|
75
|
-
|
|
75
|
+
type ScriptProps = preact.JSX.HTMLAttributes<HTMLScriptElement>;
|
|
76
76
|
/**
|
|
77
77
|
* The <Script> component is used for rendering any custom script modules. At
|
|
78
78
|
* the moment, the system only pre-renders and bundles files that are in the
|
package/dist/functions.js
CHANGED
package/dist/middleware.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { b as RootConfig, l as Request, m as Response, N as NextFunction } from './types-
|
|
2
|
-
export { r as SESSION_COOKIE, t as SaveSessionOptions, v as Session, s as SessionMiddlewareOptions, u as sessionMiddleware } from './types-
|
|
1
|
+
import { b as RootConfig, l as Request, m as Response, N as NextFunction } from './types-9209ea89.js';
|
|
2
|
+
export { r as SESSION_COOKIE, t as SaveSessionOptions, v as Session, s as SessionMiddlewareOptions, u as sessionMiddleware } from './types-9209ea89.js';
|
|
3
3
|
import 'express';
|
|
4
4
|
import 'preact';
|
|
5
5
|
import 'vite';
|
package/dist/node.d.ts
CHANGED
package/dist/render.d.ts
CHANGED
package/dist/render.js
CHANGED
|
@@ -298,21 +298,26 @@ var RouteTrie = class _RouteTrie {
|
|
|
298
298
|
return;
|
|
299
299
|
}
|
|
300
300
|
const [head, tail] = this.splitPath(path2);
|
|
301
|
+
if (head.startsWith("[[...") && head.endsWith("]]")) {
|
|
302
|
+
const paramName = head.slice(5, -2);
|
|
303
|
+
this.optCatchAllNodes = new CatchAllNode(paramName, route);
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
301
306
|
if (head.startsWith("[...") && head.endsWith("]")) {
|
|
302
307
|
const paramName = head.slice(4, -1);
|
|
303
|
-
this.
|
|
308
|
+
this.catchAllNodes = new CatchAllNode(paramName, route);
|
|
304
309
|
return;
|
|
305
310
|
}
|
|
306
311
|
let nextNode;
|
|
307
312
|
if (head.startsWith("[") && head.endsWith("]")) {
|
|
308
|
-
if (!this.
|
|
309
|
-
this.
|
|
313
|
+
if (!this.paramNodes) {
|
|
314
|
+
this.paramNodes = {};
|
|
310
315
|
}
|
|
311
316
|
const paramName = head.slice(1, -1);
|
|
312
|
-
if (!this.
|
|
313
|
-
this.
|
|
317
|
+
if (!this.paramNodes[paramName]) {
|
|
318
|
+
this.paramNodes[paramName] = new ParamNode(paramName);
|
|
314
319
|
}
|
|
315
|
-
nextNode = this.
|
|
320
|
+
nextNode = this.paramNodes[paramName].trie;
|
|
316
321
|
} else {
|
|
317
322
|
nextNode = this.children[head];
|
|
318
323
|
if (!nextNode) {
|
|
@@ -344,8 +349,8 @@ var RouteTrie = class _RouteTrie {
|
|
|
344
349
|
if (this.route) {
|
|
345
350
|
addPromise(cb("/", this.route));
|
|
346
351
|
}
|
|
347
|
-
if (this.
|
|
348
|
-
Object.values(this.
|
|
352
|
+
if (this.paramNodes) {
|
|
353
|
+
Object.values(this.paramNodes).forEach((paramChild) => {
|
|
349
354
|
const param = `[${paramChild.name}]`;
|
|
350
355
|
paramChild.trie.walk((childPath, route) => {
|
|
351
356
|
const paramUrlPath = `/${param}${childPath}`;
|
|
@@ -353,9 +358,13 @@ var RouteTrie = class _RouteTrie {
|
|
|
353
358
|
});
|
|
354
359
|
});
|
|
355
360
|
}
|
|
356
|
-
if (this.
|
|
357
|
-
const wildcardUrlPath = `/[...${this.
|
|
358
|
-
addPromise(cb(wildcardUrlPath, this.
|
|
361
|
+
if (this.catchAllNodes) {
|
|
362
|
+
const wildcardUrlPath = `/[...${this.catchAllNodes.name}]`;
|
|
363
|
+
addPromise(cb(wildcardUrlPath, this.catchAllNodes.route));
|
|
364
|
+
}
|
|
365
|
+
if (this.optCatchAllNodes) {
|
|
366
|
+
const wildcardUrlPath = `/[[...${this.optCatchAllNodes.name}]]`;
|
|
367
|
+
addPromise(cb(wildcardUrlPath, this.optCatchAllNodes.route));
|
|
359
368
|
}
|
|
360
369
|
for (const subpath of Object.keys(this.children)) {
|
|
361
370
|
const childTrie = this.children[subpath];
|
|
@@ -371,14 +380,24 @@ var RouteTrie = class _RouteTrie {
|
|
|
371
380
|
*/
|
|
372
381
|
clear() {
|
|
373
382
|
this.children = {};
|
|
374
|
-
this.
|
|
375
|
-
this.
|
|
383
|
+
this.paramNodes = void 0;
|
|
384
|
+
this.catchAllNodes = void 0;
|
|
385
|
+
this.optCatchAllNodes = void 0;
|
|
376
386
|
this.route = void 0;
|
|
377
387
|
}
|
|
378
388
|
getRoute(urlPath, params) {
|
|
379
389
|
urlPath = this.normalizePath(urlPath);
|
|
380
390
|
if (urlPath === "") {
|
|
381
|
-
|
|
391
|
+
if (this.route) {
|
|
392
|
+
return this.route;
|
|
393
|
+
}
|
|
394
|
+
if (this.optCatchAllNodes) {
|
|
395
|
+
if (urlPath) {
|
|
396
|
+
params[this.optCatchAllNodes.name] = urlPath;
|
|
397
|
+
}
|
|
398
|
+
return this.optCatchAllNodes.route;
|
|
399
|
+
}
|
|
400
|
+
return void 0;
|
|
382
401
|
}
|
|
383
402
|
const [head, tail] = this.splitPath(urlPath);
|
|
384
403
|
const child = this.children[head];
|
|
@@ -388,8 +407,8 @@ var RouteTrie = class _RouteTrie {
|
|
|
388
407
|
return route;
|
|
389
408
|
}
|
|
390
409
|
}
|
|
391
|
-
if (this.
|
|
392
|
-
for (const paramChild of Object.values(this.
|
|
410
|
+
if (this.paramNodes) {
|
|
411
|
+
for (const paramChild of Object.values(this.paramNodes)) {
|
|
393
412
|
const route = paramChild.trie.getRoute(tail, params);
|
|
394
413
|
if (route) {
|
|
395
414
|
params[paramChild.name] = head;
|
|
@@ -397,9 +416,13 @@ var RouteTrie = class _RouteTrie {
|
|
|
397
416
|
}
|
|
398
417
|
}
|
|
399
418
|
}
|
|
400
|
-
if (this.
|
|
401
|
-
params[this.
|
|
402
|
-
return this.
|
|
419
|
+
if (this.catchAllNodes) {
|
|
420
|
+
params[this.catchAllNodes.name] = urlPath;
|
|
421
|
+
return this.catchAllNodes.route;
|
|
422
|
+
}
|
|
423
|
+
if (this.optCatchAllNodes) {
|
|
424
|
+
params[this.optCatchAllNodes.name] = urlPath;
|
|
425
|
+
return this.optCatchAllNodes.route;
|
|
403
426
|
}
|
|
404
427
|
return void 0;
|
|
405
428
|
}
|
|
@@ -407,7 +430,7 @@ var RouteTrie = class _RouteTrie {
|
|
|
407
430
|
* Normalizes a path for inclusion into the route trie.
|
|
408
431
|
*/
|
|
409
432
|
normalizePath(path2) {
|
|
410
|
-
return path2.replace(/^\/+/g, "");
|
|
433
|
+
return path2.replace(/^\/+/g, "").replace(/\/+$/g, "");
|
|
411
434
|
}
|
|
412
435
|
/**
|
|
413
436
|
* Splits the parent directory from its children, e.g.:
|
|
@@ -422,13 +445,13 @@ var RouteTrie = class _RouteTrie {
|
|
|
422
445
|
return [path2.slice(0, i), path2.slice(i + 1)];
|
|
423
446
|
}
|
|
424
447
|
};
|
|
425
|
-
var
|
|
448
|
+
var ParamNode = class {
|
|
426
449
|
constructor(name) {
|
|
427
450
|
this.trie = new RouteTrie();
|
|
428
451
|
this.name = name;
|
|
429
452
|
}
|
|
430
453
|
};
|
|
431
|
-
var
|
|
454
|
+
var CatchAllNode = class {
|
|
432
455
|
constructor(name, route) {
|
|
433
456
|
this.name = name;
|
|
434
457
|
this.route = route;
|
|
@@ -510,18 +533,24 @@ async function getAllPathsForRoute(urlPathFormat, route) {
|
|
|
510
533
|
}
|
|
511
534
|
);
|
|
512
535
|
}
|
|
513
|
-
} else if (
|
|
536
|
+
} else if (routeModule.getStaticProps && !pathContainsPlaceholders(urlPathFormat)) {
|
|
537
|
+
urlPaths.push({ urlPath: normalizeUrlPath(urlPathFormat), params: {} });
|
|
538
|
+
} else if (!routeModule.handle && !pathContainsPlaceholders(urlPathFormat)) {
|
|
539
|
+
urlPaths.push({ urlPath: normalizeUrlPath(urlPathFormat), params: {} });
|
|
540
|
+
} else if (pathContainsPlaceholders(urlPathFormat) && !routeModule.handle && !routeModule.getStaticPaths) {
|
|
514
541
|
console.warn(
|
|
515
|
-
|
|
542
|
+
[
|
|
543
|
+
`warning: path contains placeholders: ${urlPathFormat}.`,
|
|
544
|
+
`define either ssg getStaticPaths() or ssr handle() for route: ${route.src}.`,
|
|
545
|
+
"more info: https://rootjs.dev/guide/routes"
|
|
546
|
+
].join("\n")
|
|
516
547
|
);
|
|
517
|
-
} else {
|
|
518
|
-
urlPaths.push({ urlPath: normalizeUrlPath(urlPathFormat), params: {} });
|
|
519
548
|
}
|
|
520
549
|
return urlPaths;
|
|
521
550
|
}
|
|
522
551
|
function replaceParams(urlPathFormat, params) {
|
|
523
552
|
const urlPath = urlPathFormat.replaceAll(
|
|
524
|
-
/\[(\.\.\.)?([\w\-_]*)\]/g,
|
|
553
|
+
/\[\[?(\.\.\.)?([\w\-_]*)\]?\]/g,
|
|
525
554
|
(match, _wildcard, key) => {
|
|
526
555
|
const val = params[key];
|
|
527
556
|
if (!val) {
|
|
@@ -676,7 +705,8 @@ var Renderer = class {
|
|
|
676
705
|
if (!scriptDep.src) {
|
|
677
706
|
return;
|
|
678
707
|
}
|
|
679
|
-
const
|
|
708
|
+
const assetId = String(scriptDep.src).slice(1);
|
|
709
|
+
const scriptAsset = await this.assetMap.get(assetId);
|
|
680
710
|
if (scriptAsset) {
|
|
681
711
|
jsDeps.add(scriptAsset.assetUrl);
|
|
682
712
|
const scriptJsDeps = await scriptAsset.getJsDeps();
|
package/dist/render.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/render/render.tsx","../src/core/pages/ErrorPage.tsx","../src/core/pages/DevErrorPage.tsx","../src/core/pages/DevNotFoundPage.tsx","../src/render/accept-language.ts","../src/render/i18n-fallbacks.ts","../src/render/router.ts","../src/render/route-trie.ts"],"sourcesContent":["import {ComponentChildren, ComponentType} from 'preact';\nimport renderToString from 'preact-render-to-string';\n\nimport {HtmlContext, HTML_CONTEXT} from '../core/components/Html';\nimport {RootConfig} from '../core/config';\nimport {getTranslations, I18N_CONTEXT} from '../core/hooks/useI18nContext';\nimport {RequestContext, REQUEST_CONTEXT} from '../core/hooks/useRequestContext';\nimport {DevErrorPage} from '../core/pages/DevErrorPage';\nimport {DevNotFoundPage} from '../core/pages/DevNotFoundPage';\nimport {ErrorPage} from '../core/pages/ErrorPage';\nimport {\n Request,\n Response,\n NextFunction,\n HandlerContext,\n RouteParams,\n Route,\n HandlerRenderFn,\n HandlerRenderOptions,\n} from '../core/types';\nimport type {ElementGraph} from '../node/element-graph';\nimport {parseTagNames} from '../utils/elements';\n\nimport {AssetMap} from './asset-map/asset-map';\nimport {htmlMinify} from './html-minify';\nimport {htmlPretty} from './html-pretty';\nimport {getFallbackLocales} from './i18n-fallbacks';\nimport {RouteTrie} from './route-trie';\nimport {getRoutes, getAllPathsForRoute, replaceParams} from './router';\n\ninterface RenderHtmlOptions {\n /** Attrs passed to the <html> tag, e.g. `{lang: 'en'}`. */\n htmlAttrs?: preact.JSX.HTMLAttributes<HTMLHtmlElement>;\n /** Attrs passed to the <head> tag. */\n headAttrs?: preact.JSX.HTMLAttributes<HTMLHeadElement>;\n /** Child components for the <head> tag. */\n headComponents?: ComponentChildren[];\n /** Attrs passed to the <body> tag. */\n bodyAttrs?: preact.JSX.HTMLAttributes<HTMLBodyElement>;\n}\n\nexport class Renderer {\n private rootConfig: RootConfig;\n private routes: RouteTrie<Route>;\n private assetMap: AssetMap;\n private elementGraph: ElementGraph;\n\n constructor(\n rootConfig: RootConfig,\n options: {assetMap: AssetMap; elementGraph: ElementGraph}\n ) {\n this.rootConfig = rootConfig;\n this.routes = getRoutes(this.rootConfig);\n this.assetMap = options.assetMap;\n this.elementGraph = options.elementGraph;\n }\n\n async handle(req: Request, res: Response, next: NextFunction) {\n // TODO(stevenle): handle baseUrl config.\n const url = req.path.toLowerCase();\n const [route, routeParams] = this.routes.get(url);\n if (!route) {\n next();\n return;\n }\n if (route.locale) {\n routeParams.$locale = route.locale;\n }\n\n const fallbackLocales = route.isDefaultLocale\n ? getFallbackLocales(req)\n : [route.locale];\n const getPreferredLocale = (availableLocales: string[]) => {\n const lowerLocales = availableLocales.map((l) => l.toLowerCase());\n for (const fallbackLocale of fallbackLocales) {\n if (lowerLocales.includes(fallbackLocale.toLowerCase())) {\n return fallbackLocale;\n }\n }\n return req.rootConfig?.i18n?.defaultLocale || 'en';\n };\n\n const render404 = async () => {\n // Calling next() will allow the dev server or prod server handle the 404\n // page as appropriate for the env.\n next();\n };\n\n const render: HandlerRenderFn = async (\n props: any,\n options?: HandlerRenderOptions\n ) => {\n if (!route.module.default) {\n console.error(`no default component exported in route: ${route.src}`);\n render404();\n return;\n }\n const currentPath = req.path;\n const locale = options?.locale || route.locale;\n const translations = options?.translations;\n const output = await this.renderComponent(route.module.default, props, {\n currentPath,\n route,\n routeParams,\n locale,\n translations,\n });\n let html = output.html;\n if (this.rootConfig.prettyHtml) {\n html = await htmlPretty(html, this.rootConfig.prettyHtmlOptions);\n } else if (this.rootConfig.minifyHtml !== false) {\n html = await htmlMinify(html, this.rootConfig.minifyHtmlOptions);\n }\n if (req.viteServer) {\n html = await req.viteServer.transformIndexHtml(currentPath, html);\n }\n // Override the status code for 404 and 500 routes, which are defined at\n // routes/404.tsx and routes/500.tsx respectively.\n let statusCode = 200;\n if (route.src === 'routes/404.tsx') {\n statusCode = 404;\n } else if (route.src === 'routes/500.tsx') {\n statusCode = 500;\n }\n req.hooks.trigger('preRender');\n res.status(statusCode).set({'Content-Type': 'text/html'}).end(html);\n };\n\n if (route.module.handle) {\n const handlerContext: HandlerContext = {\n route: route,\n params: routeParams,\n i18nFallbackLocales: fallbackLocales,\n getPreferredLocale: getPreferredLocale,\n render: render,\n render404: render404,\n };\n req.handlerContext = handlerContext;\n return route.module.handle(req, res, next);\n }\n\n let props = {};\n if (route.module.getStaticProps) {\n const propsData = await route.module.getStaticProps({\n rootConfig: this.rootConfig,\n params: routeParams,\n });\n if (propsData.notFound) {\n return render404();\n }\n if (propsData.props) {\n props = propsData.props;\n }\n }\n await render(props);\n }\n\n private async renderComponent(\n Component: ComponentType,\n props: any,\n options: {\n currentPath: string;\n route: Route;\n routeParams: RouteParams;\n locale: string;\n translations?: Record<string, string>;\n }\n ) {\n const {currentPath, route, routeParams} = options;\n const locale = options.locale;\n const translations = {\n ...getTranslations(locale),\n ...(options.translations || {}),\n };\n const ctx: RequestContext = {\n currentPath,\n route,\n props,\n routeParams,\n locale,\n translations,\n };\n const htmlContext: HtmlContext = {\n htmlAttrs: {},\n headAttrs: {},\n headComponents: [],\n bodyAttrs: {},\n scriptDeps: [],\n };\n const vdom = (\n <REQUEST_CONTEXT.Provider value={ctx}>\n <I18N_CONTEXT.Provider value={{locale, translations}}>\n <HTML_CONTEXT.Provider value={htmlContext}>\n <Component {...props} />\n </HTML_CONTEXT.Provider>\n </I18N_CONTEXT.Provider>\n </REQUEST_CONTEXT.Provider>\n );\n const mainHtml = renderToString(vdom);\n\n const jsDeps = new Set<string>();\n const cssDeps = new Set<string>();\n\n // Walk the route's dependency tree for CSS dependencies that are added via\n // `import 'foo.scss'` or `import 'foo.module.scss'`.\n const routeAsset = await this.assetMap.get(route.src);\n if (routeAsset) {\n const routeCssDeps = await routeAsset.getCssDeps();\n routeCssDeps.forEach((dep) => cssDeps.add(dep));\n }\n\n // Parse the HTML for custom elements that are found within the project\n // and automatically inject the script deps for them.\n await this.collectElementDeps(mainHtml, jsDeps, cssDeps);\n\n // Add user defined scripts added via the `<Script>` component.\n await Promise.all(\n htmlContext.scriptDeps.map(async (scriptDep) => {\n if (!scriptDep.src) {\n return;\n }\n const scriptAsset = await this.assetMap.get(scriptDep.src.slice(1));\n if (scriptAsset) {\n jsDeps.add(scriptAsset.assetUrl);\n const scriptJsDeps = await scriptAsset.getJsDeps();\n scriptJsDeps.forEach((dep) => jsDeps.add(dep));\n }\n })\n );\n\n const styleTags = Array.from(cssDeps).map((cssUrl) => {\n return <link rel=\"stylesheet\" href={cssUrl} />;\n });\n const scriptTags = Array.from(jsDeps).map((jsUrls) => {\n return <script type=\"module\" src={jsUrls} />;\n });\n\n const html = await this.renderHtml(mainHtml, {\n htmlAttrs: htmlContext.htmlAttrs,\n headAttrs: htmlContext.headAttrs,\n bodyAttrs: htmlContext.bodyAttrs,\n headComponents: [\n ...htmlContext.headComponents,\n ...styleTags,\n ...scriptTags,\n ],\n });\n return {html};\n }\n\n /** SSG renders a route. */\n async renderRoute(\n route: Route,\n options: {routeParams: Record<string, string>}\n ): Promise<{html?: string; notFound?: boolean}> {\n const routeParams = options.routeParams;\n if (route.locale) {\n routeParams.$locale = route.locale;\n }\n const Component = route.module.default;\n if (!Component) {\n throw new Error(\n 'unable to render route. the route should have a default export that renders a jsx component.'\n );\n }\n let props = {};\n let locale = route.locale;\n let translations = undefined;\n if (route.module.getStaticProps) {\n const propsData = await route.module.getStaticProps({\n rootConfig: this.rootConfig,\n params: routeParams,\n });\n if (propsData.notFound) {\n return {notFound: true};\n }\n if (propsData.props) {\n props = propsData.props;\n }\n if (propsData.locale) {\n locale = propsData.locale;\n }\n if (propsData.translations) {\n translations = propsData.translations;\n }\n }\n const routePath = route.isDefaultLocale\n ? route.routePath\n : route.localeRoutePath;\n const currentPath = replaceParams(routePath, {\n ...routeParams,\n locale: locale,\n });\n return this.renderComponent(Component, props, {\n currentPath,\n route,\n routeParams,\n locale,\n translations,\n });\n }\n\n async getSitemap(): Promise<\n Record<string, {route: Route; params: Record<string, string>}>\n > {\n const sitemap: Record<\n string,\n {route: Route; params: Record<string, string>}\n > = {};\n await this.routes.walk(async (urlPath: string, route: Route) => {\n const routePaths = await getAllPathsForRoute(urlPath, route);\n routePaths.forEach((routePath) => {\n sitemap[routePath.urlPath] = {\n route,\n params: routePath.params,\n };\n });\n });\n return sitemap;\n }\n\n private async renderHtml(html: string, options?: RenderHtmlOptions) {\n const htmlAttrs = options?.htmlAttrs || {};\n const headAttrs = options?.headAttrs || {};\n const bodyAttrs = options?.bodyAttrs || {};\n const page = (\n <html {...htmlAttrs}>\n <head {...headAttrs}>\n <meta charSet=\"utf-8\" />\n {options?.headComponents}\n </head>\n <body {...bodyAttrs} dangerouslySetInnerHTML={{__html: html}} />\n </html>\n );\n return `<!doctype html>\\n${renderToString(page)}\\n`;\n }\n\n async render404(options?: {currentPath?: string}) {\n const currentPath = options?.currentPath || '/404';\n const [route, routeParams] = this.routes.get('/404');\n if (route && route.src === 'routes/404.tsx' && route.module.default) {\n const Component = route.module.default;\n return this.renderComponent(\n Component,\n {},\n {currentPath, route, routeParams, locale: 'en'}\n );\n }\n\n const mainHtml = renderToString(\n <ErrorPage\n code={404}\n title=\"Not found\"\n message=\"Double-check the URL entered and try again.\"\n align=\"center\"\n />\n );\n const html = await this.renderHtml(mainHtml, {\n headComponents: [\n <title>404 Not Found</title>,\n <meta\n name=\"viewport\"\n content=\"width=device-width, initial-scale=1.0\"\n />,\n ],\n });\n return {html};\n }\n\n async renderError(err: any, options?: {currentPath?: string}) {\n const currentPath = options?.currentPath || '/500';\n const [route, routeParams] = this.routes.get('/500');\n if (route && route.src === 'routes/500.tsx' && route.module.default) {\n const Component = route.module.default;\n return this.renderComponent(\n Component,\n {error: err},\n {currentPath, route, routeParams, locale: 'en'}\n );\n }\n\n const mainHtml = renderToString(\n <ErrorPage\n code={500}\n title=\"Something went wrong\"\n message=\"An unknown error occurred.\"\n align=\"center\"\n />\n );\n const html = await this.renderHtml(mainHtml, {\n headComponents: [\n <title>500 Error</title>,\n <meta\n name=\"viewport\"\n content=\"width=device-width, initial-scale=1.0\"\n />,\n ],\n });\n return {html};\n }\n\n async renderDevServer404(req: Request) {\n const sitemap = await this.getSitemap();\n const mainHtml = renderToString(\n <DevNotFoundPage req={req} sitemap={sitemap} />\n );\n const html = await this.renderHtml(mainHtml, {\n headComponents: [<title>404 Not found | Root.js</title>],\n });\n return {html};\n }\n\n async renderDevServer500(req: Request, error: unknown) {\n const [route, routeParams] = this.routes.get(req.path);\n const mainHtml = renderToString(\n <DevErrorPage\n req={req}\n route={route}\n routeParams={routeParams}\n error={error}\n />\n );\n const html = await this.renderHtml(mainHtml, {\n headComponents: [<title>500 Error | Root.js</title>],\n });\n return {html};\n }\n\n /**\n * Parses rendered HTML for custom element tags used on the page and\n * automatically adds the JS/CSS deps to the page.\n */\n private async collectElementDeps(\n html: string,\n jsDeps: Set<string>,\n cssDeps: Set<string>\n ): Promise<{jsDeps: Set<string>; cssDeps: Set<string>}> {\n const elementsMap = this.elementGraph.sourceFiles;\n const assetMap = this.assetMap;\n\n const tagNames = new Set<string>();\n for (const tagName of parseTagNames(html)) {\n if (tagName && tagName in elementsMap) {\n tagNames.add(tagName);\n for (const depTagName of this.elementGraph.getDeps(tagName)) {\n tagNames.add(depTagName);\n }\n }\n }\n\n await Promise.all(\n Array.from(tagNames).map(async (tagName: string) => {\n const elementModule = elementsMap[tagName];\n const asset = await assetMap.get(elementModule.relPath);\n if (!asset) {\n return;\n }\n const assetJsDeps = await asset.getJsDeps();\n assetJsDeps.forEach((dep) => jsDeps.add(dep));\n const assetCssDeps = await asset.getCssDeps();\n assetCssDeps.forEach((dep) => cssDeps.add(dep));\n })\n );\n\n return {jsDeps, cssDeps};\n }\n}\n","import {ComponentChildren} from 'preact';\n\nconst STYLES = `\n@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap');\n\n:root {\n --font-family-text: \"Inter\", sans-serif;\n}\n\nbody {\n font-family: var(--font-family-text);\n background: #F5F5F5;\n padding: 40px 16px;\n}\n\n.root {\n max-width: 1200px;\n margin: 0 auto;\n}\n\n.root.align-center {\n text-align: center;\n}\n\nh1.title {\n margin-top: 0;\n margin-bottom: 24px;\n}\n\np.message {\n margin-top: 0;\n margin-bottom: 0;\n}\n\n.box {\n font-size: 16px;\n line-height: 1.5;\n padding: 16px;\n border-radius: 12px;\n background: #ffffff;\n}\n\npre.box {\n white-space: pre-wrap;\n}\n\n@media (min-width: 500px) {\n body {\n padding: 40px;\n }\n\n .box {\n padding: 24px;\n }\n}\n\n@media (min-width: 1024px) {\n body {\n padding: 100px;\n }\n}\n`;\n\nexport interface ErrorPageProps {\n code: number;\n title?: string;\n message?: string;\n children?: ComponentChildren;\n align?: 'center';\n}\n\nexport function ErrorPage(props: ErrorPageProps) {\n const {code, message} = props;\n const title = props.title || code;\n return (\n <>\n <style dangerouslySetInnerHTML={{__html: STYLES}}></style>\n <div className={`root align-${props.align || 'left'}`}>\n <h1 className=\"title\">{title}</h1>\n {message && <p className=\"message\">{message}</p>}\n {props.children}\n </div>\n </>\n );\n}\n","import {Request, Route, RouteParams} from '../types';\n\nimport {ErrorPage} from './ErrorPage';\n\ninterface DevErrorPageProps {\n req: Request;\n route?: Route;\n routeParams?: RouteParams;\n error: any;\n}\n\nexport function DevErrorPage(props: DevErrorPageProps) {\n const req = props.req;\n const err = props.error;\n const route = props.route;\n const routeParams = props.routeParams;\n\n let errMsg = String(err);\n if (err && err.stack) {\n // Obfuscate some user info from the stack trace so that when people send\n // error reports and screenshots, less identifiable information is sent.\n errMsg = err.stack\n .replace(/\\(.*node_modules/g, '(node_modules')\n .replace(/at \\/.*node_modules/g, 'at node_modules');\n if (req.rootConfig?.rootDir) {\n errMsg = errMsg.replaceAll(req.rootConfig.rootDir, '<root>');\n }\n if (process.env.HOME) {\n errMsg = errMsg.replaceAll(process.env.HOME, '$HOME');\n }\n }\n return (\n <ErrorPage code={500} title=\"Something went wrong\">\n {errMsg && (\n <>\n <h2>Error</h2>\n <pre className=\"box\">\n <code>{errMsg}</code>\n </pre>\n </>\n )}\n <h2>Debug Info</h2>\n <pre className=\"box\">\n <code>{`url: ${req.originalUrl}\nroute: ${route?.src || 'null'}\nrouteParams: ${(routeParams && JSON.stringify(routeParams)) || 'null'}`}</code>\n </pre>\n </ErrorPage>\n );\n}\n","import {Request, Route} from '../types';\n\nimport {ErrorPage} from './ErrorPage';\n\ninterface DevNotFoundPageProps {\n req: Request;\n sitemap: Record<string, {route: Route; params: Record<string, string>}>;\n}\n\ninterface RoutesListMap {\n [src: string]: Array<RouteURLPath>;\n}\n\ninterface RouteURLPath {\n route: Route;\n urlPath: string;\n}\n\nexport function DevNotFoundPage(props: DevNotFoundPageProps) {\n const req = props.req;\n const routesListMap: RoutesListMap = {};\n let srcMaxLength = 0;\n Object.keys(props.sitemap).forEach((urlPath) => {\n const route = props.sitemap[urlPath].route;\n routesListMap[route.src] ??= [];\n routesListMap[route.src].push({route, urlPath});\n if (route.src.length > srcMaxLength) {\n srcMaxLength = route.src.length;\n }\n });\n const routeSrcs = Object.keys(routesListMap).sort(sortRouteFiles);\n const lines: string[] = [];\n routeSrcs.forEach((routeSrc) => {\n const routeUrls = routesListMap[routeSrc].sort(sortRouteURLs);\n routeUrls.forEach((routeUrl, i) => {\n const urlPath = routeUrl.urlPath;\n if (i === 0) {\n lines.push(`${routeSrc.padEnd(srcMaxLength, ' ')} => ${urlPath}`);\n } else {\n lines.push(`${''.padEnd(srcMaxLength, ' ')} => ${urlPath}`);\n }\n });\n });\n const routesListString = lines.join('\\n');\n // const routesListString = routesList\n // .map((route) => {\n // return `${route.urlPath.padEnd(srcMaxLength, ' ')} => ${route.src}`;\n // })\n // .join('\\n');\n return (\n <ErrorPage code={404} title=\"Not found\">\n <h2>Routes</h2>\n {Object.keys(routesListMap).length > 0 ? (\n <pre className=\"box\">\n <code>{routesListString}</code>\n </pre>\n ) : (\n <div className=\"box\">\n Add your first route at <code>/routes/index.tsx</code>\n </div>\n )}\n\n <h2>Debug Info</h2>\n <pre className=\"box\">\n <code>{`url: ${req.originalUrl}`}</code>\n </pre>\n </ErrorPage>\n );\n}\n\nfunction sortRouteFiles(a: string, b: string): number {\n if (a === 'routes/index.tsx') {\n return -1;\n }\n if (b === 'routes/index.tsx') {\n return 1;\n }\n return a.localeCompare(b);\n}\n\nfunction sortRouteURLs(a: RouteURLPath, b: RouteURLPath): number {\n if (a.route.isDefaultLocale && !b.route.isDefaultLocale) {\n return -1;\n }\n if (!a.route.isDefaultLocale && b.route.isDefaultLocale) {\n return 1;\n }\n return a.urlPath.localeCompare(b.urlPath);\n}\n","export const ACCEPT_LANG_RE =\n /((([a-zA-Z]+(-[a-zA-Z0-9]+){0,2})|\\*)(;q=[0-1](\\.[0-9]+)?)?)*/g;\n\nexport interface AcceptLanguage {\n code: string;\n script?: string;\n region?: string;\n quality: number;\n}\n\nexport function parseAcceptLanguage(value: string): AcceptLanguage[] {\n const matches = String(value).match(ACCEPT_LANG_RE);\n if (!matches) {\n return [];\n }\n const results: AcceptLanguage[] = [];\n matches.forEach((m) => {\n if (!m) {\n return;\n }\n\n const parts = m.split(';');\n const ietf = parts[0].split('-');\n const hasScript = ietf.length === 3;\n\n results.push({\n code: ietf[0],\n script: hasScript ? ietf[1] : undefined,\n region: hasScript ? ietf[2] : ietf[1],\n quality: parts[1] ? parseFloat(parts[1].split('=')[1]) : 1.0,\n });\n });\n results.sort((a, b) => b.quality - a.quality);\n return results;\n}\n","/**\n * Utility functions for handling requests that mimic the Firebase Hosting i18n\n * fallback logic.\n * https://firebase.google.com/docs/hosting/i18n-rewrites\n */\n\nimport {Request} from '../core/types';\nimport {parseAcceptLanguage} from './accept-language';\n\nexport const UNKNOWN_COUNTRY = 'zz';\n\nexport function getFallbackLocales(req: Request): string[] {\n const hl = getFirstQueryParam(req, 'hl');\n const countryCode = getCountry(req);\n\n // Web crawlers should only use the default locale.\n if (isWebCrawler(req)) {\n const defaultLocale = req.rootConfig?.i18n?.defaultLocale || 'en';\n if (hl && hl !== defaultLocale) {\n return [hl, defaultLocale];\n }\n return [defaultLocale];\n }\n\n const locales = new Set<string>();\n\n // Add locales from ?hl= query parameter.\n if (hl) {\n const langCode = hl;\n locales.add(`${langCode}_${countryCode}`);\n locales.add(`${langCode}_ALL`);\n locales.add(langCode);\n }\n\n const langs = getFallbackLanguages(req);\n\n // Add `{lang}_{country}` locales.\n langs.forEach((langCode) => {\n locales.add(`${langCode}_${countryCode}`);\n });\n\n // Add ALL_{country} locale.\n locales.add(`ALL_${countryCode}`);\n\n // Add `{lang}_ALL` and `{lang}` locales.\n langs.forEach((langCode) => {\n locales.add(`${langCode}_ALL`);\n locales.add(langCode);\n });\n\n return Array.from(locales) as string[];\n}\n\nexport function getCountry(req: Request) {\n const normalize = (countryCode: string) => String(countryCode).toLowerCase();\n // Check the ?gl= query param.\n const gl = getFirstQueryParam(req, 'gl');\n if (gl) {\n return normalize(gl);\n }\n const gaeCountry =\n req.get('x-country-code') || req.get('x-appengine-country');\n if (gaeCountry) {\n return normalize(gaeCountry);\n }\n return UNKNOWN_COUNTRY;\n}\n\nfunction getFallbackLanguages(req: Request): string[] {\n const langs = new Set<string>();\n // Add languages from the Accept-Language header.\n const acceptLangHeader = req.get('accept-language') || '';\n if (acceptLangHeader) {\n parseAcceptLanguage(acceptLangHeader).forEach((lang) => {\n // For a lang like `en-US`, add both `en-US` and `en`.\n if (lang.region) {\n langs.add(`${lang.code}-${lang.region}`);\n }\n langs.add(lang.code);\n });\n }\n // Fall back to \"en\" as a last resort.\n langs.add('en');\n return Array.from(langs);\n}\n\n/**\n * Returns the first query param value in a given request.\n *\n * For example, for a URL like `/?foo=bar&foo=baz`, calling\n * `getFirstQueryParam(req, 'foo')` would return `\"bar\"`.\n */\nfunction getFirstQueryParam(req: Request, key: string): string | null {\n const val = req.query[key];\n if (val === null || val === undefined) {\n return null;\n }\n if (Array.isArray(val)) {\n if (val.length === 0) {\n return null;\n }\n return String(val[0]);\n }\n return String(val);\n}\n\nfunction isWebCrawler(req: Request): boolean {\n const userAgentHeader = req.get('User-Agent');\n if (!userAgentHeader) {\n return false;\n }\n const userAgent = userAgentHeader.toLowerCase();\n return (\n userAgent.includes('googlebot') ||\n userAgent.includes('bingbot') ||\n userAgent.includes('twitterbot')\n );\n}\n","import path from 'node:path';\n\nimport {RootConfig} from '../core/config';\nimport {Route, RouteModule} from '../core/types';\n\nimport {RouteTrie} from './route-trie';\n\nexport function getRoutes(config: RootConfig) {\n const locales = config.i18n?.locales || [];\n const i18nUrlFormat = config.i18n?.urlFormat || '/{locale}/{path}';\n const defaultLocale = config.i18n?.defaultLocale || 'en';\n\n const routes = import.meta.glob(\n ['/routes/*.ts', '/routes/**/*.ts', '/routes/*.tsx', '/routes/**/*.tsx'],\n {\n eager: true,\n }\n );\n const trie = new RouteTrie<Route>();\n Object.keys(routes).forEach((modulePath) => {\n const src = modulePath.slice(1);\n let routePath = modulePath.replace(/^\\/routes/, '');\n const parts = path.parse(routePath);\n if (parts.name.startsWith('_')) {\n return;\n }\n if (parts.name === 'index') {\n routePath = parts.dir;\n } else {\n routePath = path.join(parts.dir, parts.name);\n }\n\n const localeRoutePath = i18nUrlFormat\n .replace('{locale}', '[locale]')\n .replace('{path}', routePath.replace(/^\\/*/, ''));\n\n trie.add(routePath, {\n src,\n module: routes[modulePath] as RouteModule,\n locale: defaultLocale,\n isDefaultLocale: true,\n routePath: normalizeUrlPath(routePath),\n localeRoutePath: normalizeUrlPath(localeRoutePath),\n });\n\n // At the moment, all routes are assumed to use the site-wide i18n config.\n // TODO(stevenle): provide routes with a way to override the default\n // i18n serving behavior.\n locales.forEach((locale) => {\n const localePath = localeRoutePath.replace('[locale]', locale);\n if (localePath !== routePath) {\n trie.add(localePath, {\n src,\n module: routes[modulePath] as RouteModule,\n locale: locale,\n isDefaultLocale: false,\n routePath,\n localeRoutePath,\n });\n }\n });\n });\n return trie;\n}\n\nexport async function getAllPathsForRoute(\n urlPathFormat: string,\n route: Route\n): Promise<Array<{urlPath: string; params: Record<string, string>}>> {\n const routeModule = route.module;\n if (!routeModule.default) {\n return [];\n }\n\n const urlPaths: Array<{urlPath: string; params: Record<string, string>}> = [];\n if (routeModule.getStaticPaths) {\n const staticPaths = await routeModule.getStaticPaths();\n if (staticPaths.paths) {\n staticPaths.paths.forEach(\n (pathParams: {params: Record<string, string>}) => {\n const urlPath = replaceParams(urlPathFormat, pathParams.params || {});\n if (pathContainsPlaceholders(urlPath)) {\n console.warn(\n `path contains placeholders: ${urlPathFormat}, double check getStaticPaths() and ensure all params are returned. more info: https://rootjs.dev/guide/routes#getStaticPaths`\n );\n } else {\n urlPaths.push({\n urlPath: normalizeUrlPath(urlPath),\n params: pathParams.params || {},\n });\n }\n }\n );\n }\n } else if (pathContainsPlaceholders(urlPathFormat) && !routeModule.handle) {\n console.warn(\n `path contains placeholders: ${urlPathFormat}, did you forget to define getStaticPaths()? more info: https://rootjs.dev/guide/routes#getStaticPaths`\n );\n } else {\n urlPaths.push({urlPath: normalizeUrlPath(urlPathFormat), params: {}});\n }\n return urlPaths;\n}\n\nexport function replaceParams(\n urlPathFormat: string,\n params: Record<string, string>\n) {\n const urlPath = urlPathFormat.replaceAll(\n /\\[(\\.\\.\\.)?([\\w\\-_]*)\\]/g,\n (match: string, _wildcard: string, key: string) => {\n const val = params[key];\n if (!val) {\n throw new Error(`unreplaced param ${match} in url: ${urlPathFormat}`);\n }\n return val;\n }\n );\n return urlPath;\n}\n\nexport function normalizeUrlPath(urlPath: string) {\n if (urlPath !== '/' && urlPath.endsWith('/')) {\n urlPath = urlPath.replace(/\\/*$/g, '');\n }\n return urlPath;\n}\n\nfunction pathContainsPlaceholders(urlPath: string) {\n const segments = urlPath.split('/');\n return segments.some((segment) => {\n return segment.startsWith('[') && segment.endsWith(']');\n });\n}\n","/**\n * A trie data structure that stores routes. The trie supports `:param` and\n * `*wildcard` values.\n */\nexport class RouteTrie<T> {\n private children: Record<string, RouteTrie<T>> = {};\n private paramChildren?: {[param: string]: ParamChild<T>};\n private wildcardChild?: WildcardChild<T>;\n private route?: T;\n\n /**\n * Adds a route to the trie.\n */\n add(path: string, route: T) {\n path = this.normalizePath(path);\n\n // If the end was reached, save the value to the node.\n if (path === '') {\n this.route = route;\n return;\n }\n\n const [head, tail] = this.splitPath(path);\n if (head.startsWith('[...') && head.endsWith(']')) {\n const paramName = head.slice(4, -1);\n this.wildcardChild = new WildcardChild(paramName, route);\n return;\n }\n\n let nextNode: RouteTrie<T>;\n if (head.startsWith('[') && head.endsWith(']')) {\n if (!this.paramChildren) {\n this.paramChildren = {};\n }\n const paramName = head.slice(1, -1);\n if (!this.paramChildren[paramName]) {\n this.paramChildren[paramName] = new ParamChild(paramName);\n }\n nextNode = this.paramChildren[paramName].trie;\n } else {\n nextNode = this.children[head];\n if (!nextNode) {\n nextNode = new RouteTrie();\n this.children[head] = nextNode;\n }\n }\n nextNode.add(tail, route);\n }\n\n /**\n * Returns a route mapped to the given path and any parameter values from the\n * URL.\n */\n get(path: string): [T | undefined, Record<string, string>] {\n const params = {};\n const route = this.getRoute(path, params);\n return [route, params];\n }\n\n /**\n * Walks the route trie and calls a callback function for each route.\n */\n walk(cb: (urlPath: string, route: T) => Promise<void> | void): Promise<void> {\n const promises: Array<Promise<void>> = [];\n const addPromise = (promise: Promise<void> | void) => {\n if (promise) {\n promises.push(promise);\n }\n };\n if (this.route) {\n addPromise(cb('/', this.route));\n }\n if (this.paramChildren) {\n Object.values(this.paramChildren).forEach((paramChild) => {\n const param = `[${paramChild.name}]`;\n paramChild.trie.walk((childPath: string, route: T) => {\n const paramUrlPath = `/${param}${childPath}`;\n addPromise(cb(paramUrlPath, route));\n });\n });\n }\n if (this.wildcardChild) {\n const wildcardUrlPath = `/[...${this.wildcardChild.name}]`;\n addPromise(cb(wildcardUrlPath, this.wildcardChild.route));\n }\n for (const subpath of Object.keys(this.children)) {\n const childTrie = this.children[subpath];\n childTrie.walk((childPath: string, childRoute: T) => {\n addPromise(cb(`/${subpath}${childPath}`, childRoute));\n });\n }\n return Promise.all(promises).then(() => {});\n }\n\n /**\n * Removes all routes from the trie.\n */\n clear() {\n this.children = {};\n this.paramChildren = undefined;\n this.wildcardChild = undefined;\n this.route = undefined;\n }\n\n private getRoute(\n urlPath: string,\n params: Record<string, string>\n ): T | undefined {\n urlPath = this.normalizePath(urlPath);\n if (urlPath === '') {\n return this.route;\n }\n\n const [head, tail] = this.splitPath(urlPath);\n\n const child = this.children[head];\n if (child) {\n const route = child.getRoute(tail, params);\n if (route) {\n return route;\n }\n }\n\n if (this.paramChildren) {\n for (const paramChild of Object.values(this.paramChildren)) {\n const route = paramChild.trie.getRoute(tail, params);\n if (route) {\n params[paramChild.name] = head;\n return route;\n }\n }\n }\n\n if (this.wildcardChild) {\n params[this.wildcardChild.name] = urlPath;\n return this.wildcardChild.route;\n }\n\n return undefined;\n }\n\n /**\n * Normalizes a path for inclusion into the route trie.\n */\n private normalizePath(path: string) {\n // Remove leading slashes.\n return path.replace(/^\\/+/g, '');\n }\n\n /**\n * Splits the parent directory from its children, e.g.:\n *\n * splitPath(\"foo/bar/baz\") -> [\"foo\", \"bar/baz\"]\n */\n private splitPath(path: string): [string, string] {\n const i = path.indexOf('/');\n if (i === -1) {\n return [path, ''];\n }\n return [path.slice(0, i), path.slice(i + 1)];\n }\n}\n\n/**\n * A node in the RouteTrie for a :param child.\n */\nclass ParamChild<T> {\n readonly name: string;\n readonly trie: RouteTrie<T> = new RouteTrie();\n\n constructor(name: string) {\n this.name = name;\n }\n}\n\n/**\n * A node in the RouteTrie for a *wildcard child.\n */\nclass WildcardChild<T> {\n readonly name: string;\n readonly route: T;\n\n constructor(name: string, route: T) {\n this.name = name;\n this.route = route;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AACA,OAAO,oBAAoB;;;AC0EvB,mBACE,KACA,YAFF;AAzEJ,IAAM,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqER,SAAS,UAAU,OAAuB;AAC/C,QAAM,EAAC,MAAM,QAAO,IAAI;AACxB,QAAM,QAAQ,MAAM,SAAS;AAC7B,SACE,iCACE;AAAA,wBAAC,WAAM,yBAAyB,EAAC,QAAQ,OAAM,GAAG;AAAA,IAClD,qBAAC,SAAI,WAAW,cAAc,MAAM,SAAS,MAAM,IACjD;AAAA,0BAAC,QAAG,WAAU,SAAS,iBAAM;AAAA,MAC5B,WAAW,oBAAC,OAAE,WAAU,WAAW,mBAAQ;AAAA,MAC3C,MAAM;AAAA,OACT;AAAA,KACF;AAEJ;;;AClDQ,qBAAAA,WACE,OAAAC,MADF,QAAAC,aAAA;AAvBD,SAAS,aAAa,OAA0B;AAXvD;AAYE,QAAM,MAAM,MAAM;AAClB,QAAM,MAAM,MAAM;AAClB,QAAM,QAAQ,MAAM;AACpB,QAAM,cAAc,MAAM;AAE1B,MAAI,SAAS,OAAO,GAAG;AAC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aAAa;AACtC,UAAM,WAAW,KAAK;AAEtB,UAAM,WAAW,oBAAI,IAAY;AACjC,eAAW,WAAW,cAAc,IAAI,GAAG;AACzC,UAAI,WAAW,WAAW,aAAa;AACrC,iBAAS,IAAI,OAAO;AACpB,mBAAW,cAAc,KAAK,aAAa,QAAQ,OAAO,GAAG;AAC3D,mBAAS,IAAI,UAAU;AAAA,QACzB;AAAA,MACF;AAAA,IACF;AAEA,UAAM,QAAQ;AAAA,MACZ,MAAM,KAAK,QAAQ,EAAE,IAAI,OAAO,YAAoB;AAClD,cAAM,gBAAgB,YAAY,OAAO;AACzC,cAAM,QAAQ,MAAM,SAAS,IAAI,cAAc,OAAO;AACtD,YAAI,CAAC,OAAO;AACV;AAAA,QACF;AACA,cAAM,cAAc,MAAM,MAAM,UAAU;AAC1C,oBAAY,QAAQ,CAAC,QAAQ,OAAO,IAAI,GAAG,CAAC;AAC5C,cAAM,eAAe,MAAM,MAAM,WAAW;AAC5C,qBAAa,QAAQ,CAAC,QAAQ,QAAQ,IAAI,GAAG,CAAC;AAAA,MAChD,CAAC;AAAA,IACH;AAEA,WAAO,EAAC,QAAQ,QAAO;AAAA,EACzB;AACF;","names":["Fragment","jsx","jsxs","jsx","jsxs","path","jsx","jsxs","props"]}
|
|
1
|
+
{"version":3,"sources":["../src/render/render.tsx","../src/core/pages/ErrorPage.tsx","../src/core/pages/DevErrorPage.tsx","../src/core/pages/DevNotFoundPage.tsx","../src/render/accept-language.ts","../src/render/i18n-fallbacks.ts","../src/render/router.ts","../src/render/route-trie.ts"],"sourcesContent":["import {ComponentChildren, ComponentType} from 'preact';\nimport renderToString from 'preact-render-to-string';\n\nimport {HtmlContext, HTML_CONTEXT} from '../core/components/Html';\nimport {RootConfig} from '../core/config';\nimport {getTranslations, I18N_CONTEXT} from '../core/hooks/useI18nContext';\nimport {RequestContext, REQUEST_CONTEXT} from '../core/hooks/useRequestContext';\nimport {DevErrorPage} from '../core/pages/DevErrorPage';\nimport {DevNotFoundPage} from '../core/pages/DevNotFoundPage';\nimport {ErrorPage} from '../core/pages/ErrorPage';\nimport {\n Request,\n Response,\n NextFunction,\n HandlerContext,\n RouteParams,\n Route,\n HandlerRenderFn,\n HandlerRenderOptions,\n} from '../core/types';\nimport type {ElementGraph} from '../node/element-graph';\nimport {parseTagNames} from '../utils/elements';\n\nimport {AssetMap} from './asset-map/asset-map';\nimport {htmlMinify} from './html-minify';\nimport {htmlPretty} from './html-pretty';\nimport {getFallbackLocales} from './i18n-fallbacks';\nimport {RouteTrie} from './route-trie';\nimport {getRoutes, getAllPathsForRoute, replaceParams} from './router';\n\ninterface RenderHtmlOptions {\n /** Attrs passed to the <html> tag, e.g. `{lang: 'en'}`. */\n htmlAttrs?: preact.JSX.HTMLAttributes<HTMLHtmlElement>;\n /** Attrs passed to the <head> tag. */\n headAttrs?: preact.JSX.HTMLAttributes<HTMLHeadElement>;\n /** Child components for the <head> tag. */\n headComponents?: ComponentChildren[];\n /** Attrs passed to the <body> tag. */\n bodyAttrs?: preact.JSX.HTMLAttributes<HTMLBodyElement>;\n}\n\nexport class Renderer {\n private rootConfig: RootConfig;\n private routes: RouteTrie<Route>;\n private assetMap: AssetMap;\n private elementGraph: ElementGraph;\n\n constructor(\n rootConfig: RootConfig,\n options: {assetMap: AssetMap; elementGraph: ElementGraph}\n ) {\n this.rootConfig = rootConfig;\n this.routes = getRoutes(this.rootConfig);\n this.assetMap = options.assetMap;\n this.elementGraph = options.elementGraph;\n }\n\n async handle(req: Request, res: Response, next: NextFunction) {\n // TODO(stevenle): handle baseUrl config.\n const url = req.path.toLowerCase();\n const [route, routeParams] = this.routes.get(url);\n if (!route) {\n next();\n return;\n }\n if (route.locale) {\n routeParams.$locale = route.locale;\n }\n\n const fallbackLocales = route.isDefaultLocale\n ? getFallbackLocales(req)\n : [route.locale];\n const getPreferredLocale = (availableLocales: string[]) => {\n const lowerLocales = availableLocales.map((l) => l.toLowerCase());\n for (const fallbackLocale of fallbackLocales) {\n if (lowerLocales.includes(fallbackLocale.toLowerCase())) {\n return fallbackLocale;\n }\n }\n return req.rootConfig?.i18n?.defaultLocale || 'en';\n };\n\n const render404 = async () => {\n // Calling next() will allow the dev server or prod server handle the 404\n // page as appropriate for the env.\n next();\n };\n\n const render: HandlerRenderFn = async (\n props: any,\n options?: HandlerRenderOptions\n ) => {\n if (!route.module.default) {\n console.error(`no default component exported in route: ${route.src}`);\n render404();\n return;\n }\n const currentPath = req.path;\n const locale = options?.locale || route.locale;\n const translations = options?.translations;\n const output = await this.renderComponent(route.module.default, props, {\n currentPath,\n route,\n routeParams,\n locale,\n translations,\n });\n let html = output.html;\n if (this.rootConfig.prettyHtml) {\n html = await htmlPretty(html, this.rootConfig.prettyHtmlOptions);\n } else if (this.rootConfig.minifyHtml !== false) {\n html = await htmlMinify(html, this.rootConfig.minifyHtmlOptions);\n }\n if (req.viteServer) {\n html = await req.viteServer.transformIndexHtml(currentPath, html);\n }\n // Override the status code for 404 and 500 routes, which are defined at\n // routes/404.tsx and routes/500.tsx respectively.\n let statusCode = 200;\n if (route.src === 'routes/404.tsx') {\n statusCode = 404;\n } else if (route.src === 'routes/500.tsx') {\n statusCode = 500;\n }\n req.hooks.trigger('preRender');\n res.status(statusCode).set({'Content-Type': 'text/html'}).end(html);\n };\n\n if (route.module.handle) {\n const handlerContext: HandlerContext = {\n route: route,\n params: routeParams,\n i18nFallbackLocales: fallbackLocales,\n getPreferredLocale: getPreferredLocale,\n render: render,\n render404: render404,\n };\n req.handlerContext = handlerContext;\n return route.module.handle(req, res, next);\n }\n\n let props = {};\n if (route.module.getStaticProps) {\n const propsData = await route.module.getStaticProps({\n rootConfig: this.rootConfig,\n params: routeParams,\n });\n if (propsData.notFound) {\n return render404();\n }\n if (propsData.props) {\n props = propsData.props;\n }\n }\n await render(props);\n }\n\n private async renderComponent(\n Component: ComponentType,\n props: any,\n options: {\n currentPath: string;\n route: Route;\n routeParams: RouteParams;\n locale: string;\n translations?: Record<string, string>;\n }\n ) {\n const {currentPath, route, routeParams} = options;\n const locale = options.locale;\n const translations = {\n ...getTranslations(locale),\n ...(options.translations || {}),\n };\n const ctx: RequestContext = {\n currentPath,\n route,\n props,\n routeParams,\n locale,\n translations,\n };\n const htmlContext: HtmlContext = {\n htmlAttrs: {},\n headAttrs: {},\n headComponents: [],\n bodyAttrs: {},\n scriptDeps: [],\n };\n const vdom = (\n <REQUEST_CONTEXT.Provider value={ctx}>\n <I18N_CONTEXT.Provider value={{locale, translations}}>\n <HTML_CONTEXT.Provider value={htmlContext}>\n <Component {...props} />\n </HTML_CONTEXT.Provider>\n </I18N_CONTEXT.Provider>\n </REQUEST_CONTEXT.Provider>\n );\n const mainHtml = renderToString(vdom);\n\n const jsDeps = new Set<string>();\n const cssDeps = new Set<string>();\n\n // Walk the route's dependency tree for CSS dependencies that are added via\n // `import 'foo.scss'` or `import 'foo.module.scss'`.\n const routeAsset = await this.assetMap.get(route.src);\n if (routeAsset) {\n const routeCssDeps = await routeAsset.getCssDeps();\n routeCssDeps.forEach((dep) => cssDeps.add(dep));\n }\n\n // Parse the HTML for custom elements that are found within the project\n // and automatically inject the script deps for them.\n await this.collectElementDeps(mainHtml, jsDeps, cssDeps);\n\n // Add user defined scripts added via the `<Script>` component.\n await Promise.all(\n htmlContext.scriptDeps.map(async (scriptDep) => {\n if (!scriptDep.src) {\n return;\n }\n const assetId = String(scriptDep.src).slice(1);\n const scriptAsset = await this.assetMap.get(assetId);\n if (scriptAsset) {\n jsDeps.add(scriptAsset.assetUrl);\n const scriptJsDeps = await scriptAsset.getJsDeps();\n scriptJsDeps.forEach((dep) => jsDeps.add(dep));\n }\n })\n );\n\n const styleTags = Array.from(cssDeps).map((cssUrl) => {\n return <link rel=\"stylesheet\" href={cssUrl} />;\n });\n const scriptTags = Array.from(jsDeps).map((jsUrls) => {\n return <script type=\"module\" src={jsUrls} />;\n });\n\n const html = await this.renderHtml(mainHtml, {\n htmlAttrs: htmlContext.htmlAttrs,\n headAttrs: htmlContext.headAttrs,\n bodyAttrs: htmlContext.bodyAttrs,\n headComponents: [\n ...htmlContext.headComponents,\n ...styleTags,\n ...scriptTags,\n ],\n });\n return {html};\n }\n\n /** SSG renders a route. */\n async renderRoute(\n route: Route,\n options: {routeParams: Record<string, string>}\n ): Promise<{html?: string; notFound?: boolean}> {\n const routeParams = options.routeParams;\n if (route.locale) {\n routeParams.$locale = route.locale;\n }\n const Component = route.module.default;\n if (!Component) {\n throw new Error(\n 'unable to render route. the route should have a default export that renders a jsx component.'\n );\n }\n let props = {};\n let locale = route.locale;\n let translations = undefined;\n if (route.module.getStaticProps) {\n const propsData = await route.module.getStaticProps({\n rootConfig: this.rootConfig,\n params: routeParams,\n });\n if (propsData.notFound) {\n return {notFound: true};\n }\n if (propsData.props) {\n props = propsData.props;\n }\n if (propsData.locale) {\n locale = propsData.locale;\n }\n if (propsData.translations) {\n translations = propsData.translations;\n }\n }\n const routePath = route.isDefaultLocale\n ? route.routePath\n : route.localeRoutePath;\n const currentPath = replaceParams(routePath, {\n ...routeParams,\n locale: locale,\n });\n return this.renderComponent(Component, props, {\n currentPath,\n route,\n routeParams,\n locale,\n translations,\n });\n }\n\n async getSitemap(): Promise<\n Record<string, {route: Route; params: Record<string, string>}>\n > {\n const sitemap: Record<\n string,\n {route: Route; params: Record<string, string>}\n > = {};\n await this.routes.walk(async (urlPath: string, route: Route) => {\n const routePaths = await getAllPathsForRoute(urlPath, route);\n routePaths.forEach((routePath) => {\n sitemap[routePath.urlPath] = {\n route,\n params: routePath.params,\n };\n });\n });\n return sitemap;\n }\n\n private async renderHtml(html: string, options?: RenderHtmlOptions) {\n const htmlAttrs = options?.htmlAttrs || {};\n const headAttrs = options?.headAttrs || {};\n const bodyAttrs = options?.bodyAttrs || {};\n const page = (\n <html {...htmlAttrs}>\n <head {...headAttrs}>\n <meta charSet=\"utf-8\" />\n {options?.headComponents}\n </head>\n <body {...bodyAttrs} dangerouslySetInnerHTML={{__html: html}} />\n </html>\n );\n return `<!doctype html>\\n${renderToString(page)}\\n`;\n }\n\n async render404(options?: {currentPath?: string}) {\n const currentPath = options?.currentPath || '/404';\n const [route, routeParams] = this.routes.get('/404');\n if (route && route.src === 'routes/404.tsx' && route.module.default) {\n const Component = route.module.default;\n return this.renderComponent(\n Component,\n {},\n {currentPath, route, routeParams, locale: 'en'}\n );\n }\n\n const mainHtml = renderToString(\n <ErrorPage\n code={404}\n title=\"Not found\"\n message=\"Double-check the URL entered and try again.\"\n align=\"center\"\n />\n );\n const html = await this.renderHtml(mainHtml, {\n headComponents: [\n <title>404 Not Found</title>,\n <meta\n name=\"viewport\"\n content=\"width=device-width, initial-scale=1.0\"\n />,\n ],\n });\n return {html};\n }\n\n async renderError(err: any, options?: {currentPath?: string}) {\n const currentPath = options?.currentPath || '/500';\n const [route, routeParams] = this.routes.get('/500');\n if (route && route.src === 'routes/500.tsx' && route.module.default) {\n const Component = route.module.default;\n return this.renderComponent(\n Component,\n {error: err},\n {currentPath, route, routeParams, locale: 'en'}\n );\n }\n\n const mainHtml = renderToString(\n <ErrorPage\n code={500}\n title=\"Something went wrong\"\n message=\"An unknown error occurred.\"\n align=\"center\"\n />\n );\n const html = await this.renderHtml(mainHtml, {\n headComponents: [\n <title>500 Error</title>,\n <meta\n name=\"viewport\"\n content=\"width=device-width, initial-scale=1.0\"\n />,\n ],\n });\n return {html};\n }\n\n async renderDevServer404(req: Request) {\n const sitemap = await this.getSitemap();\n const mainHtml = renderToString(\n <DevNotFoundPage req={req} sitemap={sitemap} />\n );\n const html = await this.renderHtml(mainHtml, {\n headComponents: [<title>404 Not found | Root.js</title>],\n });\n return {html};\n }\n\n async renderDevServer500(req: Request, error: unknown) {\n const [route, routeParams] = this.routes.get(req.path);\n const mainHtml = renderToString(\n <DevErrorPage\n req={req}\n route={route}\n routeParams={routeParams}\n error={error}\n />\n );\n const html = await this.renderHtml(mainHtml, {\n headComponents: [<title>500 Error | Root.js</title>],\n });\n return {html};\n }\n\n /**\n * Parses rendered HTML for custom element tags used on the page and\n * automatically adds the JS/CSS deps to the page.\n */\n private async collectElementDeps(\n html: string,\n jsDeps: Set<string>,\n cssDeps: Set<string>\n ): Promise<{jsDeps: Set<string>; cssDeps: Set<string>}> {\n const elementsMap = this.elementGraph.sourceFiles;\n const assetMap = this.assetMap;\n\n const tagNames = new Set<string>();\n for (const tagName of parseTagNames(html)) {\n if (tagName && tagName in elementsMap) {\n tagNames.add(tagName);\n for (const depTagName of this.elementGraph.getDeps(tagName)) {\n tagNames.add(depTagName);\n }\n }\n }\n\n await Promise.all(\n Array.from(tagNames).map(async (tagName: string) => {\n const elementModule = elementsMap[tagName];\n const asset = await assetMap.get(elementModule.relPath);\n if (!asset) {\n return;\n }\n const assetJsDeps = await asset.getJsDeps();\n assetJsDeps.forEach((dep) => jsDeps.add(dep));\n const assetCssDeps = await asset.getCssDeps();\n assetCssDeps.forEach((dep) => cssDeps.add(dep));\n })\n );\n\n return {jsDeps, cssDeps};\n }\n}\n","import {ComponentChildren} from 'preact';\n\nconst STYLES = `\n@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap');\n\n:root {\n --font-family-text: \"Inter\", sans-serif;\n}\n\nbody {\n font-family: var(--font-family-text);\n background: #F5F5F5;\n padding: 40px 16px;\n}\n\n.root {\n max-width: 1200px;\n margin: 0 auto;\n}\n\n.root.align-center {\n text-align: center;\n}\n\nh1.title {\n margin-top: 0;\n margin-bottom: 24px;\n}\n\np.message {\n margin-top: 0;\n margin-bottom: 0;\n}\n\n.box {\n font-size: 16px;\n line-height: 1.5;\n padding: 16px;\n border-radius: 12px;\n background: #ffffff;\n}\n\npre.box {\n white-space: pre-wrap;\n}\n\n@media (min-width: 500px) {\n body {\n padding: 40px;\n }\n\n .box {\n padding: 24px;\n }\n}\n\n@media (min-width: 1024px) {\n body {\n padding: 100px;\n }\n}\n`;\n\nexport interface ErrorPageProps {\n code: number;\n title?: string;\n message?: string;\n children?: ComponentChildren;\n align?: 'center';\n}\n\nexport function ErrorPage(props: ErrorPageProps) {\n const {code, message} = props;\n const title = props.title || code;\n return (\n <>\n <style dangerouslySetInnerHTML={{__html: STYLES}}></style>\n <div className={`root align-${props.align || 'left'}`}>\n <h1 className=\"title\">{title}</h1>\n {message && <p className=\"message\">{message}</p>}\n {props.children}\n </div>\n </>\n );\n}\n","import {Request, Route, RouteParams} from '../types';\n\nimport {ErrorPage} from './ErrorPage';\n\ninterface DevErrorPageProps {\n req: Request;\n route?: Route;\n routeParams?: RouteParams;\n error: any;\n}\n\nexport function DevErrorPage(props: DevErrorPageProps) {\n const req = props.req;\n const err = props.error;\n const route = props.route;\n const routeParams = props.routeParams;\n\n let errMsg = String(err);\n if (err && err.stack) {\n // Obfuscate some user info from the stack trace so that when people send\n // error reports and screenshots, less identifiable information is sent.\n errMsg = err.stack\n .replace(/\\(.*node_modules/g, '(node_modules')\n .replace(/at \\/.*node_modules/g, 'at node_modules');\n if (req.rootConfig?.rootDir) {\n errMsg = errMsg.replaceAll(req.rootConfig.rootDir, '<root>');\n }\n if (process.env.HOME) {\n errMsg = errMsg.replaceAll(process.env.HOME, '$HOME');\n }\n }\n return (\n <ErrorPage code={500} title=\"Something went wrong\">\n {errMsg && (\n <>\n <h2>Error</h2>\n <pre className=\"box\">\n <code>{errMsg}</code>\n </pre>\n </>\n )}\n <h2>Debug Info</h2>\n <pre className=\"box\">\n <code>{`url: ${req.originalUrl}\nroute: ${route?.src || 'null'}\nrouteParams: ${(routeParams && JSON.stringify(routeParams)) || 'null'}`}</code>\n </pre>\n </ErrorPage>\n );\n}\n","import {Request, Route} from '../types';\n\nimport {ErrorPage} from './ErrorPage';\n\ninterface DevNotFoundPageProps {\n req: Request;\n sitemap: Record<string, {route: Route; params: Record<string, string>}>;\n}\n\ninterface RoutesListMap {\n [src: string]: Array<RouteURLPath>;\n}\n\ninterface RouteURLPath {\n route: Route;\n urlPath: string;\n}\n\nexport function DevNotFoundPage(props: DevNotFoundPageProps) {\n const req = props.req;\n const routesListMap: RoutesListMap = {};\n let srcMaxLength = 0;\n Object.keys(props.sitemap).forEach((urlPath) => {\n const route = props.sitemap[urlPath].route;\n routesListMap[route.src] ??= [];\n routesListMap[route.src].push({route, urlPath});\n if (route.src.length > srcMaxLength) {\n srcMaxLength = route.src.length;\n }\n });\n const routeSrcs = Object.keys(routesListMap).sort(sortRouteFiles);\n const lines: string[] = [];\n routeSrcs.forEach((routeSrc) => {\n const routeUrls = routesListMap[routeSrc].sort(sortRouteURLs);\n routeUrls.forEach((routeUrl, i) => {\n const urlPath = routeUrl.urlPath;\n if (i === 0) {\n lines.push(`${routeSrc.padEnd(srcMaxLength, ' ')} => ${urlPath}`);\n } else {\n lines.push(`${''.padEnd(srcMaxLength, ' ')} => ${urlPath}`);\n }\n });\n });\n const routesListString = lines.join('\\n');\n // const routesListString = routesList\n // .map((route) => {\n // return `${route.urlPath.padEnd(srcMaxLength, ' ')} => ${route.src}`;\n // })\n // .join('\\n');\n return (\n <ErrorPage code={404} title=\"Not found\">\n <h2>Routes</h2>\n {Object.keys(routesListMap).length > 0 ? (\n <pre className=\"box\">\n <code>{routesListString}</code>\n </pre>\n ) : (\n <div className=\"box\">\n Add your first route at <code>/routes/index.tsx</code>\n </div>\n )}\n\n <h2>Debug Info</h2>\n <pre className=\"box\">\n <code>{`url: ${req.originalUrl}`}</code>\n </pre>\n </ErrorPage>\n );\n}\n\nfunction sortRouteFiles(a: string, b: string): number {\n if (a === 'routes/index.tsx') {\n return -1;\n }\n if (b === 'routes/index.tsx') {\n return 1;\n }\n return a.localeCompare(b);\n}\n\nfunction sortRouteURLs(a: RouteURLPath, b: RouteURLPath): number {\n if (a.route.isDefaultLocale && !b.route.isDefaultLocale) {\n return -1;\n }\n if (!a.route.isDefaultLocale && b.route.isDefaultLocale) {\n return 1;\n }\n return a.urlPath.localeCompare(b.urlPath);\n}\n","export const ACCEPT_LANG_RE =\n /((([a-zA-Z]+(-[a-zA-Z0-9]+){0,2})|\\*)(;q=[0-1](\\.[0-9]+)?)?)*/g;\n\nexport interface AcceptLanguage {\n code: string;\n script?: string;\n region?: string;\n quality: number;\n}\n\nexport function parseAcceptLanguage(value: string): AcceptLanguage[] {\n const matches = String(value).match(ACCEPT_LANG_RE);\n if (!matches) {\n return [];\n }\n const results: AcceptLanguage[] = [];\n matches.forEach((m) => {\n if (!m) {\n return;\n }\n\n const parts = m.split(';');\n const ietf = parts[0].split('-');\n const hasScript = ietf.length === 3;\n\n results.push({\n code: ietf[0],\n script: hasScript ? ietf[1] : undefined,\n region: hasScript ? ietf[2] : ietf[1],\n quality: parts[1] ? parseFloat(parts[1].split('=')[1]) : 1.0,\n });\n });\n results.sort((a, b) => b.quality - a.quality);\n return results;\n}\n","/**\n * Utility functions for handling requests that mimic the Firebase Hosting i18n\n * fallback logic.\n * https://firebase.google.com/docs/hosting/i18n-rewrites\n */\n\nimport {Request} from '../core/types';\nimport {parseAcceptLanguage} from './accept-language';\n\nexport const UNKNOWN_COUNTRY = 'zz';\n\nexport function getFallbackLocales(req: Request): string[] {\n const hl = getFirstQueryParam(req, 'hl');\n const countryCode = getCountry(req);\n\n // Web crawlers should only use the default locale.\n if (isWebCrawler(req)) {\n const defaultLocale = req.rootConfig?.i18n?.defaultLocale || 'en';\n if (hl && hl !== defaultLocale) {\n return [hl, defaultLocale];\n }\n return [defaultLocale];\n }\n\n const locales = new Set<string>();\n\n // Add locales from ?hl= query parameter.\n if (hl) {\n const langCode = hl;\n locales.add(`${langCode}_${countryCode}`);\n locales.add(`${langCode}_ALL`);\n locales.add(langCode);\n }\n\n const langs = getFallbackLanguages(req);\n\n // Add `{lang}_{country}` locales.\n langs.forEach((langCode) => {\n locales.add(`${langCode}_${countryCode}`);\n });\n\n // Add ALL_{country} locale.\n locales.add(`ALL_${countryCode}`);\n\n // Add `{lang}_ALL` and `{lang}` locales.\n langs.forEach((langCode) => {\n locales.add(`${langCode}_ALL`);\n locales.add(langCode);\n });\n\n return Array.from(locales) as string[];\n}\n\nexport function getCountry(req: Request) {\n const normalize = (countryCode: string) => String(countryCode).toLowerCase();\n // Check the ?gl= query param.\n const gl = getFirstQueryParam(req, 'gl');\n if (gl) {\n return normalize(gl);\n }\n const gaeCountry =\n req.get('x-country-code') || req.get('x-appengine-country');\n if (gaeCountry) {\n return normalize(gaeCountry);\n }\n return UNKNOWN_COUNTRY;\n}\n\nfunction getFallbackLanguages(req: Request): string[] {\n const langs = new Set<string>();\n // Add languages from the Accept-Language header.\n const acceptLangHeader = req.get('accept-language') || '';\n if (acceptLangHeader) {\n parseAcceptLanguage(acceptLangHeader).forEach((lang) => {\n // For a lang like `en-US`, add both `en-US` and `en`.\n if (lang.region) {\n langs.add(`${lang.code}-${lang.region}`);\n }\n langs.add(lang.code);\n });\n }\n // Fall back to \"en\" as a last resort.\n langs.add('en');\n return Array.from(langs);\n}\n\n/**\n * Returns the first query param value in a given request.\n *\n * For example, for a URL like `/?foo=bar&foo=baz`, calling\n * `getFirstQueryParam(req, 'foo')` would return `\"bar\"`.\n */\nfunction getFirstQueryParam(req: Request, key: string): string | null {\n const val = req.query[key];\n if (val === null || val === undefined) {\n return null;\n }\n if (Array.isArray(val)) {\n if (val.length === 0) {\n return null;\n }\n return String(val[0]);\n }\n return String(val);\n}\n\nfunction isWebCrawler(req: Request): boolean {\n const userAgentHeader = req.get('User-Agent');\n if (!userAgentHeader) {\n return false;\n }\n const userAgent = userAgentHeader.toLowerCase();\n return (\n userAgent.includes('googlebot') ||\n userAgent.includes('bingbot') ||\n userAgent.includes('twitterbot')\n );\n}\n","import path from 'node:path';\n\nimport {RootConfig} from '../core/config';\nimport {Route, RouteModule} from '../core/types';\n\nimport {RouteTrie} from './route-trie';\n\nexport function getRoutes(config: RootConfig) {\n const locales = config.i18n?.locales || [];\n const i18nUrlFormat = config.i18n?.urlFormat || '/{locale}/{path}';\n const defaultLocale = config.i18n?.defaultLocale || 'en';\n\n const routes = import.meta.glob(\n ['/routes/*.ts', '/routes/**/*.ts', '/routes/*.tsx', '/routes/**/*.tsx'],\n {\n eager: true,\n }\n );\n const trie = new RouteTrie<Route>();\n Object.keys(routes).forEach((modulePath) => {\n const src = modulePath.slice(1);\n let routePath = modulePath.replace(/^\\/routes/, '');\n const parts = path.parse(routePath);\n if (parts.name.startsWith('_')) {\n return;\n }\n if (parts.name === 'index') {\n routePath = parts.dir;\n } else {\n routePath = path.join(parts.dir, parts.name);\n }\n\n const localeRoutePath = i18nUrlFormat\n .replace('{locale}', '[locale]')\n .replace('{path}', routePath.replace(/^\\/*/, ''));\n\n trie.add(routePath, {\n src,\n module: routes[modulePath] as RouteModule,\n locale: defaultLocale,\n isDefaultLocale: true,\n routePath: normalizeUrlPath(routePath),\n localeRoutePath: normalizeUrlPath(localeRoutePath),\n });\n\n // At the moment, all routes are assumed to use the site-wide i18n config.\n // TODO(stevenle): provide routes with a way to override the default\n // i18n serving behavior.\n locales.forEach((locale) => {\n const localePath = localeRoutePath.replace('[locale]', locale);\n if (localePath !== routePath) {\n trie.add(localePath, {\n src,\n module: routes[modulePath] as RouteModule,\n locale: locale,\n isDefaultLocale: false,\n routePath,\n localeRoutePath,\n });\n }\n });\n });\n return trie;\n}\n\nexport async function getAllPathsForRoute(\n urlPathFormat: string,\n route: Route\n): Promise<Array<{urlPath: string; params: Record<string, string>}>> {\n const routeModule = route.module;\n if (!routeModule.default) {\n return [];\n }\n\n const urlPaths: Array<{urlPath: string; params: Record<string, string>}> = [];\n if (routeModule.getStaticPaths) {\n const staticPaths = await routeModule.getStaticPaths();\n if (staticPaths.paths) {\n staticPaths.paths.forEach(\n (pathParams: {params: Record<string, string>}) => {\n const urlPath = replaceParams(urlPathFormat, pathParams.params || {});\n if (pathContainsPlaceholders(urlPath)) {\n console.warn(\n `path contains placeholders: ${urlPathFormat}, double check getStaticPaths() and ensure all params are returned. more info: https://rootjs.dev/guide/routes#getStaticPaths`\n );\n } else {\n urlPaths.push({\n urlPath: normalizeUrlPath(urlPath),\n params: pathParams.params || {},\n });\n }\n }\n );\n }\n } else if (\n routeModule.getStaticProps &&\n !pathContainsPlaceholders(urlPathFormat)\n ) {\n urlPaths.push({urlPath: normalizeUrlPath(urlPathFormat), params: {}});\n } else if (!routeModule.handle && !pathContainsPlaceholders(urlPathFormat)) {\n urlPaths.push({urlPath: normalizeUrlPath(urlPathFormat), params: {}});\n } else if (\n pathContainsPlaceholders(urlPathFormat) &&\n !routeModule.handle &&\n !routeModule.getStaticPaths\n ) {\n console.warn(\n [\n `warning: path contains placeholders: ${urlPathFormat}.`,\n `define either ssg getStaticPaths() or ssr handle() for route: ${route.src}.`,\n 'more info: https://rootjs.dev/guide/routes',\n ].join('\\n')\n );\n }\n\n return urlPaths;\n}\n\nexport function replaceParams(\n urlPathFormat: string,\n params: Record<string, string>\n) {\n const urlPath = urlPathFormat.replaceAll(\n /\\[\\[?(\\.\\.\\.)?([\\w\\-_]*)\\]?\\]/g,\n (match: string, _wildcard: string, key: string) => {\n const val = params[key];\n if (!val) {\n throw new Error(`unreplaced param ${match} in url: ${urlPathFormat}`);\n }\n return val;\n }\n );\n return urlPath;\n}\n\nexport function normalizeUrlPath(urlPath: string) {\n if (urlPath !== '/' && urlPath.endsWith('/')) {\n urlPath = urlPath.replace(/\\/*$/g, '');\n }\n return urlPath;\n}\n\nfunction pathContainsPlaceholders(urlPath: string) {\n const segments = urlPath.split('/');\n return segments.some((segment) => {\n return segment.startsWith('[') && segment.endsWith(']');\n });\n}\n","/**\n * A trie data structure that stores routes. Supports Next-style routing using\n * [param], [...catchall], and [[...optcatchall]] placeholders.\n */\nexport class RouteTrie<T> {\n private children: Record<string, RouteTrie<T>> = {};\n private paramNodes?: {[param: string]: ParamNode<T>};\n private catchAllNodes?: CatchAllNode<T>;\n private optCatchAllNodes?: CatchAllNode<T>;\n private route?: T;\n\n /**\n * Adds a route to the trie.\n */\n add(path: string, route: T) {\n path = this.normalizePath(path);\n\n // If the end was reached, save the value to the node.\n if (path === '') {\n this.route = route;\n return;\n }\n\n const [head, tail] = this.splitPath(path);\n\n if (head.startsWith('[[...') && head.endsWith(']]')) {\n const paramName = head.slice(5, -2);\n this.optCatchAllNodes = new CatchAllNode(paramName, route);\n return;\n }\n if (head.startsWith('[...') && head.endsWith(']')) {\n const paramName = head.slice(4, -1);\n this.catchAllNodes = new CatchAllNode(paramName, route);\n return;\n }\n\n let nextNode: RouteTrie<T>;\n if (head.startsWith('[') && head.endsWith(']')) {\n if (!this.paramNodes) {\n this.paramNodes = {};\n }\n const paramName = head.slice(1, -1);\n if (!this.paramNodes[paramName]) {\n this.paramNodes[paramName] = new ParamNode(paramName);\n }\n nextNode = this.paramNodes[paramName].trie;\n } else {\n nextNode = this.children[head];\n if (!nextNode) {\n nextNode = new RouteTrie();\n this.children[head] = nextNode;\n }\n }\n nextNode.add(tail, route);\n }\n\n /**\n * Returns a route mapped to the given path and any parameter values from the\n * URL.\n */\n get(path: string): [T | undefined, Record<string, string>] {\n const params = {};\n const route = this.getRoute(path, params);\n return [route, params];\n }\n\n /**\n * Walks the route trie and calls a callback function for each route.\n */\n walk(cb: (urlPath: string, route: T) => Promise<void> | void): Promise<void> {\n const promises: Array<Promise<void>> = [];\n const addPromise = (promise: Promise<void> | void) => {\n if (promise) {\n promises.push(promise);\n }\n };\n if (this.route) {\n addPromise(cb('/', this.route));\n }\n if (this.paramNodes) {\n Object.values(this.paramNodes).forEach((paramChild) => {\n const param = `[${paramChild.name}]`;\n paramChild.trie.walk((childPath: string, route: T) => {\n const paramUrlPath = `/${param}${childPath}`;\n addPromise(cb(paramUrlPath, route));\n });\n });\n }\n if (this.catchAllNodes) {\n const wildcardUrlPath = `/[...${this.catchAllNodes.name}]`;\n addPromise(cb(wildcardUrlPath, this.catchAllNodes.route));\n }\n if (this.optCatchAllNodes) {\n const wildcardUrlPath = `/[[...${this.optCatchAllNodes.name}]]`;\n addPromise(cb(wildcardUrlPath, this.optCatchAllNodes.route));\n }\n for (const subpath of Object.keys(this.children)) {\n const childTrie = this.children[subpath];\n childTrie.walk((childPath: string, childRoute: T) => {\n addPromise(cb(`/${subpath}${childPath}`, childRoute));\n });\n }\n return Promise.all(promises).then(() => {});\n }\n\n /**\n * Removes all routes from the trie.\n */\n clear() {\n this.children = {};\n this.paramNodes = undefined;\n this.catchAllNodes = undefined;\n this.optCatchAllNodes = undefined;\n this.route = undefined;\n }\n\n private getRoute(\n urlPath: string,\n params: Record<string, string>\n ): T | undefined {\n urlPath = this.normalizePath(urlPath);\n if (urlPath === '') {\n if (this.route) {\n return this.route;\n }\n if (this.optCatchAllNodes) {\n if (urlPath) {\n params[this.optCatchAllNodes.name] = urlPath;\n }\n return this.optCatchAllNodes.route;\n }\n return undefined;\n }\n\n const [head, tail] = this.splitPath(urlPath);\n\n const child = this.children[head];\n if (child) {\n const route = child.getRoute(tail, params);\n if (route) {\n return route;\n }\n }\n\n if (this.paramNodes) {\n for (const paramChild of Object.values(this.paramNodes)) {\n const route = paramChild.trie.getRoute(tail, params);\n if (route) {\n params[paramChild.name] = head;\n return route;\n }\n }\n }\n\n if (this.catchAllNodes) {\n params[this.catchAllNodes.name] = urlPath;\n return this.catchAllNodes.route;\n }\n\n if (this.optCatchAllNodes) {\n params[this.optCatchAllNodes.name] = urlPath;\n return this.optCatchAllNodes.route;\n }\n\n return undefined;\n }\n\n /**\n * Normalizes a path for inclusion into the route trie.\n */\n private normalizePath(path: string) {\n // Remove leading/trailing slashes.\n return path.replace(/^\\/+/g, '').replace(/\\/+$/g, '');\n }\n\n /**\n * Splits the parent directory from its children, e.g.:\n *\n * splitPath(\"foo/bar/baz\") -> [\"foo\", \"bar/baz\"]\n */\n private splitPath(path: string): [string, string] {\n const i = path.indexOf('/');\n if (i === -1) {\n return [path, ''];\n }\n return [path.slice(0, i), path.slice(i + 1)];\n }\n}\n\n/**\n * A node in the RouteTrie for a :param child.\n */\nclass ParamNode<T> {\n readonly name: string;\n readonly trie: RouteTrie<T> = new RouteTrie();\n\n constructor(name: string) {\n this.name = name;\n }\n}\n\n/**\n * A node in the RouteTrie for a *wildcard child.\n */\nclass CatchAllNode<T> {\n readonly name: string;\n readonly route: T;\n\n constructor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M,cAAc,MAAM,MAAM,UAAU;AAC1C,oBAAY,QAAQ,CAAC,QAAQ,OAAO,IAAI,GAAG,CAAC;AAC5C,cAAM,eAAe,MAAM,MAAM,WAAW;AAC5C,qBAAa,QAAQ,CAAC,QAAQ,QAAQ,IAAI,GAAG,CAAC;AAAA,MAChD,CAAC;AAAA,IACH;AAEA,WAAO,EAAC,QAAQ,QAAO;AAAA,EACzB;AACF;","names":["Fragment","jsx","jsxs","jsx","jsxs","path","jsx","jsxs","props"]}
|
|
@@ -33,12 +33,12 @@ declare class Session {
|
|
|
33
33
|
toString(): string;
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
type HtmlMinifyOptions = Options;
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
type HtmlPrettyOptions = HTMLBeautifyOptions;
|
|
39
39
|
|
|
40
|
-
|
|
41
|
-
|
|
40
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
41
|
+
type ConfigureServerHook = (server: Server, options: ConfigureServerOptions) => MaybePromise<void> | MaybePromise<() => void>;
|
|
42
42
|
interface ConfigureServerOptions {
|
|
43
43
|
type: 'dev' | 'preview' | 'prod';
|
|
44
44
|
rootConfig: RootConfig;
|
|
@@ -137,7 +137,7 @@ interface RootUserConfig {
|
|
|
137
137
|
*/
|
|
138
138
|
plugins?: Plugin[];
|
|
139
139
|
}
|
|
140
|
-
|
|
140
|
+
type RootConfig = RootUserConfig & {
|
|
141
141
|
rootDir: string;
|
|
142
142
|
};
|
|
143
143
|
interface LocaleGroup {
|
|
@@ -303,13 +303,13 @@ declare class Renderer {
|
|
|
303
303
|
* Param values from the route, e.g. a route like `/route/[slug].tsx` will pass
|
|
304
304
|
* `{slug: 'foo'}`.
|
|
305
305
|
*/
|
|
306
|
-
|
|
306
|
+
type RouteParams = Record<string, string>;
|
|
307
307
|
/**
|
|
308
308
|
* The `getStaticProps()` function is an optional function that routes can
|
|
309
309
|
* define to fetch and transform props before passing it to the route's
|
|
310
310
|
* component.
|
|
311
311
|
*/
|
|
312
|
-
|
|
312
|
+
type GetStaticProps<T = unknown> = (ctx: {
|
|
313
313
|
rootConfig: RootConfig;
|
|
314
314
|
params: RouteParams;
|
|
315
315
|
}) => Promise<{
|
|
@@ -331,7 +331,7 @@ declare type GetStaticProps<T = unknown> = (ctx: {
|
|
|
331
331
|
* paths that should exist for a given route. This should be used alongside a
|
|
332
332
|
* parameterized route, e.g. `/routes/blog/[slug].tsx`.
|
|
333
333
|
*/
|
|
334
|
-
|
|
334
|
+
type GetStaticPaths<T = RouteParams> = () => Promise<{
|
|
335
335
|
paths: Array<{
|
|
336
336
|
params: T;
|
|
337
337
|
}>;
|
|
@@ -344,14 +344,14 @@ interface MultipartFile {
|
|
|
344
344
|
mimetype: string;
|
|
345
345
|
buffer: Buffer;
|
|
346
346
|
}
|
|
347
|
-
|
|
347
|
+
type RequestMiddleware = ((req: Request, res: Response) => any) | ((req: Request, res: Response, next: NextFunction) => any) | ((err: any, req: Request, res: Response, next: NextFunction) => any);
|
|
348
348
|
/** Root.js express app. */
|
|
349
|
-
|
|
349
|
+
type Server = Express & {
|
|
350
350
|
use(middlewares: RequestMiddleware | RequestMiddleware[]): any;
|
|
351
351
|
use(urlPath: string, middlewares: RequestMiddleware | RequestMiddleware[]): any;
|
|
352
352
|
};
|
|
353
353
|
/** Root.js express request. */
|
|
354
|
-
|
|
354
|
+
type Request = Request$1 & {
|
|
355
355
|
/** The root.js project config. */
|
|
356
356
|
rootConfig?: RootConfig & {
|
|
357
357
|
rootDir: string;
|
|
@@ -376,12 +376,12 @@ declare type Request = Request$1 & {
|
|
|
376
376
|
};
|
|
377
377
|
};
|
|
378
378
|
/** Root.js express response. */
|
|
379
|
-
|
|
379
|
+
type Response = Response$1 & {
|
|
380
380
|
session: Session;
|
|
381
381
|
saveSession: () => void;
|
|
382
382
|
};
|
|
383
383
|
/** Root.js express next function. */
|
|
384
|
-
|
|
384
|
+
type NextFunction = NextFunction$1;
|
|
385
385
|
/**
|
|
386
386
|
* A context variable passed to a route's `handle()` method within the req
|
|
387
387
|
* object.
|
|
@@ -418,7 +418,7 @@ interface HandlerContext<T = any> {
|
|
|
418
418
|
* contains the route's param values and also a `render()` method that can be
|
|
419
419
|
* used to render the route's default component.
|
|
420
420
|
*/
|
|
421
|
-
|
|
421
|
+
type Handler = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
|
|
422
422
|
interface RouteModule {
|
|
423
423
|
default?: ComponentType<unknown>;
|
|
424
424
|
getStaticPaths?: GetStaticPaths;
|
|
@@ -465,6 +465,6 @@ interface HandlerRenderOptions {
|
|
|
465
465
|
*/
|
|
466
466
|
translations?: Record<string, string>;
|
|
467
467
|
}
|
|
468
|
-
|
|
468
|
+
type HandlerRenderFn = (props: any, options?: HandlerRenderOptions) => Promise<void>;
|
|
469
469
|
|
|
470
470
|
export { ConfigureServerHook as C, GetStaticProps as G, HandlerContext as H, LocaleGroup as L, MultipartFile as M, NextFunction as N, Plugin as P, Route as R, Server as S, RootUserConfig as a, RootConfig as b, RootI18nConfig as c, RootServerConfig as d, defineConfig as e, ConfigureServerOptions as f, configureServerPlugins as g, getVitePlugins as h, RouteParams as i, GetStaticPaths as j, RequestMiddleware as k, Request as l, Response as m, Handler as n, RouteModule as o, HandlerRenderOptions as p, HandlerRenderFn as q, SESSION_COOKIE as r, SessionMiddlewareOptions as s, SaveSessionOptions as t, sessionMiddleware as u, Session as v, Renderer as w };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blinkk/root",
|
|
3
|
-
"version": "1.0.0-rc.
|
|
3
|
+
"version": "1.0.0-rc.2",
|
|
4
4
|
"author": "s@blinkk.com",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"engines": {
|
|
@@ -54,27 +54,27 @@
|
|
|
54
54
|
}
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
|
-
"bundle-require": "^4.0.
|
|
57
|
+
"bundle-require": "^4.0.2",
|
|
58
58
|
"busboy": "^1.6.0",
|
|
59
|
-
"commander": "^
|
|
59
|
+
"commander": "^11.0.0",
|
|
60
60
|
"compression": "^1.7.4",
|
|
61
61
|
"cookie-parser": "^1.4.6",
|
|
62
62
|
"esbuild": "0.19.4",
|
|
63
|
-
"express": "^4.18.
|
|
64
|
-
"fs-extra": "^
|
|
65
|
-
"html-minifier-terser": "^7.
|
|
66
|
-
"js-beautify": "^1.14.
|
|
63
|
+
"express": "^4.18.2",
|
|
64
|
+
"fs-extra": "^11.1.1",
|
|
65
|
+
"html-minifier-terser": "^7.2.0",
|
|
66
|
+
"js-beautify": "^1.14.9",
|
|
67
67
|
"kleur": "^4.1.5",
|
|
68
|
-
"sass": "^1.
|
|
69
|
-
"sirv": "^2.0.
|
|
68
|
+
"sass": "^1.69.3",
|
|
69
|
+
"sirv": "^2.0.3",
|
|
70
70
|
"tiny-glob": "^0.2.9",
|
|
71
|
-
"vite": "4.
|
|
71
|
+
"vite": "4.4.11"
|
|
72
72
|
},
|
|
73
73
|
"peerDependencies": {
|
|
74
74
|
"firebase-admin": ">=11",
|
|
75
75
|
"firebase-functions": ">=4",
|
|
76
|
-
"preact": "10
|
|
77
|
-
"preact-render-to-string": "5
|
|
76
|
+
"preact": ">=10",
|
|
77
|
+
"preact-render-to-string": ">=5"
|
|
78
78
|
},
|
|
79
79
|
"peerDependenciesMeta": {
|
|
80
80
|
"firebase-functions": {
|
|
@@ -89,21 +89,20 @@
|
|
|
89
89
|
"@types/compression": "^1.7.2",
|
|
90
90
|
"@types/cookie-parser": "^1.4.3",
|
|
91
91
|
"@types/express": "^4.17.13",
|
|
92
|
-
"@types/fs-extra": "^
|
|
92
|
+
"@types/fs-extra": "^11.0.2",
|
|
93
93
|
"@types/html-minifier-terser": "^7.0.0",
|
|
94
|
-
"@types/js-beautify": "^1.
|
|
95
|
-
"@types/node": "^
|
|
96
|
-
"@types/preact-custom-element": "^4.0.
|
|
97
|
-
"firebase-admin": "^11.
|
|
98
|
-
"firebase-functions": "^4.4.
|
|
99
|
-
"nodemon": "^
|
|
100
|
-
"preact": "^10.
|
|
101
|
-
"preact-custom-element": "^4.
|
|
102
|
-
"preact-render-to-string": "^
|
|
103
|
-
"rollup": "^2.79.0",
|
|
94
|
+
"@types/js-beautify": "^1.14.1",
|
|
95
|
+
"@types/node": "^20.8.4",
|
|
96
|
+
"@types/preact-custom-element": "^4.0.2",
|
|
97
|
+
"firebase-admin": "^11.11.0",
|
|
98
|
+
"firebase-functions": "^4.4.1",
|
|
99
|
+
"nodemon": "^3.0.1",
|
|
100
|
+
"preact": "^10.18.1",
|
|
101
|
+
"preact-custom-element": "^4.3.0",
|
|
102
|
+
"preact-render-to-string": "^6.2.2",
|
|
104
103
|
"tsup": "^7.2.0",
|
|
105
|
-
"typescript": "^
|
|
106
|
-
"vitest": "^0.
|
|
104
|
+
"typescript": "^5.2.2",
|
|
105
|
+
"vitest": "^0.34.6"
|
|
107
106
|
},
|
|
108
107
|
"scripts": {
|
|
109
108
|
"build": "rm -rf dist && tsup-node",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli/commands/build.ts","../src/node/element-graph.ts","../src/render/asset-map/build-asset-map.ts","../src/utils/batch.ts","../src/cli/commands/dev.ts","../src/middleware/hooks.ts","../src/render/asset-map/dev-asset-map.ts","../src/utils/ports.ts","../src/utils/rand.ts","../src/cli/commands/preview.ts","../src/cli/commands/start.ts"],"sourcesContent":["/* eslint-disable no-control-regex */\nimport path from 'node:path';\nimport {fileURLToPath} from 'node:url';\n\nimport fsExtra from 'fs-extra';\nimport {dim, cyan} from 'kleur/colors';\nimport glob from 'tiny-glob';\nimport {build as viteBuild, Manifest, ManifestChunk, UserConfig} from 'vite';\n\nimport {getVitePlugins} from '../../core/plugin.js';\nimport {Route} from '../../core/types.js';\nimport {getElements} from '../../node/element-graph.js';\nimport {loadRootConfig} from '../../node/load-config.js';\nimport {BuildAssetMap} from '../../render/asset-map/build-asset-map.js';\nimport {htmlMinify} from '../../render/html-minify.js';\nimport {htmlPretty} from '../../render/html-pretty.js';\nimport {batchAsyncCalls} from '../../utils/batch.js';\nimport {\n copyGlob,\n fileExists,\n isDirectory,\n isJsFile,\n loadJson,\n makeDir,\n rmDir,\n writeFile,\n} from '../../utils/fsutils.js';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\ntype RenderModule = typeof import('../../render/render.js');\n\ninterface BuildOptions {\n ssrOnly?: boolean;\n mode?: string;\n concurrency?: number;\n}\n\nexport async function build(rootProjectDir?: string, options?: BuildOptions) {\n const mode = options?.mode || 'production';\n process.env.NODE_ENV = mode;\n\n const rootDir = path.resolve(rootProjectDir || process.cwd());\n const rootConfig = await loadRootConfig(rootDir, {command: 'build'});\n const distDir = path.join(rootDir, 'dist');\n const ssrOnly = options?.ssrOnly || false;\n\n console.log();\n console.log(`${dim('┃')} project: ${rootDir}`);\n console.log(`${dim('┃')} output: ${distDir}/html`);\n console.log(`${dim('┃')} mode: ${mode}`);\n console.log();\n\n await rmDir(distDir);\n await makeDir(distDir);\n\n const routeFiles: string[] = [];\n if (await isDirectory(path.join(rootDir, 'routes'))) {\n const pageFiles = await glob('routes/**/*', {cwd: rootDir});\n pageFiles.forEach((file) => {\n const parts = path.parse(file);\n if (!parts.name.startsWith('_') && isJsFile(parts.base)) {\n routeFiles.push(path.resolve(rootDir, file));\n }\n });\n }\n\n const elementGraph = await getElements(rootConfig);\n const elements = Object.values(elementGraph.sourceFiles).map((sourceFile) => {\n return sourceFile.filePath;\n });\n\n const bundleScripts: string[] = [];\n if (await isDirectory(path.join(rootDir, 'bundles'))) {\n const bundleFiles = await glob('bundles/*', {cwd: rootDir});\n bundleFiles.forEach((file) => {\n const parts = path.parse(file);\n if (isJsFile(parts.base)) {\n bundleScripts.push(path.resolve(rootDir, file));\n }\n });\n }\n\n const rootPlugins = rootConfig.plugins || [];\n const viteConfig = rootConfig.vite || {};\n const vitePlugins = [\n ...(viteConfig.plugins || []),\n ...getVitePlugins(rootPlugins),\n ];\n\n const baseConfig: UserConfig = {\n ...viteConfig,\n root: rootDir,\n mode: mode,\n esbuild: {\n ...viteConfig.esbuild,\n jsx: 'automatic',\n jsxImportSource: 'preact',\n treeShaking: true,\n },\n plugins: vitePlugins,\n };\n\n // Bundle the render.js file with vite along with any plugins `ssrInput()`\n // config values. These inputs are bundled through vite and support things\n // like `input.meta.glob()`.\n const ssrInput = {\n render: path.resolve(__dirname, './render.js'),\n };\n rootPlugins.forEach((plugin) => {\n if (plugin.ssrInput) {\n Object.assign(ssrInput, plugin.ssrInput());\n }\n });\n const noExternalConfig = viteConfig.ssr?.noExternal;\n const noExternal: Array<string | RegExp> = [];\n if (noExternalConfig) {\n if (Array.isArray(noExternalConfig)) {\n noExternal.push(...noExternalConfig);\n } else {\n noExternal.push(noExternalConfig as string | RegExp);\n }\n }\n await viteBuild({\n ...baseConfig,\n publicDir: false,\n build: {\n ...viteConfig?.build,\n rollupOptions: {\n ...viteConfig?.build?.rollupOptions,\n input: ssrInput,\n output: {\n format: 'esm',\n chunkFileNames: 'chunks/[hash].min.js',\n assetFileNames: 'assets/[name].[hash][extname]',\n sanitizeFileName: sanitizeFileName,\n },\n },\n outDir: path.join(distDir, 'server'),\n ssr: true,\n ssrManifest: false,\n cssCodeSplit: true,\n target: 'esnext',\n minify: false,\n modulePreload: {polyfill: false},\n reportCompressedSize: false,\n },\n ssr: {\n ...viteConfig.ssr,\n target: 'node',\n noExternal: ['@blinkk/root', ...noExternal],\n },\n });\n\n // Pre-render CSS deps from /routes/.\n await viteBuild({\n ...baseConfig,\n publicDir: false,\n build: {\n ...viteConfig?.build,\n rollupOptions: {\n ...viteConfig?.build?.rollupOptions,\n input: [...routeFiles],\n output: {\n format: 'esm',\n entryFileNames: 'assets/[name].[hash].min.js',\n assetFileNames: 'assets/[name].[hash][extname]',\n chunkFileNames: 'chunks/[hash].min.js',\n sanitizeFileName: sanitizeFileName,\n ...viteConfig?.build?.rollupOptions?.output,\n },\n },\n outDir: path.join(distDir, 'routes'),\n ssr: false,\n ssrManifest: false,\n manifest: true,\n cssCodeSplit: true,\n target: 'esnext',\n minify: true,\n modulePreload: {polyfill: false},\n reportCompressedSize: false,\n },\n });\n\n // Pre-render /elements/ and /bundles/.\n const clientInput = [...elements, ...bundleScripts];\n if (clientInput.length > 0) {\n await viteBuild({\n ...baseConfig,\n publicDir: false,\n build: {\n ...viteConfig?.build,\n rollupOptions: {\n ...viteConfig?.build?.rollupOptions,\n input: [...elements, ...bundleScripts],\n output: {\n format: 'esm',\n entryFileNames: 'assets/[name].[hash].min.js',\n assetFileNames: 'assets/[name].[hash][extname]',\n chunkFileNames: 'chunks/[hash].min.js',\n sanitizeFileName: sanitizeFileName,\n ...viteConfig?.build?.rollupOptions?.output,\n },\n },\n outDir: path.join(distDir, 'client'),\n ssr: false,\n ssrManifest: false,\n manifest: true,\n cssCodeSplit: true,\n target: 'esnext',\n minify: true,\n modulePreload: {polyfill: false},\n reportCompressedSize: false,\n },\n });\n } else {\n await writeFile(path.join(distDir, 'client/manifest.json'), '{}');\n }\n\n // Copy CSS files from dist/routes/**/*.css to dist/client/ and flatten the\n // routes manifest to ignore imported modules. Then add the route assets to\n // the client manifest.\n await copyGlob(\n '**/*.css',\n path.join(distDir, 'routes'),\n path.join(distDir, 'client')\n );\n const routesManifest = await loadJson<Manifest>(\n path.join(distDir, 'routes/manifest.json')\n );\n const clientManifest = await loadJson<Manifest>(\n path.join(distDir, 'client/manifest.json')\n );\n function collectRouteCss(\n asset: ManifestChunk,\n cssDeps: Set<string>,\n visited: Set<string>\n ) {\n if (!asset || !asset.file || visited.has(asset.file)) {\n return;\n }\n visited.add(asset.file);\n if (asset.css) {\n asset.css.forEach((dep) => cssDeps.add(dep));\n }\n if (asset.imports) {\n asset.imports.forEach((manifestKey) => {\n collectRouteCss(routesManifest[manifestKey], cssDeps, visited);\n });\n }\n }\n Object.keys(routesManifest).forEach((manifestKey) => {\n const asset = routesManifest[manifestKey];\n if (asset.isEntry) {\n const visited = new Set<string>();\n const cssDeps = new Set<string>();\n collectRouteCss(asset, cssDeps, visited);\n asset.css = Array.from(cssDeps);\n asset.imports = [];\n clientManifest[manifestKey] = asset;\n } else if (asset.file.endsWith('.css')) {\n clientManifest[manifestKey] = asset;\n }\n });\n\n // Use the output of the client build to generate an asset map, which is used\n // by the renderer for automatically injecting dependencies for a page.\n const assetMap = BuildAssetMap.fromViteManifest(\n rootConfig,\n clientManifest,\n elementGraph\n );\n\n // Save the asset map to `dist/client` for use by the prod SSR server.\n const rootManifest = assetMap.toJson();\n await writeFile(\n path.join(distDir, 'client/root-manifest.json'),\n JSON.stringify(rootManifest, null, 2)\n );\n\n // Save the element graph to `dist/client` for use by the prod SSR server.\n const elementGraphJson = elementGraph.toJson();\n await writeFile(\n path.join(distDir, 'client/root-element-graph.json'),\n JSON.stringify(elementGraphJson, null, 2)\n );\n\n // Write SSG output to `dist/html`.\n const buildDir = path.join(distDir, 'html');\n\n // Recursively copy files from `public` to `dist/html`.\n const publicDir = path.join(rootDir, 'public');\n if (fsExtra.existsSync(path.join(rootDir, 'public'))) {\n fsExtra.copySync(publicDir, buildDir, {dereference: true});\n } else {\n await makeDir(buildDir);\n }\n\n // Copy files from `dist/client/{assets,chunks}` to `dist/html` using the\n // root manifest. Ignore route files.\n console.log('\\njs/css output:');\n await Promise.all(\n Object.keys(rootManifest).map(async (src) => {\n // Don't expose route files in the final output. If any client-side code\n // relies on route dependencies, it should probably be broken out into a\n // shared component instead.\n if (isRouteFile(src)) {\n return;\n }\n const assetData = rootManifest[src];\n // Ignore files with no assetUrl, which can sometimes occur if a source\n // file is empty.\n if (!assetData.assetUrl) {\n return;\n }\n const assetRelPath = assetData.assetUrl.slice(1);\n const assetFrom = path.join(distDir, 'client', assetRelPath);\n const assetTo = path.join(buildDir, assetRelPath);\n // Ignore assets that don't exist. This is because build artifacts from\n // the routes/ folder are not copied to dist/client (only css deps are).\n if (!(await fileExists(assetFrom))) {\n console.log(`${assetFrom} does not exist`);\n return;\n }\n await fsExtra.copy(assetFrom, assetTo);\n printFileOutput(fileSize(assetTo), 'dist/html/', assetRelPath);\n })\n );\n\n // Pre-render HTML pages (SSG).\n if (!ssrOnly) {\n const render: RenderModule = await import(\n path.join(distDir, 'server/render.js')\n );\n const renderer = new render.Renderer(rootConfig, {assetMap, elementGraph});\n const sitemap = await renderer.getSitemap();\n\n console.log('\\nhtml output:');\n const batchSize = Number(options?.concurrency || 10);\n await batchAsyncCalls(Object.keys(sitemap), batchSize, async (urlPath) => {\n const {route, params} = sitemap[urlPath];\n try {\n const data = await renderer.renderRoute(route, {\n routeParams: params,\n });\n if (data.notFound) {\n return;\n }\n\n // The renderer currently assumes that all paths serve HTML.\n // TODO(stevenle): support non-HTML routes using `routes/[name].[ext].ts`.\n let outFilePath = path.join(urlPath.slice(1), 'index.html');\n if (outFilePath.endsWith('404/index.html')) {\n outFilePath = outFilePath.replace('404/index.html', '404.html');\n }\n const outPath = path.join(buildDir, outFilePath);\n\n let html = data.html || '';\n if (rootConfig.prettyHtml !== false) {\n html = await htmlPretty(html, rootConfig.prettyHtmlOptions);\n }\n // HTML minification is `true` by default. Set to `false` to disable.\n if (rootConfig.minifyHtml !== false) {\n html = await htmlMinify(html, rootConfig.minifyHtmlOptions);\n }\n await writeFile(outPath, html);\n\n printFileOutput(fileSize(outPath), 'dist/html/', outFilePath);\n } catch (e) {\n logBuildError({route, params, urlPath}, e);\n throw new Error(\n `BuildError: ${urlPath} (${route.src}) failed to build.`\n );\n }\n });\n }\n}\n\nfunction isRouteFile(filepath: string) {\n return filepath.startsWith('routes') && isJsFile(filepath);\n}\n\nfunction fileSize(filepath: string) {\n const stats = fsExtra.statSync(filepath);\n const bytes = stats.size;\n\n const k = 1024;\n if (bytes < k) {\n return (bytes / k).toFixed(2) + ' kB';\n }\n const units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + units[i];\n}\n\nfunction printFileOutput(\n fileSize: string,\n outputDir: string,\n outputFile: string\n) {\n const indent = ' '.repeat(2);\n const paddedSize = fileSize.padStart(9, ' ');\n console.log(\n `${indent}${dim(paddedSize)} ${dim(outputDir)}${cyan(outputFile)}`\n );\n}\n\nfunction sanitizeFileName(name: string): string {\n return (\n name\n // Remove placeholder vars from paths like routes/[...var].tsx.\n .replaceAll('...', '')\n .replaceAll('_', '')\n .replaceAll('[', '')\n .replaceAll(']', '')\n // Remove non-ascii chars and null bytes.\n .replace(/[^\\x00-\\x7F]/g, '')\n .replace(/\\x00/g, '')\n .toLowerCase()\n );\n}\n\ninterface BuildContext {\n route: Route;\n params: Record<string, string>;\n urlPath: string;\n}\n\nfunction logBuildError(ctx: BuildContext, e: Error) {\n const {route, params, urlPath} = ctx;\n const errorString = String(e.stack || e);\n console.error();\n if (Object.keys(params).length > 0) {\n console.error(\n `An error occurred building ${urlPath} (${route.src}) with params:\n${formatParams(params)}\n\nThe error was:\n ${errorString}\n `.trim()\n );\n } else {\n console.error(\n `An error occurred building ${urlPath} (${route.src})\n\nThe error was:\n ${errorString}`\n );\n }\n}\n\nfunction formatParams(params: Record<string, string>) {\n return Object.entries(params)\n .map(([key, value]) => {\n return ` ${key}: ${value}`;\n })\n .join('\\n');\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport glob from 'tiny-glob';\nimport {searchForWorkspaceRoot} from 'vite';\n\nimport {RootConfig} from '../core/config';\nimport {isValidTagName, parseTagNames} from '../utils/elements';\nimport {directoryContains, isDirectory, isJsFile} from '../utils/fsutils';\n\ninterface ElementSourceFile {\n /** Full file path. */\n filePath: string;\n /** Path relative to the root project directory. */\n relPath: string;\n}\n\n/**\n * Dependency graph for element files to capture which other elements are used\n * by any particular element.\n */\nexport class ElementGraph {\n /**\n * Element tagName => sourceFile.\n */\n readonly sourceFiles: {[tagName: string]: ElementSourceFile} = {};\n\n /**\n * Element tagName => set of element tagName dependencies.\n */\n private deps: Record<string, string[]> = {};\n\n constructor(sourceFiles: {[tagName: string]: ElementSourceFile}) {\n this.sourceFiles = sourceFiles;\n }\n\n toJson() {\n for (const tagName in this.sourceFiles) {\n this.deps[tagName] ??= this.parseDepsFromSource(tagName);\n }\n return {\n sourceFiles: this.sourceFiles,\n deps: this.deps,\n };\n }\n\n static fromJson(data: {deps: any; sourceFiles: any}) {\n const graph = new ElementGraph(data.sourceFiles);\n graph.deps = data.deps;\n return graph;\n }\n\n getDeps(tagName: string, visited?: Set<string>): string[] {\n visited ??= new Set();\n if (visited.has(tagName)) {\n return [];\n }\n\n visited.add(tagName);\n this.deps[tagName] ??= this.parseDepsFromSource(tagName);\n\n const deps = new Set(this.deps[tagName]);\n for (const depTagName of this.deps[tagName]) {\n for (const childDep of this.getDeps(depTagName, visited)) {\n deps.add(childDep);\n }\n }\n return Array.from(deps);\n }\n\n /**\n * Parses an element's source file for usage of other custom elements.\n */\n private parseDepsFromSource(tagName: string): string[] {\n const srcFile = this.sourceFiles[tagName];\n if (!srcFile) {\n throw new Error(`could not find file path for tagName <${tagName}>`);\n }\n const src = fs.readFileSync(srcFile.filePath, 'utf-8');\n const tagNames = parseTagNames(src);\n const deps = new Set<string>();\n for (const depTagName of tagNames) {\n if (depTagName !== tagName && depTagName in this.sourceFiles) {\n deps.add(depTagName);\n }\n }\n return Array.from(deps);\n }\n}\n\n/**\n * Returns a map of all the element file definitions in the project.\n */\nexport async function getElements(\n rootConfig: RootConfig\n): Promise<ElementGraph> {\n const rootDir = rootConfig.rootDir;\n\n const elementsDirs = getElementsDirs(rootConfig);\n const excludePatterns = rootConfig.elements?.exclude || [];\n const excludeElement = (moduleId: string) => {\n return excludePatterns.some((pattern) => Boolean(moduleId.match(pattern)));\n };\n\n const elementFilePaths: {[tagName: string]: ElementSourceFile} = {};\n for (const dirPath of elementsDirs) {\n if (await isDirectory(dirPath)) {\n const files = await glob('**/*', {cwd: dirPath});\n files.forEach((file) => {\n const parts = path.parse(file);\n if (isJsFile(parts.base) && isValidTagName(parts.name)) {\n const tagName = parts.name;\n const filePath = path.join(dirPath, file);\n const relPath = path.relative(rootDir, filePath);\n if (!excludeElement(relPath)) {\n elementFilePaths[tagName] = {filePath, relPath};\n }\n }\n });\n }\n }\n\n const graph = new ElementGraph(elementFilePaths);\n return graph;\n}\n\n/**\n * Get all element dirs.\n */\nexport function getElementsDirs(rootConfig: RootConfig) {\n const rootDir = rootConfig.rootDir;\n const workspaceRoot = searchForWorkspaceRoot(rootDir);\n\n const elementsDirs = [path.join(rootDir, 'elements')];\n const elementsInclude = rootConfig.elements?.include || [];\n\n for (const dirPath of elementsInclude) {\n const elementsDir = path.resolve(rootDir, dirPath);\n if (!directoryContains(rootDir, elementsDir)) {\n throw new Error(\n `the elements dir (${dirPath}) should be within the project's workspace (${workspaceRoot})`\n );\n }\n elementsDirs.push(elementsDir);\n }\n\n return elementsDirs;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport {Manifest} from 'vite';\n\nimport {RootConfig} from '../../core/config';\nimport {ElementGraph} from '../../node/element-graph';\nimport {isJsFile} from '../../utils/fsutils';\n\nimport {Asset, AssetMap} from './asset-map';\n\nexport type BuildAssetManifest = Record<\n string,\n {\n src: string;\n assetUrl: string;\n importedModules: string[];\n importedCss: string[];\n isElement: boolean;\n }\n>;\n\nexport class BuildAssetMap implements AssetMap {\n private rootConfig: RootConfig;\n private srcToAsset: Map<string, BuildAsset>;\n\n constructor(rootConfig: RootConfig) {\n this.rootConfig = rootConfig;\n this.srcToAsset = new Map();\n }\n\n async get(src: string): Promise<Asset | null> {\n const asset = this.srcToAsset.get(src);\n if (asset) {\n return asset;\n }\n // Try resolving the realpath of the asset, following symlinks.\n const realSrc = realPathRelativeTo(this.rootConfig.rootDir, src);\n if (realSrc !== src) {\n const asset = this.srcToAsset.get(realSrc);\n if (asset) {\n return asset;\n }\n }\n console.log(`could not find build asset: ${src}`);\n return null;\n }\n\n private add(asset: BuildAsset) {\n this.srcToAsset.set(asset.src, asset);\n }\n\n toJson(): BuildAssetManifest {\n const result: BuildAssetManifest = {};\n for (const src of this.srcToAsset.keys()) {\n result[src] = this.srcToAsset.get(src)!.toJson();\n }\n return result;\n }\n\n static fromViteManifest(\n rootConfig: RootConfig,\n clientManifest: Manifest,\n elementsGraph: ElementGraph\n ) {\n const assetMap = new BuildAssetMap(rootConfig);\n\n const elementFiles = new Set();\n Object.values(elementsGraph.sourceFiles).forEach((elementSource) => {\n elementFiles.add(elementSource.relPath);\n // Vite will resolve symlinks, so we need to follow the src and add the\n // realpath to the element files.\n const realSrc = realPathRelativeTo(\n rootConfig.rootDir,\n elementSource.relPath\n );\n if (realSrc !== elementSource.filePath) {\n elementFiles.add(realSrc);\n }\n });\n\n Object.keys(clientManifest).forEach((manifestKey) => {\n const src = manifestKey;\n const manifestChunk = clientManifest[manifestKey];\n const isElement = elementFiles.has(src);\n // NOTES(stevenle): routes/ files are included in the manifest so for\n // their CSS deps, but do not have an asset URL.\n const assetUrl =\n src.startsWith('routes/') && isJsFile(src)\n ? ''\n : `/${manifestChunk.file}`;\n const assetData = {\n src: src,\n assetUrl: assetUrl,\n importedModules: manifestChunk.imports || [],\n importedCss: (manifestChunk.css || []).map((relPath) => `/${relPath}`),\n isElement: isElement,\n };\n assetMap.add(new BuildAsset(assetMap, assetData));\n });\n\n return assetMap;\n }\n\n static fromRootManifest(\n rootConfig: RootConfig,\n rootManifest: BuildAssetManifest\n ) {\n const assetMap = new BuildAssetMap(rootConfig);\n Object.keys(rootManifest).forEach((moduleId) => {\n const assetData = rootManifest[moduleId];\n assetMap.add(new BuildAsset(assetMap, assetData));\n });\n return assetMap;\n }\n}\n\n/**\n * Returns the realpath of a src file, relative to the rootDir.\n */\nfunction realPathRelativeTo(rootDir: string, src: string) {\n const fullPath = path.resolve(rootDir, src);\n if (!fs.existsSync(fullPath)) {\n return src;\n }\n const realpath = fs.realpathSync(path.resolve(rootDir, src));\n return path.relative(rootDir, realpath);\n}\n\nexport class BuildAsset {\n src: string;\n assetUrl: string;\n private assetMap: BuildAssetMap;\n private importedModules: string[];\n private importedCss: string[];\n isElement: boolean;\n\n constructor(\n assetMap: BuildAssetMap,\n assetData: {\n src: string;\n assetUrl: string;\n importedModules: string[];\n importedCss: string[];\n isElement: boolean;\n }\n ) {\n this.assetMap = assetMap;\n this.src = assetData.src;\n this.assetUrl = assetData.assetUrl;\n this.importedModules = assetData.importedModules;\n this.importedCss = assetData.importedCss;\n this.isElement = assetData.isElement;\n }\n\n async getCssDeps(): Promise<string[]> {\n const visited = new Set<string>();\n const deps = new Set<string>();\n await this.collectCss(this, deps, visited);\n return Array.from(deps);\n }\n\n async getJsDeps(): Promise<string[]> {\n const visited = new Set<string>();\n const deps = new Set<string>();\n await this.collectJs(this, deps, visited);\n return Array.from(deps);\n }\n\n private async collectJs(\n asset: BuildAsset | null,\n urls: Set<string>,\n visited: Set<string>\n ) {\n if (!asset) {\n return;\n }\n if (!asset.src) {\n return;\n }\n if (visited.has(asset.src)) {\n return;\n }\n visited.add(asset.src);\n if (asset.isElement) {\n urls.add(asset.assetUrl);\n }\n await Promise.all(\n asset.importedModules.map(async (src) => {\n const importedAsset = (await this.assetMap.get(src)) as BuildAsset;\n this.collectJs(importedAsset, urls, visited);\n })\n );\n }\n\n private async collectCss(\n asset: BuildAsset | null,\n urls: Set<string>,\n visited: Set<string>\n ) {\n if (!asset) {\n return;\n }\n if (!asset.src) {\n return;\n }\n if (visited.has(asset.src)) {\n return;\n }\n visited.add(asset.src);\n if (asset.importedCss) {\n asset.importedCss.forEach((cssUrl) => urls.add(cssUrl));\n }\n await Promise.all(\n asset.importedModules.map(async (moduleId) => {\n const importedAsset = (await this.assetMap.get(moduleId)) as BuildAsset;\n this.collectCss(importedAsset, urls, visited);\n })\n );\n }\n\n toJson() {\n return {\n src: this.src,\n assetUrl: this.assetUrl,\n importedModules: this.importedModules,\n importedCss: this.importedCss,\n isElement: this.isElement,\n };\n }\n}\n","export async function batchAsyncCalls<T, U>(\n data: T[],\n batchSize: number,\n asyncFunction: (item: T) => Promise<U>\n): Promise<U[]> {\n const result: U[] = [];\n const batches = Math.ceil(data.length / batchSize);\n for (let i = 0; i < batches; i++) {\n const batch = data.slice(i * batchSize, (i + 1) * batchSize);\n const batchResults = await Promise.all(batch.map(asyncFunction));\n result.push(...batchResults);\n }\n return result;\n}\n","import path from 'node:path';\nimport {fileURLToPath} from 'node:url';\n\nimport cookieParser from 'cookie-parser';\nimport {default as express} from 'express';\nimport {dim} from 'kleur/colors';\nimport sirv from 'sirv';\nimport glob from 'tiny-glob';\n\nimport {RootConfig} from '../../core/config.js';\nimport {configureServerPlugins} from '../../core/plugin.js';\nimport {Server, Request, Response, NextFunction} from '../../core/types.js';\nimport {hooksMiddleware} from '../../middleware/hooks.js';\nimport {\n rootProjectMiddleware,\n trailingSlashMiddleware,\n} from '../../middleware/middleware.js';\nimport {sessionMiddleware} from '../../middleware/session.js';\nimport {getElements, getElementsDirs} from '../../node/element-graph.js';\nimport {loadRootConfig} from '../../node/load-config.js';\nimport {createViteServer} from '../../node/vite.js';\nimport {DevServerAssetMap} from '../../render/asset-map/dev-asset-map.js';\nimport {dirExists, isDirectory, isJsFile} from '../../utils/fsutils.js';\nimport {findOpenPort} from '../../utils/ports.js';\nimport {randString} from '../../utils/rand.js';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\ntype RenderModule = typeof import('../../render/render.js');\n\nexport interface DevOptions {\n host?: string;\n}\n\nexport async function dev(rootProjectDir?: string, options?: DevOptions) {\n process.env.NODE_ENV = 'development';\n const rootDir = path.resolve(rootProjectDir || process.cwd());\n const defaultPort = parseInt(process.env.PORT || '4007');\n const host = options?.host || 'localhost';\n const port = await findOpenPort(defaultPort, defaultPort + 10);\n console.log();\n console.log(`${dim('┃')} project: ${rootDir}`);\n console.log(`${dim('┃')} server: http://${host}:${port}`);\n console.log(`${dim('┃')} mode: development`);\n console.log();\n const server = await createDevServer({rootDir, port});\n server.listen(port, host);\n}\n\nexport async function createDevServer(options?: {\n rootDir?: string;\n port?: number;\n}): Promise<Server> {\n const rootDir = path.resolve(options?.rootDir || process.cwd());\n const rootConfig = await loadRootConfig(rootDir, {command: 'dev'});\n const port = options?.port;\n\n const server: Server = express();\n server.disable('x-powered-by');\n\n // Inject req context vars.\n server.use(rootProjectMiddleware({rootConfig}));\n server.use(await viteServerMiddleware({rootConfig, port}));\n server.use(hooksMiddleware());\n\n // Session middleware for handling session cookies.\n const sessionCookieSecret =\n rootConfig.server?.sessionCookieSecret || randString(36);\n server.use(cookieParser(sessionCookieSecret));\n server.use(sessionMiddleware());\n\n const plugins = rootConfig.plugins || [];\n await configureServerPlugins(\n server,\n async () => {\n // Add user-configured middlewares from `root.config.ts`.\n const userMiddlewares = rootConfig.server?.middlewares || [];\n for (const middleware of userMiddlewares) {\n server.use(middleware);\n }\n\n // Add static file middleware.\n const publicDir = path.join(rootDir, 'public');\n if (await dirExists(publicDir)) {\n server.use(sirv(publicDir, {dev: false}));\n }\n\n // Add the root.js dev server middlewares.\n server.use(trailingSlashMiddleware({rootConfig}));\n server.use(rootDevServerMiddleware());\n server.use(rootDevServer404Middleware());\n server.use(rootDevServer500Middleware());\n },\n plugins,\n {type: 'dev', rootConfig}\n );\n\n return server;\n}\n\n/**\n * Middleware that initializes a vite server and injects it into the request\n * context.\n */\nasync function viteServerMiddleware(options: {\n rootConfig: RootConfig;\n port?: number;\n}) {\n const rootConfig = options.rootConfig;\n const rootDir = rootConfig.rootDir;\n\n let elementGraph = await getElements(rootConfig);\n const elements = Object.values(elementGraph.sourceFiles).map((sourceFile) => {\n return sourceFile.relPath;\n });\n\n const bundleScripts: string[] = [];\n if (await isDirectory(path.join(rootDir, 'bundles'))) {\n const bundleFiles = await glob('bundles/*', {cwd: rootDir});\n bundleFiles.forEach((file) => {\n const parts = path.parse(file);\n if (isJsFile(parts.base)) {\n bundleScripts.push(file);\n }\n });\n }\n\n const optimizeDeps = [...elements, ...bundleScripts];\n const viteServer = await createViteServer(rootConfig, {\n port: options.port,\n optimizeDeps: optimizeDeps,\n });\n\n // Watch for file changes and re-generate the elements graph if any elements\n // are added or deleted.\n function isInElementsDir(changedFilePath: string) {\n const filePath = path.resolve(changedFilePath);\n const elementsDirs = getElementsDirs(rootConfig);\n return elementsDirs.some((dirPath) => filePath.startsWith(dirPath));\n }\n viteServer.watcher.on('add', async (filePath: string) => {\n if (isInElementsDir(filePath)) {\n // Re-generate the elements graph.\n elementGraph = await getElements(rootConfig);\n console.log(`element added: ${filePath}`);\n }\n });\n viteServer.watcher.on('unlink', async (filePath: string) => {\n if (isInElementsDir(filePath)) {\n // Re-generate the elements graph.\n elementGraph = await getElements(rootConfig);\n console.log(`element deleted: ${filePath}`);\n }\n });\n\n return async (req: Request, res: Response, next: NextFunction) => {\n try {\n // Add the viteServer to the req.\n req.viteServer = viteServer;\n // Dynamically import the render.js module using vite's SSR import loader.\n const renderModulePath = path.resolve(__dirname, './render.js');\n const render = (await viteServer.ssrLoadModule(\n renderModulePath\n )) as RenderModule;\n // Create a dev asset map using Vite dev server's module graph.\n const assetMap = new DevServerAssetMap(\n rootConfig,\n viteServer.moduleGraph\n );\n // Add a renderer object to the req for plugins and other middleware to\n // use.\n req.renderer = new render.Renderer(rootConfig, {assetMap, elementGraph});\n // Run the viteServer middlewares to handle vite-specific endpoints.\n viteServer.middlewares(req, res, next);\n } catch (e) {\n next(e);\n }\n };\n}\n\nfunction rootDevServerMiddleware() {\n return async (req: Request, res: Response, next: NextFunction) => {\n const renderer = req.renderer!;\n const viteServer = req.viteServer!;\n try {\n await renderer.handle(req, res, next);\n } catch (err) {\n // If an error is caught, let Vite fix the stack trace so it maps back to\n // your actual source code.\n viteServer.ssrFixStacktrace(err);\n next(err);\n }\n };\n}\n\nfunction rootDevServer404Middleware() {\n return async (req: Request, res: Response) => {\n console.error(`❓ 404 ${req.originalUrl}`);\n if (req.renderer) {\n const url = req.path;\n const ext = path.extname(url);\n if (!ext) {\n const renderer = req.renderer;\n const data = await renderer.renderDevServer404(req);\n const html = data.html || '';\n res.status(404).set({'Content-Type': 'text/html'}).end(html);\n return;\n }\n }\n res.status(404).set({'Content-Type': 'text/plain'}).end('404');\n };\n}\n\nfunction rootDevServer500Middleware() {\n return async (err: any, req: Request, res: Response, next: NextFunction) => {\n console.error(`❗ 500 ${req.originalUrl}`);\n console.error(String(err.stack || err));\n if (req.renderer) {\n const url = req.path;\n const ext = path.extname(url);\n if (!ext) {\n const renderer = req.renderer;\n const data = await renderer.renderDevServer500(req, err);\n const html = data.html || '';\n res.status(500).set({'Content-Type': 'text/html'}).end(html);\n return;\n }\n }\n next(err);\n };\n}\n","import {Request, Response, NextFunction} from '../core/types';\n\nexport function hooksMiddleware() {\n return (req: Request, res: Response, next: NextFunction) => {\n req.hooks = new Hooks();\n next();\n };\n}\n\nexport type HooksCallbackFn = (...args: any[]) => any;\n\nexport class Hooks {\n private callbacks: {[name: string]: HooksCallbackFn[]} = {};\n\n add(name: string, cb: (...args: any[]) => any) {\n this.callbacks[name] ??= [];\n this.callbacks[name].push(cb);\n }\n\n trigger(name: string, ...args: any[]) {\n const callbacks = this.callbacks[name] || [];\n callbacks.forEach((cb) => {\n cb(...args);\n });\n }\n}\n","import path from 'node:path';\n\nimport {ModuleGraph, ModuleNode, searchForWorkspaceRoot} from 'vite';\n\nimport {RootConfig} from '../../core/config';\nimport {directoryContains} from '../../utils/fsutils';\n\nimport {Asset, AssetMap} from './asset-map';\n\nexport class DevServerAssetMap implements AssetMap {\n private rootConfig: RootConfig;\n private moduleGraph: ModuleGraph;\n\n constructor(rootConfig: RootConfig, moduleGraph: ModuleGraph) {\n this.rootConfig = rootConfig;\n this.moduleGraph = moduleGraph;\n }\n\n async get(src: string): Promise<Asset | null> {\n const file = path.resolve(this.rootConfig.rootDir, src);\n\n const viteModules = this.moduleGraph.getModulesByFile(file);\n if (viteModules && viteModules.size > 0) {\n const [viteModule] = viteModules;\n return new DevServerAsset(src, {\n assetMap: this,\n viteModule: viteModule,\n });\n }\n\n // On dev, in some cases the module doesn't make it into the module graph\n // so return a generic asset.\n if (file.startsWith(this.rootConfig.rootDir)) {\n const assetUrl = file.slice(this.rootConfig.rootDir.length);\n return {\n src: src,\n assetUrl: assetUrl,\n getCssDeps: async () => [],\n getJsDeps: async () => [assetUrl],\n };\n }\n const workspaceRoot = searchForWorkspaceRoot(this.rootConfig.rootDir);\n if (await directoryContains(workspaceRoot, file)) {\n const assetUrl = `/@fs/${file}`;\n return {\n src: src,\n assetUrl: assetUrl,\n getCssDeps: async () => [],\n getJsDeps: async () => [assetUrl],\n };\n }\n\n console.log(`could not find asset in asset map: ${src}`);\n return null;\n }\n\n filePathToSrc(file: string) {\n return path.relative(this.rootConfig.rootDir, file);\n }\n}\n\nexport class DevServerAsset implements Asset {\n src: string;\n moduleId: string;\n assetUrl: string;\n private assetMap: DevServerAssetMap;\n private viteModule: ModuleNode;\n\n constructor(\n src: string,\n options: {\n assetMap: DevServerAssetMap;\n viteModule: ModuleNode;\n }\n ) {\n this.src = src;\n this.assetMap = options.assetMap;\n this.viteModule = options.viteModule;\n this.moduleId = this.viteModule.id!;\n this.assetUrl = this.viteModule.url;\n }\n\n async getCssDeps(): Promise<string[]> {\n const visited = new Set<string>();\n const deps = new Set<string>();\n this.collectCss(this, deps, visited);\n return Array.from(deps);\n }\n\n async getJsDeps(): Promise<string[]> {\n const visited = new Set<string>();\n const deps = new Set<string>();\n this.collectJs(this, deps, visited);\n return Array.from(deps);\n }\n\n getImportedModules() {\n return this.viteModule.importedModules;\n }\n\n private collectJs(\n asset: DevServerAsset | null,\n urls: Set<string>,\n visited: Set<string>\n ) {\n if (!asset) {\n return;\n }\n if (!asset.moduleId) {\n return;\n }\n if (visited.has(asset.moduleId)) {\n return;\n }\n visited.add(asset.moduleId);\n const parts = path.parse(asset.assetUrl);\n if (\n ['.js', '.jsx', '.ts', '.tsx'].includes(parts.ext) &&\n asset.moduleId.includes('/elements/')\n ) {\n urls.add(asset.assetUrl);\n }\n asset.getImportedModules().forEach((viteModule) => {\n if (viteModule.file) {\n const src = this.assetMap.filePathToSrc(viteModule.file);\n const importedAsset = new DevServerAsset(src, {\n assetMap: this.assetMap,\n viteModule: viteModule,\n });\n this.collectJs(importedAsset, urls, visited);\n }\n });\n }\n\n private collectCss(\n asset: DevServerAsset | null,\n urls: Set<string>,\n visited: Set<string>\n ) {\n if (!asset) {\n return;\n }\n if (!asset.assetUrl) {\n return;\n }\n if (visited.has(asset.assetUrl)) {\n return;\n }\n visited.add(asset.assetUrl);\n if (asset.src.endsWith('.scss')) {\n const parts = path.parse(asset.src);\n if (!parts.name.startsWith('_')) {\n urls.add(asset.assetUrl);\n }\n }\n asset.getImportedModules().forEach((viteModule) => {\n if (viteModule.file) {\n const src = this.assetMap.filePathToSrc(viteModule.file);\n const importedAsset = new DevServerAsset(src, {\n assetMap: this.assetMap,\n viteModule: viteModule,\n });\n this.collectCss(importedAsset, urls, visited);\n }\n });\n }\n}\n","import {createServer} from 'node:net';\n\n/**\n * Checks whether a port is open.\n */\nexport function isPortOpen(port: number): Promise<boolean> {\n return new Promise((resolve, reject) => {\n const server = createServer();\n server.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EADDRINUSE') {\n resolve(false);\n return;\n }\n reject(err);\n });\n server.on('close', () => {\n resolve(true);\n });\n server.listen(port, () => {\n server.close((err) => {\n if (err) {\n console.log(`error closing server: ${err}`);\n reject(err);\n }\n });\n });\n });\n}\n\n/**\n * Finds the first open port between two values.\n */\nexport async function findOpenPort(min: number, max: number): Promise<number> {\n let port = min;\n while (port <= max) {\n const isOpen = await isPortOpen(port);\n if (isOpen) {\n return port;\n }\n port += 1;\n }\n throw new Error(`no ports open between ${min} and ${max}`);\n}\n","export function randString(len: number): string {\n const result = [];\n const chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n for (let i = 0; i < len; i++) {\n const rand = Math.floor(Math.random() * chars.length);\n result.push(chars.charAt(rand));\n }\n return result.join('');\n}\n","import path from 'node:path';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport {default as express} from 'express';\nimport {dim} from 'kleur/colors';\nimport sirv from 'sirv';\n\nimport {RootConfig} from '../../core/config';\nimport {configureServerPlugins} from '../../core/plugin';\nimport {Request, Response, NextFunction, Server} from '../../core/types.js';\nimport {hooksMiddleware} from '../../middleware/hooks';\nimport {\n rootProjectMiddleware,\n trailingSlashMiddleware,\n} from '../../middleware/middleware';\nimport {sessionMiddleware} from '../../middleware/session';\nimport {ElementGraph} from '../../node/element-graph.js';\nimport {loadRootConfig} from '../../node/load-config';\nimport {\n BuildAssetManifest,\n BuildAssetMap,\n} from '../../render/asset-map/build-asset-map';\nimport {fileExists, loadJson} from '../../utils/fsutils';\nimport {randString} from '../../utils/rand';\n\ntype RenderModule = typeof import('../../render/render.js');\n\nexport interface PreviewOptions {\n host?: string;\n}\n\nexport async function preview(\n rootProjectDir?: string,\n options?: PreviewOptions\n) {\n // TODO(stevenle): figure out standard practice for NODE_ENV when using the\n // preview command.\n process.env.NODE_ENV = 'development';\n const rootDir = path.resolve(rootProjectDir || process.cwd());\n const server = await createPreviewServer({rootDir});\n const port = parseInt(process.env.PORT || '4007');\n const host = options?.host || 'localhost';\n console.log();\n console.log(`${dim('┃')} project: ${rootDir}`);\n console.log(`${dim('┃')} server: http://${host}:${port}`);\n console.log(`${dim('┃')} mode: preview`);\n console.log();\n server.listen(port, host);\n}\n\nexport async function createPreviewServer(options: {\n rootDir: string;\n}): Promise<Server> {\n const rootDir = options.rootDir;\n const rootConfig = await loadRootConfig(rootDir, {command: 'preview'});\n const distDir = path.join(rootDir, 'dist');\n\n const server: Server = express();\n server.disable('x-powered-by');\n server.use(compression());\n\n // Inject request context vars.\n server.use(rootProjectMiddleware({rootConfig}));\n server.use(await rootPreviewRendererMiddleware({rootConfig, distDir}));\n server.use(hooksMiddleware());\n\n // Session middleware for handling session cookies.\n const sessionCookieSecret =\n rootConfig.server?.sessionCookieSecret || randString(36);\n server.use(cookieParser(sessionCookieSecret));\n server.use(sessionMiddleware());\n\n const plugins = rootConfig.plugins || [];\n configureServerPlugins(\n server,\n async () => {\n // Add user-configured middlewares from `root.config.ts`.\n const userMiddlewares = rootConfig.server?.middlewares || [];\n userMiddlewares.forEach((middleware) => {\n server.use(middleware);\n });\n\n // Add static file middleware.\n const publicDir = path.join(distDir, 'html');\n server.use(sirv(publicDir, {dev: false}));\n\n // Add the root.js preview server middlewares.\n server.use(trailingSlashMiddleware({rootConfig}));\n server.use(rootPreviewServerMiddleware());\n\n // Add error handlers.\n server.use(rootPreviewServer404Middleware());\n server.use(rootPreviewServer500Middleware());\n },\n plugins,\n {type: 'preview', rootConfig}\n );\n return server;\n}\n\n/**\n * Injects a renderer into the request.\n */\nasync function rootPreviewRendererMiddleware(options: {\n rootConfig: RootConfig;\n distDir: string;\n}) {\n const {distDir, rootConfig} = options;\n const render: RenderModule = await import(\n path.join(distDir, 'server/render.js')\n );\n const manifestPath = path.join(distDir, 'client/root-manifest.json');\n if (!(await fileExists(manifestPath))) {\n throw new Error(\n `could not find ${manifestPath}. run \\`root build\\` before \\`root preview\\`.`\n );\n }\n const elementGraphJsonPath = path.join(\n distDir,\n 'client/root-element-graph.json'\n );\n if (!(await fileExists(elementGraphJsonPath))) {\n throw new Error(\n `could not find ${elementGraphJsonPath}. run \\`root build\\` before \\`root start\\`.`\n );\n }\n const rootManifest = await loadJson<BuildAssetManifest>(manifestPath);\n const assetMap = BuildAssetMap.fromRootManifest(rootConfig, rootManifest);\n const elementGraphJson = await loadJson<any>(elementGraphJsonPath);\n const elementGraph = ElementGraph.fromJson(elementGraphJson);\n const renderer = new render.Renderer(rootConfig, {assetMap, elementGraph});\n return async (req: Request, _: Response, next: NextFunction) => {\n req.renderer = renderer;\n next();\n };\n}\n\n/**\n * Preview server request handler.\n */\nfunction rootPreviewServerMiddleware() {\n return async (req: Request, res: Response, next: NextFunction) => {\n const renderer = req.renderer!;\n try {\n await renderer.handle(req, res, next);\n } catch (e) {\n try {\n console.error(`error rendering ${req.originalUrl}`);\n console.error(e.stack || e);\n const {html} = await renderer.renderError(e);\n res.status(500).set({'Content-Type': 'text/html'}).end(html);\n } catch (e2) {\n console.error('failed to render custom error');\n console.error(e2);\n next(e);\n }\n }\n };\n}\n\nfunction rootPreviewServer404Middleware() {\n return async (req: Request, res: Response) => {\n console.error(`❓ 404 ${req.originalUrl}`);\n if (req.renderer) {\n const url = req.path;\n const ext = path.extname(url);\n if (!ext) {\n const renderer = req.renderer;\n const data = await renderer.render404({currentPath: url});\n const html = data.html || '';\n res.status(404).set({'Content-Type': 'text/html'}).end(html);\n return;\n }\n }\n res.status(404).set({'Content-Type': 'text/plain'}).end('404');\n };\n}\n\nfunction rootPreviewServer500Middleware() {\n return async (err: any, req: Request, res: Response, next: NextFunction) => {\n console.error(`❗ 500 ${req.originalUrl}`);\n console.error(String(err.stack || err));\n if (req.renderer) {\n const url = req.path;\n const ext = path.extname(url);\n if (!ext) {\n const renderer = req.renderer;\n const data = await renderer.renderDevServer500(req, err);\n const html = data.html || '';\n res.status(500).set({'Content-Type': 'text/html'}).end(html);\n return;\n }\n }\n next(err);\n };\n}\n","import path from 'node:path';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport {default as express} from 'express';\nimport {dim} from 'kleur/colors';\nimport sirv from 'sirv';\n\nimport {RootConfig} from '../../core/config';\nimport {configureServerPlugins} from '../../core/plugin';\nimport {Request, Response, NextFunction, Server} from '../../core/types.js';\nimport {hooksMiddleware} from '../../middleware/hooks';\nimport {\n rootProjectMiddleware,\n trailingSlashMiddleware,\n} from '../../middleware/middleware';\nimport {sessionMiddleware} from '../../middleware/session';\nimport {ElementGraph} from '../../node/element-graph';\nimport {loadRootConfig} from '../../node/load-config';\nimport {\n BuildAssetManifest,\n BuildAssetMap,\n} from '../../render/asset-map/build-asset-map';\nimport {fileExists, loadJson} from '../../utils/fsutils';\nimport {randString} from '../../utils/rand';\n\ntype RenderModule = typeof import('../../render/render.js');\n\nexport interface StartOptions {\n host?: string;\n}\n\nexport async function start(rootProjectDir?: string, options?: StartOptions) {\n process.env.NODE_ENV = 'production';\n const rootDir = path.resolve(rootProjectDir || process.cwd());\n const server = await createProdServer({rootDir});\n const port = parseInt(process.env.PORT || '4007');\n const host = options?.host || 'localhost';\n console.log();\n console.log(`${dim('┃')} project: ${rootDir}`);\n console.log(`${dim('┃')} server: http://${host}:${port}`);\n console.log(`${dim('┃')} mode: production`);\n console.log();\n server.listen(port, host);\n}\n\nexport async function createProdServer(options: {\n rootDir: string;\n}): Promise<Server> {\n const rootDir = options.rootDir;\n const rootConfig = await loadRootConfig(rootDir, {command: 'start'});\n const distDir = path.join(rootDir, 'dist');\n\n const server: Server = express();\n server.disable('x-powered-by');\n server.use(compression());\n\n // Inject request context vars.\n server.use(rootProjectMiddleware({rootConfig}));\n server.use(await rootProdRendererMiddleware({rootConfig, distDir}));\n server.use(hooksMiddleware());\n\n // Session middleware for handling session cookies.\n const sessionCookieSecret =\n rootConfig.server?.sessionCookieSecret || randString(36);\n server.use(cookieParser(sessionCookieSecret));\n server.use(sessionMiddleware());\n\n const plugins = rootConfig.plugins || [];\n configureServerPlugins(\n server,\n async () => {\n // Add user-configured middlewares from `root.config.ts`.\n const userMiddlewares = rootConfig.server?.middlewares || [];\n userMiddlewares.forEach((middleware) => {\n server.use(middleware);\n });\n\n // Add static file middleware.\n const publicDir = path.join(distDir, 'html');\n server.use(sirv(publicDir, {dev: false}));\n\n // Add the root.js preview server middlewares.\n server.use(trailingSlashMiddleware({rootConfig}));\n server.use(rootProdServerMiddleware());\n\n // Add error handlers.\n server.use(rootProdServer404Middleware());\n server.use(rootProdServer500Middleware());\n },\n plugins,\n {type: 'prod', rootConfig}\n );\n return server;\n}\n\n/**\n * Injects a renderer into the request.\n */\nasync function rootProdRendererMiddleware(options: {\n rootConfig: RootConfig;\n distDir: string;\n}) {\n const {distDir, rootConfig} = options;\n const render: RenderModule = await import(\n path.join(distDir, 'server/render.js')\n );\n const manifestPath = path.join(distDir, 'client/root-manifest.json');\n if (!(await fileExists(manifestPath))) {\n throw new Error(\n `could not find ${manifestPath}. run \\`root build\\` before \\`root start\\`.`\n );\n }\n const elementGraphJsonPath = path.join(\n distDir,\n 'client/root-element-graph.json'\n );\n if (!(await fileExists(elementGraphJsonPath))) {\n throw new Error(\n `could not find ${elementGraphJsonPath}. run \\`root build\\` before \\`root start\\`.`\n );\n }\n const rootManifest = await loadJson<BuildAssetManifest>(manifestPath);\n const assetMap = BuildAssetMap.fromRootManifest(rootConfig, rootManifest);\n const elementGraphJson = await loadJson<any>(elementGraphJsonPath);\n const elementGraph = ElementGraph.fromJson(elementGraphJson);\n const renderer = new render.Renderer(rootConfig, {assetMap, elementGraph});\n return async (req: Request, _: Response, next: NextFunction) => {\n req.renderer = renderer;\n next();\n };\n}\n\n/**\n * Prod server request handler.\n */\nfunction rootProdServerMiddleware() {\n return async (req: Request, res: Response, next: NextFunction) => {\n const renderer = req.renderer!;\n try {\n await renderer.handle(req, res, next);\n } catch (e) {\n try {\n console.error(`error rendering ${req.originalUrl}`);\n console.error(e.stack || e);\n const {html} = await renderer.renderError(e);\n res.status(500).set({'Content-Type': 'text/html'}).end(html);\n } catch (e2) {\n console.error('failed to render custom error');\n console.error(e2);\n next(e);\n }\n }\n };\n}\n\nfunction rootProdServer404Middleware() {\n return async (req: Request, res: Response) => {\n console.error(`❓ 404 ${req.originalUrl}`);\n if (req.renderer) {\n const url = req.path;\n const ext = path.extname(url);\n if (!ext) {\n const renderer = req.renderer;\n const data = await renderer.render404({currentPath: url});\n const html = data.html || '';\n res.status(404).set({'Content-Type': 'text/html'}).end(html);\n return;\n }\n }\n res.status(404).set({'Content-Type': 'text/plain'}).end('404');\n };\n}\n\nfunction rootProdServer500Middleware() {\n return async (err: any, req: Request, res: Response, next: NextFunction) => {\n console.error(`❗ 500 ${req.originalUrl}`);\n console.error(String(err.stack || err));\n if (req.renderer) {\n const url = req.path;\n const ext = path.extname(url);\n if (!ext) {\n const renderer = req.renderer;\n const data = await renderer.renderError(err);\n const html = data.html || '';\n res.status(500).set({'Content-Type': 'text/html'}).end(html);\n return;\n }\n }\n next(err);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAAOA,WAAU;AACjB,SAAQ,qBAAoB;AAE5B,OAAO,aAAa;AACpB,SAAQ,KAAK,YAAW;AACxB,OAAOC,WAAU;AACjB,SAAQ,SAAS,iBAAqD;;;ACPtE,OAAO,QAAQ;AACf,OAAO,UAAU;AAEjB,OAAO,UAAU;AACjB,SAAQ,8BAA6B;AAiB9B,IAAM,eAAN,MAAM,cAAa;AAAA,EAWxB,YAAY,aAAqD;AAPjE;AAAA;AAAA;AAAA,SAAS,cAAsD,CAAC;AAKhE;AAAA;AAAA;AAAA,SAAQ,OAAiC,CAAC;AAGxC,SAAK,cAAc;AAAA,EACrB;AAAA,EAEA,SAAS;AACP,eAAW,WAAW,KAAK,aAAa;AACtC,WAAK,KAAK,OAAO,MAAM,KAAK,oBAAoB,OAAO;AAAA,IACzD;AACA,WAAO;AAAA,MACL,aAAa,KAAK;AAAA,MAClB,MAAM,KAAK;AAAA,IACb;AAAA,EACF;AAAA,EAEA,OAAO,SAAS,MAAqC;AACnD,UAAM,QAAQ,IAAI,cAAa,KAAK,WAAW;AAC/C,UAAM,OAAO,KAAK;AAClB,WAAO;AAAA,EACT;AAAA,EAEA,QAAQ,SAAiB,SAAiC;AACxD,gBAAY,oBAAI,IAAI;AACpB,QAAI,QAAQ,IAAI,OAAO,GAAG;AACxB,aAAO,CAAC;AAAA,IACV;AAEA,YAAQ,IAAI,OAAO;AACnB,SAAK,KAAK,OAAO,MAAM,KAAK,oBAAoB,OAAO;AAEvD,UAAM,OAAO,IAAI,IAAI,KAAK,KAAK,OAAO,CAAC;AACvC,eAAW,cAAc,KAAK,KAAK,OAAO,GAAG;AAC3C,iBAAW,YAAY,KAAK,QAAQ,YAAY,OAAO,GAAG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SAAO,OAAO,KAAc,QAAkB;AAC5C,YAAQ,MAAM,cAAS,IAAI,WAAW,EAAE;AACxC,QAAI,IAAI,UAAU;AAChB,YAAM,MAAM,IAAI;AAChB,YAAM,MAAMA,MAAK,QAAQ,GAAG;AAC5B,UAAI,CAAC,KAAK;AACR,cAAM,WAAW,IAAI;AACrB,cAAM,OAAO,MAAM,SAAS,UAAU,EAAC,aAAa,IAAG,CAAC;AACxD,cAAM,OAAO,KAAK,QAAQ;AAC1B,YAAI,OAAO,GAAG,EAAE,IAAI,EAAC,gBAAgB,YAAW,CAAC,EAAE,IAAI,IAAI;AAC3D;AAAA,MACF;AAAA,IACF;AACA,QAAI,OAAO,GAAG,EAAE,IAAI,EAAC,gBAAgB,aAAY,CAAC,EAAE,IAAI,KAAK;AAAA,EAC/D;AACF;AAEA,SAAS,8BAA8B;AACrC,SAAO,OAAO,KAAU,KAAc,KAAe,SAAuB;AAC1E,YAAQ,MAAM,cAAS,IAAI,WAAW,EAAE;AACxC,YAAQ,MAAM,OAAO,IAAI,SAAS,GAAG,CAAC;AACtC,QAAI,IAAI,UAAU;AAChB,YAAM,MAAM,IAAI;AAChB,YAAM,MAAMA,MAAK,QAAQ,GAAG;AAC5B,UAAI,CAAC,KAAK;AACR,cAAM,WAAW,IAAI;AACrB,cAAM,OAAO,MAAM,SAAS,YAAY,GAAG;AAC3C,cAAM,OAAO,KAAK,QAAQ;AAC1B,YAAI,OAAO,GAAG,EAAE,IAAI,EAAC,gBAAgB,YAAW,CAAC,EAAE,IAAI,IAAI;AAC3D;AAAA,MACF;AAAA,IACF;AACA,SAAK,GAAG;AAAA,EACV;AACF;","names":["path","glob","fs","path","asset","path","fs","path","glob","fileSize","path","fileURLToPath","dim","glob","path","searchForWorkspaceRoot","path","searchForWorkspaceRoot","__dirname","path","fileURLToPath","dim","_a","glob","path","cookieParser","express","dim","sirv","path","dim","express","cookieParser","_a","sirv","path","compression","cookieParser","express","dim","sirv","path","dim","express","compression","cookieParser","_a","sirv"]}
|