@blinkk/root 1.0.0-alpha.2 → 1.0.0-alpha.21

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/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli/commands/dev.ts","../src/render/vite-plugin-root.ts","../src/render/asset-map/dev-asset-map.ts","../src/cli/load-config.ts","../src/render/html-minify.ts","../src/core/fsutils.ts","../src/cli/commands/build.ts","../src/render/asset-map/build-asset-map.ts","../src/cli/commands/start.ts"],"sourcesContent":["import path from 'node:path';\nimport {fileURLToPath} from 'node:url';\nimport {default as express, Request, Response, NextFunction} from 'express';\nimport {createServer as createViteServer} from 'vite';\nimport pluginRoot from '../../render/vite-plugin-root.js';\nimport {DevServerAssetMap} from '../../render/asset-map/dev-asset-map.js';\nimport {loadRootConfig} from '../load-config.js';\nimport {htmlMinify} from '../../render/html-minify.js';\nimport {Renderer} from '../../render/render.js';\nimport {isDirectory, isJsFile} from '../../core/fsutils.js';\nimport glob from 'tiny-glob';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nexport async function createServer(options?: {rootDir?: string}) {\n const app = express();\n\n app.use(express.static('public'));\n const middlewares = await getMiddlewares({rootDir: options?.rootDir});\n middlewares.forEach((middleware) => app.use(middleware));\n\n const port = parseInt(process.env.PORT || '4007');\n console.log('🌳 Root.js');\n console.log();\n console.log(`Started server: http://localhost:${port}`);\n app.listen(port);\n}\n\nexport async function getMiddlewares(options?: {rootDir?: string}) {\n const rootDir = options?.rootDir || process.cwd();\n const rootConfig = await loadRootConfig(rootDir);\n const viteConfig = rootConfig.vite || {};\n const renderModulePath = path.resolve(__dirname, './render.js');\n\n const pages: string[] = [];\n if (await isDirectory(path.join(rootDir, 'routes'))) {\n const pageFiles = await glob(path.join(rootDir, 'routes/**/*'));\n pageFiles.forEach((file) => {\n const parts = path.parse(file);\n if (!parts.name.startsWith('_') && isJsFile(parts.base)) {\n pages.push(file);\n }\n });\n }\n\n const elements: string[] = [];\n if (await isDirectory(path.join(rootDir, 'elements'))) {\n const elementFiles = await glob(path.join(rootDir, 'elements/**/*'));\n elementFiles.forEach((file) => {\n const parts = path.parse(file);\n if (isJsFile(parts.base)) {\n elements.push(file);\n }\n });\n }\n\n const bundleScripts: string[] = [];\n if (await isDirectory(path.join(rootDir, 'bundles'))) {\n const bundleFiles = await glob(path.join(rootDir, 'bundles/*'));\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 viteServer = await createViteServer({\n ...viteConfig,\n server: {middlewareMode: true},\n appType: 'custom',\n optimizeDeps: {\n include: [...pages, ...elements, ...bundleScripts],\n },\n ssr: {\n noExternal: ['@blinkk/root'],\n },\n esbuild: {\n jsx: 'automatic',\n jsxImportSource: 'preact',\n },\n plugins: [...(viteConfig.plugins || []), pluginRoot()],\n });\n\n const rootMiddleware = async (\n req: Request,\n res: Response,\n next: NextFunction\n ) => {\n const url = req.originalUrl;\n const render = await viteServer.ssrLoadModule(renderModulePath);\n const renderer = new render.Renderer(rootConfig) as Renderer;\n try {\n // Create a dev asset map using Vite dev server's module graph.\n const assetMap = new DevServerAssetMap(viteServer.moduleGraph);\n const data = await renderer.render(url, {\n assetMap: assetMap,\n });\n // Inject the Vite HMR client.\n const html = await htmlMinify(\n await viteServer.transformIndexHtml(url, data.html || '')\n );\n\n res.status(200).set({'Content-Type': 'text/html'}).end(html);\n } catch (e) {\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(e);\n try {\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 return [viteServer.middlewares, rootMiddleware];\n}\n\nexport function dev(rootDir?: string) {\n createServer({rootDir});\n}\n","import path from 'path';\nimport glob from 'tiny-glob';\nimport {ViteDevServer} from 'vite';\n\nconst ELEMENTS_REGEX = /h\\(\"(\\w[\\w-]+\\w)\"/g;\n\nexport interface RootPluginOptions {\n // Project directory.\n rootDir?: string;\n}\n\nexport function pluginRoot(options?: RootPluginOptions) {\n const rootDir = options?.rootDir || process.cwd();\n let config: any;\n let server: ViteDevServer;\n let elementMap: Record<string, string>;\n\n async function updateElementMap() {\n elementMap = {};\n const files = await glob('./elements/**/*', {cwd: rootDir});\n files.forEach((file) => {\n const parts = path.parse(file);\n if (isJsFile(parts.base)) {\n elementMap[parts.name] = `${rootDir}/${file}`;\n }\n });\n }\n\n async function getElementImport(tagName: string): Promise<string | null> {\n if (!elementMap) {\n await updateElementMap();\n }\n if (tagName in elementMap) {\n const filePath = elementMap[tagName];\n if (server && server.moduleGraph) {\n const moduleSet = server.moduleGraph.getModulesByFile(filePath);\n if (moduleSet && moduleSet.size > 0) {\n const module = moduleSet.values().next().value;\n return module.url;\n }\n }\n }\n return null;\n }\n\n return {\n name: 'vite-plugin-root',\n\n // TODO(stevenle): when the config is resolved, store a list of places to\n // find custom elements.\n configResolved(resolvedConfig: any) {\n config = resolvedConfig;\n },\n\n configureServer(_server: ViteDevServer) {\n server = _server;\n },\n\n async transform(src: string, id: string): Promise<any> {\n if (id.includes('/elements/') && isJsFile(id)) {\n const idParts = path.parse(id);\n const deps = new Set<string>();\n const elementsRe = ELEMENTS_REGEX;\n for (const match of src.matchAll(elementsRe)) {\n const tagName = match[1];\n // All custom elements should contain a dash.\n if (!tagName.includes('-')) {\n continue;\n }\n // Avoid circular deps.\n if (tagName === idParts.name) {\n continue;\n }\n deps.add(tagName);\n }\n const importUrls: string[] = [];\n await Promise.all(\n Array.from(deps).map(async (tagName) => {\n const importUrl = await getElementImport(tagName);\n if (importUrl) {\n importUrls.push(importUrl);\n }\n })\n );\n if (importUrls.length > 0) {\n const importLines = importUrls\n .map((url) => `import '${url}';`)\n .join('\\n');\n const code = `${src}\n\n// autogenerated by root:\n${importLines}\n`;\n return {code};\n }\n return null;\n }\n },\n };\n}\n\nfunction isJsFile(file: string): boolean {\n return !!file.match(/\\.(j|t)sx?$/);\n}\n\nexport default pluginRoot;\n","import path from 'node:path';\nimport {ModuleGraph, ModuleNode} from 'vite';\nimport {Asset, AssetMap} from './asset-map';\n\nexport class DevServerAssetMap implements AssetMap {\n private moduleGraph: ModuleGraph;\n\n constructor(moduleGraph: ModuleGraph) {\n this.moduleGraph = moduleGraph;\n }\n\n async get(moduleId: string): Promise<Asset | null> {\n const viteModule = await this.moduleGraph.getModuleByUrl(moduleId);\n if (!viteModule || !viteModule.id) {\n return null;\n }\n return new DevServerAsset(this, viteModule);\n }\n}\n\nexport class DevServerAsset implements Asset {\n moduleId: string;\n assetUrl: string;\n private assetMap: AssetMap;\n private viteModule: ModuleNode;\n\n constructor(assetMap: AssetMap, viteModule: ModuleNode) {\n this.assetMap = assetMap;\n this.viteModule = 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.id) {\n const importedAsset = new DevServerAsset(this.assetMap, viteModule);\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.moduleId.endsWith('.scss')) {\n const parts = path.parse(asset.assetUrl);\n if (!parts.name.startsWith('_')) {\n urls.add(asset.assetUrl);\n }\n }\n asset.getImportedModules().forEach((viteModule) => {\n if (viteModule.id) {\n const importedAsset = new DevServerAsset(this.assetMap, viteModule);\n this.collectCss(importedAsset, urls, visited);\n }\n });\n }\n}\n","import {bundleRequire} from 'bundle-require';\nimport JoyCon from 'joycon';\nimport {RootConfig} from '../core/config';\n\nexport async function loadRootConfig(rootDir: string): Promise<RootConfig> {\n const joycon = new JoyCon();\n const configPath = await joycon.resolve({\n cwd: rootDir,\n files: ['root.config.ts'],\n });\n if (configPath) {\n const configBundle = await bundleRequire({\n filepath: configPath,\n });\n return configBundle.mod.default || {};\n }\n return {};\n}\n","import {minify} from 'html-minifier-terser';\n\nexport async function htmlMinify(html: string): Promise<string> {\n const min = await minify(html, {\n collapseWhitespace: true,\n removeComments: true,\n preserveLineBreaks: true,\n });\n return min.trimStart();\n}\n","import {promises as fs} from 'node:fs';\nimport path from 'node:path';\nimport fsExtra from 'fs-extra';\n\nexport function isJsFile(file: string) {\n return !!file.match(/\\.(j|t)sx?$/);\n}\n\nexport async function writeFile(filePath: string, content: string) {\n const dirPath = path.dirname(filePath);\n await makeDir(dirPath);\n await fs.writeFile(filePath, content);\n}\n\nexport async function makeDir(dirPath: string) {\n try {\n await fs.access(dirPath);\n } catch (e) {\n await fs.mkdir(dirPath, {recursive: true});\n }\n}\n\nexport async function copyDir(srcDir: string, dstDir: string) {\n if (!fsExtra.existsSync(srcDir)) {\n return;\n }\n fsExtra.copySync(srcDir, dstDir, {recursive: true, overwrite: true});\n}\n\nexport async function rmDir(dirPath: string) {\n await fs.rm(dirPath, {recursive: true, force: true});\n}\n\nexport async function loadJson(filePath: string): Promise<any> {\n const content = await fs.readFile(filePath, 'utf-8');\n return JSON.parse(content);\n}\n\nexport async function isDirectory(dirPath: string) {\n return fs\n .stat(dirPath)\n .then((fsStat) => {\n return fsStat.isDirectory();\n })\n .catch((err) => {\n if (err.code === 'ENOENT') {\n return false;\n }\n throw err;\n });\n}\n\nexport function fileExists(filePath: string): Promise<boolean> {\n return fs\n .access(filePath)\n .then(() => true)\n .catch(() => false);\n}\n","import path from 'node:path';\nimport {fileURLToPath} from 'node:url';\nimport fsExtra from 'fs-extra';\nimport glob from 'tiny-glob';\nimport {build as viteBuild} from 'vite';\nimport {pluginRoot} from '../../render/vite-plugin-root.js';\nimport {BuildAssetMap} from '../../render/asset-map/build-asset-map.js';\nimport {loadRootConfig} from '../load-config.js';\nimport {\n copyDir,\n isDirectory,\n isJsFile,\n loadJson,\n makeDir,\n rmDir,\n writeFile,\n} from '../../core/fsutils.js';\nimport {Renderer} from '../../render/render.js';\nimport {htmlMinify} from '../../render/html-minify.js';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nexport async function build(rootDir?: string) {\n console.log('🌳 Root.js');\n\n if (!rootDir) {\n rootDir = process.cwd();\n }\n const rootConfig = await loadRootConfig(rootDir);\n const distDir = path.join(rootDir, 'dist');\n await rmDir(distDir);\n await makeDir(distDir);\n\n const pages: string[] = [];\n if (await isDirectory(path.join(rootDir, 'routes'))) {\n const pageFiles = await glob(path.join(rootDir, 'routes/**/*'));\n pageFiles.forEach((file) => {\n const parts = path.parse(file);\n if (!parts.name.startsWith('_') && isJsFile(parts.base)) {\n pages.push(file);\n }\n });\n }\n\n const elements: string[] = [];\n if (await isDirectory(path.join(rootDir, 'elements'))) {\n const elementFiles = await glob(path.join(rootDir, 'elements/**/*'));\n elementFiles.forEach((file) => {\n const parts = path.parse(file);\n if (isJsFile(parts.base)) {\n elements.push(file);\n }\n });\n }\n\n const bundleScripts: string[] = [];\n if (await isDirectory(path.join(rootDir, 'bundles'))) {\n const bundleFiles = await glob(path.join(rootDir, 'bundles/*'));\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 viteConfig = rootConfig.vite || {};\n const baseConfig = {\n ...viteConfig,\n root: rootDir,\n esbuild: {\n jsxFactory: 'h',\n jsxFragment: 'Fragment',\n jsxInject: 'import {h, Fragment} from \"preact\";',\n },\n plugins: [...(viteConfig.plugins || []), pluginRoot()],\n };\n\n // Bundle the render.js file with vite, which is pre-optimized for rendering\n // HTML routes.\n await viteBuild({\n ...baseConfig,\n mode: 'production',\n publicDir: false,\n build: {\n rollupOptions: {\n input: [path.resolve(__dirname, './render.js')],\n output: {\n format: 'esm',\n chunkFileNames: 'chunks/[name].[hash].js',\n assetFileNames: 'assets/[name].[hash][extname]',\n },\n },\n outDir: path.join(distDir, 'server'),\n ssr: true,\n ssrManifest: false,\n cssCodeSplit: true,\n target: 'esnext',\n minify: false,\n polyfillModulePreload: false,\n reportCompressedSize: false,\n },\n ssr: {\n noExternal: ['@blinkk/root'],\n },\n });\n\n // Pre-render any client scripts and CSS deps.\n await viteBuild({\n ...baseConfig,\n mode: 'production',\n publicDir: false,\n build: {\n rollupOptions: {\n input: [...pages, ...elements, ...bundleScripts],\n output: {\n format: 'esm',\n chunkFileNames: 'chunks/[name].[hash].js',\n assetFileNames: 'assets/[name].[hash][extname]',\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 polyfillModulePreload: false,\n reportCompressedSize: false,\n },\n });\n\n const manifest = await loadJson(path.join(distDir, 'client/manifest.json'));\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 = new BuildAssetMap(manifest);\n\n // Save the asset map to `dist/client` for use by the prod SSR server.\n writeFile(\n path.join(distDir, 'client/root-manifest.json'),\n JSON.stringify(assetMap.toJson(), 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);\n } else {\n makeDir(buildDir);\n }\n\n // Copy files from `dist/client/{assets,chunks}` to `dist/html`.\n copyDir(path.join(distDir, 'client/assets'), path.join(buildDir, 'assets'));\n copyDir(path.join(distDir, 'client/chunks'), path.join(buildDir, 'chunks'));\n\n // Render HTML pages.\n const render = await import(path.join(distDir, 'server/render.js'));\n const renderer = new render.Renderer(rootConfig) as Renderer;\n const sitemap = await renderer.getSitemap();\n\n await Promise.all(\n Object.keys(sitemap).map(async (urlPath) => {\n const {route, params} = sitemap[urlPath];\n const data = await renderer.renderRoute(route, {\n assetMap,\n routeParams: params,\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 outPath = path.join(distDir, `html${urlPath}`, 'index.html');\n\n if (outPath.endsWith('404/index.html')) {\n outPath = outPath.replace('404/index.html', '404.html');\n }\n\n const html = await htmlMinify(data.html || '');\n await writeFile(outPath, html);\n\n const relPath = outPath.slice(path.dirname(distDir).length + 1);\n console.log(`saved ${relPath}`);\n })\n );\n}\n","import path from 'path';\nimport {Manifest, ManifestChunk} from 'vite';\nimport {Asset, AssetMap} from './asset-map';\n\nexport class BuildAssetMap implements AssetMap {\n private manifest: Manifest;\n private moduleIdToAsset: Map<string, BuildAsset>;\n\n constructor(manifest: Manifest) {\n this.manifest = manifest;\n this.moduleIdToAsset = new Map();\n Object.keys(this.manifest).forEach((manifestKey) => {\n const moduleId = `/${manifestKey}`;\n this.moduleIdToAsset.set(\n moduleId,\n new BuildAsset(this, moduleId, this.manifest[manifestKey])\n );\n });\n }\n\n async get(moduleId: string): Promise<Asset | null> {\n return this.moduleIdToAsset.get(moduleId) || null;\n }\n\n toJson(): any {\n const result: any = {};\n for (const moduleId of this.moduleIdToAsset.keys()) {\n result[moduleId] = this.moduleIdToAsset.get(moduleId)!.toJson();\n }\n return result;\n }\n}\n\nexport class BuildAsset {\n moduleId: string;\n assetUrl: string;\n private assetMap: BuildAssetMap;\n private manifestData: ManifestChunk;\n private importedModules: string[];\n private importedCss: string[];\n\n constructor(\n assetMap: BuildAssetMap,\n moduleId: string,\n manifestData: ManifestChunk\n ) {\n this.assetMap = assetMap;\n this.moduleId = moduleId;\n this.manifestData = manifestData;\n this.assetUrl = `/${manifestData.file}`;\n this.importedModules = (this.manifestData.imports || []).map(\n (relPath) => `/${relPath}`\n );\n this.importedCss = (this.manifestData.css || []).map(\n (relPath) => `/${relPath}`\n );\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.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 ['.ts', '.tsx'].includes(parts.ext) &&\n asset.moduleId.includes('/elements/')\n ) {\n urls.add(asset.assetUrl);\n }\n await Promise.all(\n asset.importedModules.map(async (moduleId) => {\n const importedAsset = (await this.assetMap.get(moduleId)) 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.assetUrl) {\n return;\n }\n if (visited.has(asset.moduleId)) {\n return;\n }\n visited.add(asset.moduleId);\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(): any {\n return {\n moduleId: this.moduleId,\n assetUrl: this.assetUrl,\n importedModules: this.importedModules,\n importedCss: this.importedCss,\n };\n }\n}\n","export async function start(rootDir?: string) {\n console.log('SSR production server is coming soon');\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;;;ACHA;AACA;AAGA,IAAM,iBAAiB;AAOhB,oBAAoB,SAA6B;AACtD,QAAM,UAAU,oCAAS,YAAW,QAAQ,IAAI;AAChD,MAAI;AACJ,MAAI;AACJ,MAAI;AAEJ,oCAAkC;AAChC,iBAAa,CAAC;AACd,UAAM,QAAQ,MAAM,KAAK,mBAAmB,EAAC,KAAK,QAAO,CAAC;AAC1D,UAAM,QAAQ,CAAC,SAAS;AACtB,YAAM,QAAQ,KAAK,MAAM,IAAI;AAC7B,UAAI,SAAS,MAAM,IAAI,GAAG;AACxB,mBAAW,MAAM,QAAQ,GAAG,WAAW;AAAA,MACzC;AAAA,IACF,CAAC;AAAA,EACH;AAEA,kCAAgC,SAAyC;AACvE,QAAI,CAAC,YAAY;AACf,YAAM,iBAAiB;AAAA,IACzB;AACA,QAAI,WAAW,YAAY;AACzB,YAAM,WAAW,WAAW;AAC5B,UAAI,UAAU,OAAO,aAAa;AAChC,cAAM,YAAY,OAAO,YAAY,iBAAiB,QAAQ;AAC9D,YAAI,aAAa,UAAU,OAAO,GAAG;AACnC,gBAAM,SAAS,UAAU,OAAO,EAAE,KAAK,EAAE;AACzC,iBAAO,OAAO;AAAA,QAChB;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IAIN,eAAe,gBAAqB;AAClC,eAAS;AAAA,IACX;AAAA,IAEA,gBAAgB,SAAwB;AACtC,eAAS;AAAA,IACX;AAAA,IAEA,MAAM,UAAU,KAA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Q,OAAO,EAAE,SAAS,CAAC;AAC9D,YAAQ,IAAI,SAAS,SAAS;AAAA,EAChC,CAAC,CACH;AACF;;;AE5LA,qBAA4B,SAAkB;AAC5C,UAAQ,IAAI,sCAAsC;AACpD;","names":[]}
1
+ {"version":3,"sources":["../src/cli/commands/dev.ts","../src/render/vite-plugin-root.ts","../src/core/elements.ts","../src/core/fsutils.ts","../src/render/asset-map/dev-asset-map.ts","../src/cli/load-config.ts","../src/render/html-minify.ts","../src/core/middleware.ts","../src/cli/ports.ts","../src/cli/commands/build.ts","../src/render/asset-map/build-asset-map.ts","../src/cli/commands/preview.ts","../src/cli/commands/start.ts"],"sourcesContent":["import path from 'node:path';\nimport {fileURLToPath} from 'node:url';\nimport {default as express} from 'express';\nimport {createServer as createViteServer} from 'vite';\nimport {pluginRoot} from '../../render/vite-plugin-root.js';\nimport {DevServerAssetMap} from '../../render/asset-map/dev-asset-map.js';\nimport {loadRootConfig} from '../load-config.js';\nimport {htmlMinify} from '../../render/html-minify.js';\nimport {isDirectory, isJsFile} from '../../core/fsutils.js';\nimport glob from 'tiny-glob';\nimport {dim} from 'kleur/colors';\nimport {Server, Request, Response, NextFunction} from '../../core/types.js';\nimport {configureServerPlugins, getVitePlugins} from '../../core/plugin.js';\nimport {RootConfig} from '../../core/config.js';\nimport {rootProjectMiddleware} from '../../core/middleware.js';\nimport {findOpenPort} from '../ports.js';\nimport {getElements} from '../../core/elements.js';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nexport async function dev(rootProjectDir?: string) {\n process.env.NODE_ENV = 'development';\n const rootDir = path.resolve(rootProjectDir || process.cwd());\n const defaultPort = parseInt(process.env.PORT || '4007');\n const port = await findOpenPort(defaultPort, defaultPort + 10);\n console.log();\n console.log(`${dim('┃')} project: ${rootDir}`);\n console.log(`${dim('┃')} server: http://localhost:${port}`);\n console.log(`${dim('┃')} mode: development`);\n console.log();\n const server = await createServer({rootDir, port});\n server.listen(port);\n}\n\nasync function createServer(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);\n const port = options?.port;\n\n const server = express();\n server.disable('x-powered-by');\n\n // Inject req context vars.\n server.use(rootProjectMiddleware({rootDir, rootConfig}));\n server.use(await viteServerMiddleware({rootDir, rootConfig, port}));\n server.use(rootDevRendererMiddleware());\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 // Add the root.js dev server middlewares.\n server.use(rootDevServerMiddleware());\n server.use(rootDevServer404Middleware());\n },\n plugins,\n {type: 'dev'}\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 rootDir: string;\n rootConfig: RootConfig;\n port?: number;\n}) {\n const rootDir = options.rootDir;\n const rootConfig = options.rootConfig;\n const viteConfig = rootConfig.vite || {};\n\n let hmrOptions = viteConfig.server?.hmr;\n if (typeof hmrOptions === 'undefined' && options.port) {\n // Automatically set the HMR port to `port + 10`. This allows multiple\n // root.js dev servers to run without conflicts.\n hmrOptions = {port: options.port + 10};\n }\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(file);\n }\n });\n }\n\n const elementsMap = await getElements(rootConfig);\n const elements = Object.values(elementsMap).map((mod) => mod.src);\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 viteServer = await createViteServer({\n ...viteConfig,\n mode: 'development',\n root: rootDir,\n publicDir: path.join(rootDir, 'public'),\n server: {\n ...(viteConfig.server || {}),\n middlewareMode: true,\n hmr: hmrOptions,\n },\n appType: 'custom',\n optimizeDeps: {\n ...(viteConfig.optimizeDeps || {}),\n include: [\n ...routeFiles,\n ...elements,\n ...bundleScripts,\n ...(viteConfig.optimizeDeps?.include || []),\n ],\n },\n ssr: {\n ...(viteConfig.ssr || {}),\n noExternal: ['@blinkk/root'],\n },\n esbuild: {\n ...(viteConfig.esbuild || {}),\n jsx: 'automatic',\n jsxImportSource: 'preact',\n },\n plugins: [\n await pluginRoot({rootConfig}),\n ...(viteConfig.plugins || []),\n ...getVitePlugins(rootConfig.plugins || []),\n ],\n });\n return (req: Request, res: Response, next: NextFunction) => {\n req.viteServer = viteServer;\n viteServer.middlewares(req, res, next);\n };\n}\n\nfunction rootDevRendererMiddleware() {\n const renderModulePath = path.resolve(__dirname, './render.js');\n return async (req: Request, _: Response, next: NextFunction) => {\n const rootConfig = req.rootConfig!;\n const viteServer = req.viteServer!;\n // Dynamically import the render.js module using vite's SSR import loader.\n const render = await viteServer.ssrLoadModule(renderModulePath);\n // Create a dev asset map using Vite dev server's module graph.\n const assetMap = new DevServerAssetMap(rootConfig, viteServer.moduleGraph);\n req.renderer = new render.Renderer(rootConfig, {assetMap});\n next();\n };\n}\n\nfunction rootDevServerMiddleware() {\n return async (req: Request, res: Response, next: NextFunction) => {\n const url = req.originalUrl;\n const renderer = req.renderer!;\n const viteServer = req.viteServer!;\n const rootConfig = req.rootConfig!;\n try {\n const data = await renderer.render(url);\n if (data.notFound || !data.html) {\n next();\n return;\n }\n // Inject the Vite HMR client.\n let html = await viteServer.transformIndexHtml(url, data.html || '');\n if (rootConfig.minifyHtml !== false) {\n html = await htmlMinify(html);\n }\n res.status(200).set({'Content-Type': 'text/html'}).end(html);\n } catch (e) {\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(e);\n console.error(e);\n try {\n if (renderer) {\n const {html} = await renderer.renderError(e);\n res.status(500).set({'Content-Type': 'text/html'}).end(html);\n } else {\n next(e);\n }\n } catch (e2) {\n console.error('failed to render custom error');\n console.error(e2);\n next(e);\n }\n }\n };\n}\n\nfunction rootDevServer404Middleware() {\n return async (req: Request, res: Response) => {\n const url = req.originalUrl;\n const ext = path.extname(url);\n const renderer = req.renderer!;\n if (!ext) {\n const data = await renderer.renderDevServer404();\n const html = data.html || '';\n res.status(404).set({'Content-Type': 'text/html'}).end(html);\n return;\n }\n res.status(404).set({'Content-Type': 'text/plain'}).end('404');\n };\n}\n","import path from 'node:path';\nimport {ElementModule} from 'virtual:root-elements';\nimport {RootConfig} from '../core/config';\nimport {getElements} from '../core/elements';\nimport {isJsFile} from '../core/fsutils';\n\nconst JSX_ELEMENTS_REGEX = /jsxs?\\(\"(\\w[\\w-]+\\w)\"/g;\nconst HTML_ELEMENTS_REGEX = /<(\\w[\\w-]+\\w)/g;\n\nexport interface RootPluginOptions {\n rootConfig: RootConfig;\n}\n\nexport function pluginRoot(options: RootPluginOptions) {\n const elementsVirtualId = 'virtual:root-elements';\n const resolvedElementsVirtualId = '\\0' + elementsVirtualId;\n const rootConfig = options.rootConfig;\n\n let tagNameToElement: Record<string, ElementModule>;\n const customElementFiles: Set<string> = new Set();\n async function updateElementMap() {\n tagNameToElement = await getElements(rootConfig);\n customElementFiles.clear();\n Object.values(tagNameToElement).forEach((elementModule) => {\n customElementFiles.add(elementModule.filePath);\n customElementFiles.add(elementModule.realPath);\n });\n }\n\n async function getElementImport(tagname: string): Promise<string | null> {\n if (!tagNameToElement) {\n await updateElementMap();\n }\n if (tagname in tagNameToElement) {\n const elementModule = tagNameToElement[tagname];\n if (elementModule.filePath === elementModule.realPath) {\n return elementModule.src;\n }\n // TODO(stevenle): handle symlinked elements.\n }\n return null;\n }\n\n function isCustomElement(id: string) {\n if (!isJsFile(id)) {\n return false;\n }\n return customElementFiles.has(id);\n }\n\n return {\n name: 'vite-plugin-root',\n\n resolveId(id: string) {\n if (id === elementsVirtualId) {\n return resolvedElementsVirtualId;\n }\n return null;\n },\n\n async load(id: string) {\n if (id === resolvedElementsVirtualId) {\n await updateElementMap();\n return `export const elementsMap = ${JSON.stringify(tagNameToElement)}`;\n }\n return null;\n },\n\n async transform(src: string, id: string): Promise<any> {\n if (isCustomElement(id)) {\n await updateElementMap();\n const idParts = path.parse(id);\n const deps = new Set<string>();\n const tagnames = [\n ...src.matchAll(JSX_ELEMENTS_REGEX),\n ...src.matchAll(HTML_ELEMENTS_REGEX),\n ];\n for (const match of tagnames) {\n const tagname = match[1];\n // All custom elements should contain a dash.\n if (!tagname.includes('-')) {\n continue;\n }\n // Avoid circular deps.\n if (tagname === idParts.name) {\n continue;\n }\n deps.add(tagname);\n }\n const importUrls: string[] = [];\n await Promise.all(\n Array.from(deps).map(async (tagname) => {\n const importUrl = await getElementImport(tagname);\n if (importUrl) {\n importUrls.push(importUrl);\n }\n })\n );\n if (importUrls.length > 0) {\n const importLines = importUrls\n .map((url) => `import '/${url}';`)\n .join('\\n');\n const code = `${src}\n\n// autogenerated by root:\n${importLines}\n`;\n return {code};\n }\n return null;\n }\n return null;\n },\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport glob from 'tiny-glob';\nimport {ElementModule} from 'virtual:root-elements';\nimport {searchForWorkspaceRoot} from 'vite';\nimport {RootConfig} from './config';\nimport {directoryContains, isDirectory, isJsFile} from './fsutils';\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<Record<string, ElementModule>> {\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 const excludePatterns = rootConfig.elements?.exclude || [];\n const excludeElement = (moduleId: string) => {\n return excludePatterns.some((pattern) => Boolean(moduleId.match(pattern)));\n };\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 const elementMap: Record<string, ElementModule> = {};\n for (const dirPath of elementsDirs) {\n if (await isDirectory(dirPath)) {\n const elementFiles = await glob('**/*', {cwd: dirPath});\n elementFiles.forEach((file) => {\n const parts = path.parse(file);\n if (isJsFile(parts.base)) {\n const filePath = path.join(dirPath, file);\n const src = path.relative(rootDir, filePath);\n const realPath = fs.realpathSync(filePath);\n if (!excludeElement(src)) {\n elementMap[parts.name] = {\n src,\n filePath,\n realPath,\n };\n }\n }\n });\n }\n }\n return elementMap;\n}\n","import {promises as fs} from 'node:fs';\nimport path from 'node:path';\nimport fsExtra from 'fs-extra';\n\nexport function isJsFile(filename: string) {\n return !!filename.match(/\\.(j|t)sx?$/);\n}\n\nexport async function writeFile(filepath: string, content: string) {\n const dirPath = path.dirname(filepath);\n await makeDir(dirPath);\n await fs.writeFile(filepath, content);\n}\n\nexport async function makeDir(dirpath: string) {\n try {\n await fs.access(dirpath);\n } catch (e) {\n await fs.mkdir(dirpath, {recursive: true});\n }\n}\n\nexport async function copyDir(srcdir: string, dstdir: string) {\n if (!fsExtra.existsSync(srcdir)) {\n return;\n }\n fsExtra.copySync(srcdir, dstdir, {recursive: true, overwrite: true});\n}\n\nexport async function rmDir(dirpath: string) {\n await fs.rm(dirpath, {recursive: true, force: true});\n}\n\nexport async function loadJson<T = unknown>(filepath: string): Promise<T> {\n const content = await fs.readFile(filepath, 'utf-8');\n return JSON.parse(content);\n}\n\nexport async function isDirectory(dirpath: string) {\n return fs\n .stat(dirpath)\n .then((fsStat) => {\n return fsStat.isDirectory();\n })\n .catch((err) => {\n if (err.code === 'ENOENT') {\n return false;\n }\n throw err;\n });\n}\n\nexport function fileExists(filepath: string): Promise<boolean> {\n return fs\n .access(filepath)\n .then(() => true)\n .catch(() => false);\n}\n\nexport async function directoryContains(\n dirpath: string,\n subpath: string\n): Promise<boolean> {\n const outer = await fs.realpath(dirpath);\n const inner = await fs.realpath(subpath);\n const rel = path.relative(outer, inner);\n return !rel.startsWith('..');\n}\n","import path from 'node:path';\nimport {ModuleGraph, ModuleNode, searchForWorkspaceRoot} from 'vite';\nimport {RootConfig} from '../../core/config';\nimport {directoryContains} from '../../core/fsutils';\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 {bundleRequire} from 'bundle-require';\nimport JoyCon from 'joycon';\nimport {RootConfig} from '../core/config';\n\nexport async function loadRootConfig(rootDir: string): Promise<RootConfig> {\n const joycon = new JoyCon();\n const configPath = await joycon.resolve({\n cwd: rootDir,\n files: ['root.config.ts'],\n });\n if (configPath) {\n const configBundle = await bundleRequire({\n filepath: configPath,\n });\n return Object.assign({}, configBundle.mod.default || {}, {rootDir});\n }\n return {rootDir};\n}\n","import {minify} from 'html-minifier-terser';\n\nexport async function htmlMinify(html: string): Promise<string> {\n try {\n const min = await minify(html, {\n collapseWhitespace: true,\n removeComments: true,\n preserveLineBreaks: true,\n });\n return min.trimStart();\n } catch (e) {\n console.error('failed to minify html:', e);\n return html;\n }\n}\n","import {RootConfig} from './config';\nimport {Request, Response, NextFunction} from './types';\n\n/**\n * Middleware that injects the root.js project config into the request context.\n */\nexport function rootProjectMiddleware(options: {\n rootDir: string;\n rootConfig: RootConfig;\n}) {\n return (req: Request, _: Response, next: NextFunction) => {\n req.rootConfig = Object.assign({}, options.rootConfig, {\n rootDir: options.rootDir,\n });\n next();\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","import path from 'node:path';\nimport {fileURLToPath} from 'node:url';\nimport fsExtra from 'fs-extra';\nimport glob from 'tiny-glob';\nimport {build as viteBuild, Manifest, UserConfig} from 'vite';\nimport {pluginRoot} from '../../render/vite-plugin-root.js';\nimport {BuildAssetMap} from '../../render/asset-map/build-asset-map.js';\nimport {loadRootConfig} from '../load-config.js';\nimport {\n isDirectory,\n isJsFile,\n loadJson,\n makeDir,\n rmDir,\n writeFile,\n} from '../../core/fsutils.js';\nimport {htmlMinify} from '../../render/html-minify.js';\nimport {dim, blue, cyan} from 'kleur/colors';\nimport {getVitePlugins} from '../../core/plugin.js';\nimport {getElements} from '../../core/elements.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}\n\nexport async function build(rootProjectDir?: string, options?: BuildOptions) {\n const rootDir = path.resolve(rootProjectDir || process.cwd());\n const rootConfig = await loadRootConfig(rootDir);\n const distDir = path.join(rootDir, 'dist');\n const ssrOnly = options?.ssrOnly || false;\n const mode = options?.mode || 'production';\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 elementsMap = await getElements(rootConfig);\n const elements = Object.values(elementsMap).map((mod) =>\n path.resolve(rootDir, mod.src)\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 viteConfig = rootConfig.vite || {};\n const vitePlugins = [\n pluginRoot({rootConfig}),\n ...(viteConfig.plugins || []),\n ...getVitePlugins(rootConfig.plugins || []),\n ];\n\n const baseConfig: UserConfig = {\n ...viteConfig,\n root: rootDir,\n mode: mode,\n esbuild: {\n jsx: 'automatic',\n jsxImportSource: 'preact',\n treeShaking: true,\n },\n plugins: vitePlugins,\n };\n\n // Bundle the render.js file with vite, which is pre-optimized for rendering\n // HTML routes.\n await viteBuild({\n ...baseConfig,\n publicDir: false,\n build: {\n rollupOptions: {\n input: [path.resolve(__dirname, './render.js')],\n output: {\n format: 'esm',\n chunkFileNames: 'chunks/[name].[hash].js',\n assetFileNames: 'assets/[name].[hash][extname]',\n },\n },\n outDir: path.join(distDir, 'server'),\n ssr: true,\n ssrManifest: false,\n cssCodeSplit: true,\n target: 'esnext',\n minify: false,\n polyfillModulePreload: false,\n reportCompressedSize: false,\n },\n ssr: {\n noExternal: ['@blinkk/root'],\n },\n });\n\n // Pre-render any client scripts and CSS deps.\n await viteBuild({\n ...baseConfig,\n publicDir: false,\n build: {\n rollupOptions: {\n input: [...routeFiles, ...elements, ...bundleScripts],\n output: {\n format: 'esm',\n chunkFileNames: 'chunks/[name].[hash].js',\n assetFileNames: 'assets/[name].[hash][extname]',\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 polyfillModulePreload: false,\n reportCompressedSize: false,\n },\n });\n\n const viteManifest = await loadJson<Manifest>(\n path.join(distDir, 'client/manifest.json')\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 viteManifest,\n elementsMap\n );\n\n // Save the asset map to `dist/client` for use by the prod SSR server.\n const rootManifest = assetMap.toJson();\n writeFile(\n path.join(distDir, 'client/root-manifest.json'),\n JSON.stringify(rootManifest, 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);\n } else {\n makeDir(buildDir);\n }\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 makeDir(path.join(buildDir, 'assets'));\n makeDir(path.join(buildDir, 'chunks'));\n Object.keys(rootManifest).forEach((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 const assetRelPath = assetData.assetUrl.slice(1);\n const assetFrom = path.join(distDir, 'client', assetRelPath);\n const assetTo = path.join(buildDir, assetRelPath);\n fsExtra.copySync(assetFrom, assetTo);\n printFileOutput(fileSize(assetTo), 'dist/html/', assetRelPath);\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});\n const sitemap = await renderer.getSitemap();\n\n console.log('\\nhtml output:');\n await Promise.all(\n Object.keys(sitemap).map(async (urlPath) => {\n const {route, params} = sitemap[urlPath];\n const data = await renderer.renderRoute(route, {\n routeParams: params,\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 const html = await htmlMinify(data.html || '');\n await writeFile(outPath, html);\n\n printFileOutput(fileSize(outPath), 'dist/html/', outFilePath);\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","import fs from 'node:fs';\nimport path from 'node:path';\nimport {ElementModule} from 'virtual:root-elements';\nimport {Manifest} from 'vite';\nimport {RootConfig} from '../../core/config';\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 viteManifest: Manifest,\n elementMap: Record<string, ElementModule>\n ) {\n const assetMap = new BuildAssetMap(rootConfig);\n\n const elementFiles = new Set();\n Object.values(elementMap).forEach((elementModule) => {\n elementFiles.add(elementModule.src);\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(rootConfig.rootDir, elementModule.src);\n if (realSrc !== elementModule.src) {\n elementFiles.add(realSrc);\n }\n });\n\n Object.keys(viteManifest).forEach((manifestKey) => {\n const src = manifestKey;\n const manifestChunk = viteManifest[manifestKey];\n const isElement = elementFiles.has(src);\n const assetData = {\n src: src,\n assetUrl: `/${manifestChunk.file}`,\n importedModules: manifestChunk.imports || [],\n importedCss: (manifestChunk.css || []).map((relPath) => `/${relPath}`),\n isElement: isElement,\n };\n assetMap.add(new BuildAsset(assetMap, assetData));\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.assetUrl) {\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","import path from 'node:path';\nimport {default as express} from 'express';\nimport {Request, Response, NextFunction, Server} from '../../core/types.js';\nimport {loadRootConfig} from '../load-config';\nimport {Renderer} from '../../render/render.js';\nimport {fileExists, loadJson} from '../../core/fsutils';\nimport {\n BuildAssetManifest,\n BuildAssetMap,\n} from '../../render/asset-map/build-asset-map';\nimport {htmlMinify} from '../../render/html-minify';\nimport {dim} from 'kleur/colors';\nimport {configureServerPlugins} from '../../core/plugin';\nimport sirv from 'sirv';\nimport compression from 'compression';\nimport {rootProjectMiddleware} from '../../core/middleware';\nimport {RootConfig} from '../../core/config';\n\ntype RenderModule = typeof import('../../render/render.js');\n\nexport async function preview(rootProjectDir?: string) {\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 createServer({rootDir});\n const port = parseInt(process.env.PORT || '4007');\n console.log();\n console.log(`${dim('┃')} project: ${rootDir}`);\n console.log(`${dim('┃')} server: http://localhost:${port}`);\n console.log(`${dim('┃')} mode: staging`);\n console.log();\n server.listen(port);\n}\n\nasync function createServer(options: {rootDir: string}): Promise<Server> {\n const rootDir = options.rootDir;\n const rootConfig = await loadRootConfig(rootDir);\n const distDir = path.join(rootDir, 'dist');\n\n const server = express();\n server.disable('x-powered-by');\n server.use(compression());\n\n // Inject request context vars.\n server.use(rootProjectMiddleware({rootDir, rootConfig}));\n server.use(await rootPreviewRendererMiddleware({rootConfig, distDir}));\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(rootPreviewServerMiddleware());\n // TODO(stevenle): handle 404/500 errors.\n },\n plugins,\n {type: 'preview'}\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 rootManifest = await loadJson<BuildAssetManifest>(manifestPath);\n const assetMap = BuildAssetMap.fromRootManifest(rootConfig, rootManifest);\n const renderer = new render.Renderer(rootConfig, {assetMap}) as Renderer;\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 rootConfig = req.rootConfig!;\n const renderer = req.renderer!;\n try {\n const url = req.originalUrl;\n const data = await renderer.render(url);\n if (data.notFound || !data.html) {\n next();\n return;\n }\n let html = data.html || '';\n if (rootConfig.minifyHtml !== false) {\n html = await htmlMinify(html);\n }\n res.status(200).set({'Content-Type': 'text/html'}).end(html);\n } catch (e) {\n try {\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","import path from 'node:path';\nimport {default as express} from 'express';\nimport {loadRootConfig} from '../load-config';\nimport {Renderer} from '../../render/render.js';\nimport {fileExists, loadJson} from '../../core/fsutils';\nimport {\n BuildAssetManifest,\n BuildAssetMap,\n} from '../../render/asset-map/build-asset-map';\nimport {htmlMinify} from '../../render/html-minify';\nimport {dim} from 'kleur/colors';\nimport {configureServerPlugins} from '../../core/plugin';\nimport sirv from 'sirv';\nimport compression from 'compression';\nimport {Request, Response, NextFunction, Server} from '../../core/types.js';\nimport {rootProjectMiddleware} from '../../core/middleware';\nimport {RootConfig} from '../../core/config';\n\ntype RenderModule = typeof import('../../render/render.js');\n\nexport async function start(rootProjectDir?: string) {\n process.env.NODE_ENV = 'production';\n const rootDir = path.resolve(rootProjectDir || process.cwd());\n const server = await createServer({rootDir});\n const port = parseInt(process.env.PORT || '4007');\n console.log();\n console.log(`${dim('┃')} project: ${rootDir}`);\n console.log(`${dim('┃')} server: http://localhost:${port}`);\n console.log(`${dim('┃')} mode: production`);\n console.log();\n server.listen(port);\n}\n\nasync function createServer(options: {rootDir: string}): Promise<Server> {\n const rootDir = options.rootDir;\n const rootConfig = await loadRootConfig(rootDir);\n const distDir = path.join(rootDir, 'dist');\n\n const server = express();\n server.disable('x-powered-by');\n server.use(compression());\n\n // Inject request context vars.\n server.use(rootProjectMiddleware({rootDir, rootConfig}));\n server.use(await rootProdRendererMiddleware({rootConfig, distDir}));\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(rootProdServerMiddleware());\n // TODO(stevenle): handle 404/500 errors.\n },\n plugins,\n {type: 'prod'}\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 preview\\`.`\n );\n }\n const rootManifest = await loadJson<BuildAssetManifest>(manifestPath);\n const assetMap = BuildAssetMap.fromRootManifest(rootConfig, rootManifest);\n const renderer = new render.Renderer(rootConfig, {assetMap}) as Renderer;\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 rootProdServerMiddleware() {\n return async (req: Request, res: Response, next: NextFunction) => {\n const rootConfig = req.rootConfig!;\n const renderer = req.renderer!;\n try {\n const url = req.originalUrl;\n const data = await renderer.render(url);\n if (data.notFound || !data.html) {\n next();\n return;\n }\n let html = data.html || '';\n if (rootConfig.minifyHtml !== false) {\n html = await htmlMinify(html);\n }\n res.status(200).set({'Content-Type': 'text/html'}).end(html);\n } catch (e) {\n try {\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"],"mappings":";;;;;;AAAA,OAAOA,WAAU;AACjB,SAAQ,qBAAoB;AAC5B,SAAQ,WAAW,eAAc;AACjC,SAAQ,gBAAgB,wBAAuB;;;ACH/C,OAAOC,WAAU;;;ACAjB,OAAOC,SAAQ;AACf,OAAOC,WAAU;AACjB,OAAO,UAAU;AAEjB,SAAQ,8BAA6B;;;ACJrC,SAAQ,YAAY,UAAS;AAC7B,OAAO,UAAU;AACjB,OAAO,aAAa;AAEb,SAAS,SAAS,UAAkB;AACzC,SAAO,CAAC,CAAC,SAAS,MAAM,aAAa;AACvC;AAEA,eAAsB,UAAU,UAAkB,SAAiB;AACjE,QAAM,UAAU,KAAK,QAAQ,QAAQ;AACrC,QAAM,QAAQ,OAAO;AACrB,QAAM,GAAG,UAAU,UAAU,OAAO;AACtC;AAEA,eAAsB,QAAQ,SAAiB;AAC7C,MAAI;AACF,UAAM,GAAG,OAAO,OAAO;AAAA,EACzB,SAAS,GAAP;AACA,UAAM,GAAG,MAAM,SAAS,EAAC,WAAW,KAAI,CAAC;AAAA,EAC3C;AACF;AASA,eAAsB,MAAM,SAAiB;AAC3C,QAAM,GAAG,GAAG,SAAS,EAAC,WAAW,MAAM,OAAO,KAAI,CAAC;AACrD;AAEA,eAAsB,SAAsB,UAA8B;AACxE,QAAM,UAAU,MAAM,GAAG,SAAS,UAAU,OAAO;AACnD,SAAO,KAAK,MAAM,OAAO;AAC3B;AAEA,eAAsB,YAAY,SAAiB;AACjD,SAAO,GACJ,KAAK,OAAO,EACZ,KAAK,CAAC,WAAW;AAChB,WAAO,OAAO,YAAY;AAAA,EAC5B,CAAC,EACA,MAAM,CAAC,QAAQ;AACd,QAAI,IAAI,SAAS,UAAU;AACzB,aAAO;AAAA,I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,EAAE,IAAI,EAAC,gBAAgB,YAAW,CAAC,EAAE,IAAI,IAAI;AAAA,IAC7D,SAAS,GAAP;AACA,UAAI;AACF,cAAM,EAAC,KAAI,IAAI,MAAM,SAAS,YAAY,CAAC;AAC3C,YAAI,OAAO,GAAG,EAAE,IAAI,EAAC,gBAAgB,YAAW,CAAC,EAAE,IAAI,IAAI;AAAA,MAC7D,SAAS,IAAP;AACA,gBAAQ,MAAM,+BAA+B;AAC7C,gBAAQ,MAAM,EAAE;AAChB,aAAK,CAAC;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACF;","names":["path","path","fs","path","path","fs","path","path","searchForWorkspaceRoot","path","searchForWorkspaceRoot","glob","path","createServer","glob","path","fileURLToPath","fsExtra","glob","fs","path","asset","dim","__dirname","path","fileURLToPath","dim","glob","fsExtra","fileSize","path","express","dim","path","createServer","dim","express","path","express","dim","sirv","compression","path","createServer","dim","express","compression","sirv"]}
@@ -0,0 +1,213 @@
1
+ import { Express, Request as Request$1, Response as Response$1, NextFunction as NextFunction$1 } from 'express';
2
+ import { ViteDevServer, PluginOption, UserConfig } from 'vite';
3
+ import { ComponentType } from 'preact';
4
+
5
+ interface RouteModule {
6
+ default?: ComponentType<unknown>;
7
+ getStaticPaths?: GetStaticPaths;
8
+ getStaticProps?: GetStaticProps;
9
+ }
10
+ interface Route {
11
+ /** The relative path to the route file, e.g. `routes/index.tsx`. */
12
+ src: string;
13
+ /** The imported route module. */
14
+ module: RouteModule;
15
+ /** The locale used for the route. */
16
+ locale: string;
17
+ /**
18
+ * The mapped URL path for the route, e.g.:
19
+ *
20
+ * routes/index.tsx => `/`.
21
+ * routes/events.tsx => `/events`.
22
+ * routes/blog/[slug].tsx => `/blog/[slug]`.
23
+ *
24
+ * Per the example above, this value may contain placeholder params.
25
+ */
26
+ routePath: string;
27
+ /**
28
+ * The localized URL path for the route, e.g. `/[locale]/blog/[slug]`.
29
+ * Per the example above, this value contains placeholder params.
30
+ */
31
+ localeRoutePath: string;
32
+ }
33
+
34
+ interface Asset {
35
+ /**
36
+ * The path to the asset's src file, relative to the project root.
37
+ */
38
+ src: string;
39
+ /**
40
+ * The serving URL for the asset.
41
+ */
42
+ assetUrl: string;
43
+ /**
44
+ * Recursively walks all deps and returns a list of CSS asset URLs.
45
+ */
46
+ getCssDeps(): Promise<string[]>;
47
+ /**
48
+ * Recursively walks all deps and returns a list of JS asset URLs.
49
+ */
50
+ getJsDeps(): Promise<string[]>;
51
+ }
52
+ interface AssetMap {
53
+ /**
54
+ * Returns the asset for a given src file. The `src` value should be a path
55
+ * relative to the project root, e.g. "routes/index.tsx".
56
+ */
57
+ get: (src: string) => Promise<Asset | null>;
58
+ }
59
+
60
+ declare class Renderer {
61
+ private rootConfig;
62
+ private routes;
63
+ private assetMap;
64
+ constructor(rootConfig: RootConfig, options: {
65
+ assetMap: AssetMap;
66
+ });
67
+ render(url: string): Promise<{
68
+ html?: string;
69
+ notFound?: boolean;
70
+ }>;
71
+ renderRoute(route: Route, options: {
72
+ routeParams: Record<string, string>;
73
+ }): Promise<{
74
+ html?: string;
75
+ notFound?: boolean;
76
+ }>;
77
+ getSitemap(): Promise<Record<string, {
78
+ route: Route;
79
+ params: Record<string, string>;
80
+ }>>;
81
+ private renderHtml;
82
+ render404(): Promise<{
83
+ html: string;
84
+ notFound: boolean;
85
+ }>;
86
+ renderError(error: unknown): Promise<{
87
+ html: string;
88
+ }>;
89
+ renderDevServer404(): Promise<{
90
+ html: string;
91
+ }>;
92
+ /**
93
+ * Parses rendered HTML for custom element tags used on the page and
94
+ * automatically adds the JS/CSS deps to the page.
95
+ */
96
+ private collectElementDeps;
97
+ }
98
+
99
+ declare type GetStaticProps<T = unknown> = (ctx: {
100
+ params: Record<string, string>;
101
+ }) => Promise<{
102
+ props?: T;
103
+ notFound?: boolean;
104
+ }>;
105
+ declare type GetStaticPaths<T = Record<string, string>> = () => Promise<{
106
+ paths: Array<{
107
+ params: T;
108
+ }>;
109
+ }>;
110
+ declare type Server = Express;
111
+ declare type Request = Request$1 & {
112
+ /** The root.js project config. */
113
+ rootConfig?: RootConfig & {
114
+ rootDir: string;
115
+ };
116
+ /** The vite dev server. This is only available when running `root dev`. */
117
+ viteServer?: ViteDevServer;
118
+ /** The root.js renderer, to render routes within middlware. */
119
+ renderer?: Renderer;
120
+ };
121
+ declare type Response = Response$1;
122
+ declare type NextFunction = NextFunction$1;
123
+
124
+ declare type MaybePromise<T> = T | Promise<T>;
125
+ declare type ConfigureServerHook = (server: Server, options: ConfigureServerOptions) => MaybePromise<void> | MaybePromise<() => void>;
126
+ interface ConfigureServerOptions {
127
+ type: 'dev' | 'preview' | 'prod';
128
+ }
129
+ interface Plugin {
130
+ name?: string;
131
+ /** Configures the root.js express server . */
132
+ configureServer?: ConfigureServerHook;
133
+ /** Adds vite plugins. */
134
+ vitePlugins?: PluginOption[];
135
+ }
136
+ /**
137
+ * Runs the pre-hook configureServer method of every plugin, calls a callback
138
+ * function, and then runs the configureServer's post-hook if provided. Plugins
139
+ * provide a post-hook by returning a callback function from configureServer.
140
+ */
141
+ declare function configureServerPlugins(server: Server, callback: () => Promise<void>, plugins: Plugin[], options: ConfigureServerOptions): Promise<void>;
142
+ declare function getVitePlugins(plugins: Plugin[]): PluginOption[];
143
+
144
+ interface RootUserConfig {
145
+ /**
146
+ * Config for auto-injecting custom element dependencies.
147
+ */
148
+ elements?: {
149
+ /**
150
+ * A list of directories to use to look for custom elements. The dir path
151
+ * should be relative to the project dir, e.g. "path/to/elements" or
152
+ * "node_modules/my-package".
153
+ */
154
+ include?: string[];
155
+ /**
156
+ * A list of RegEx patterns to exclude. The string passed to the RegEx is
157
+ * the file URL relative to the project root, e.g. "/elements/foo/foo.ts".
158
+ */
159
+ exclude?: RegExp[];
160
+ };
161
+ /**
162
+ * Config options for localization and internationalization.
163
+ */
164
+ i18n?: RootI18nConfig;
165
+ /**
166
+ * Config options for the Root.js express server.
167
+ */
168
+ server?: RootServerConfig;
169
+ /**
170
+ * Vite config.
171
+ * @see {@link https://vitejs.dev/config/} for more information.
172
+ */
173
+ vite?: UserConfig;
174
+ /**
175
+ * Whether to automatically minify HTML output.
176
+ */
177
+ minifyHtml?: boolean;
178
+ /**
179
+ * Whether to include a sitemap.xml file to the build output.
180
+ */
181
+ sitemap?: boolean;
182
+ /**
183
+ * Plugins.
184
+ */
185
+ plugins?: Plugin[];
186
+ }
187
+ declare type RootConfig = RootUserConfig & {
188
+ rootDir: string;
189
+ };
190
+ interface RootI18nConfig {
191
+ /**
192
+ * Locales enabled for the site.
193
+ */
194
+ locales?: string[];
195
+ /**
196
+ * The default locale to use. Defaults is `en`.
197
+ */
198
+ defaultLocale?: string;
199
+ /**
200
+ * URL format for localized content. Default is `/{locale}/{path}`.
201
+ */
202
+ urlFormat?: string;
203
+ }
204
+ interface RootServerConfig {
205
+ /**
206
+ * An array of middleware to add to the express server. These middleware are
207
+ * added to the beginning of the express app.
208
+ */
209
+ middlewares?: Array<(req: Request, res: Response, next: NextFunction) => void | Promise<void>>;
210
+ }
211
+ declare function defineConfig(config: RootUserConfig): RootUserConfig;
212
+
213
+ export { ConfigureServerHook as C, GetStaticProps as G, 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, GetStaticPaths as i, Request as j, Response as k, Renderer as l };
package/dist/core.d.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  import * as preact from 'preact';
2
- import { h, ComponentChildren } from 'preact';
3
- export { R as RootConfig, a as RootI18nConfig, d as defineConfig } from './config-5b8f6033.js';
2
+ import { ComponentChildren } from 'preact';
3
+ import { R as Route } from './config-9fd26091.js';
4
+ export { C as ConfigureServerHook, f as ConfigureServerOptions, i as GetStaticPaths, G as GetStaticProps, N as NextFunction, P as Plugin, j as Request, k as Response, b as RootConfig, c as RootI18nConfig, d as RootServerConfig, a as RootUserConfig, S as Server, g as configureServerPlugins, e as defineConfig, h as getVitePlugins } from './config-9fd26091.js';
5
+ import 'express';
4
6
  import 'vite';
5
7
 
6
8
  interface ErrorPageProps {
7
9
  error: unknown;
8
10
  }
9
- declare function ErrorPage(props: ErrorPageProps): h.JSX.Element;
11
+ declare function ErrorPage(props: ErrorPageProps): preact.JSX.Element;
10
12
 
11
13
  declare const HEAD_CONTEXT: preact.Context<ComponentChildren[]>;
12
14
  interface HeadProps {
@@ -26,7 +28,7 @@ interface ScriptProps {
26
28
  /**
27
29
  * The <Script> component is used for rendering any custom script modules. At
28
30
  * the moment, the system only pre-renders and bundles files that are in the
29
- * `src/bundles` folder at the root of the project.
31
+ * `/bundles` folder at the root of the project.
30
32
  */
31
33
  declare function Script(props: ScriptProps): null;
32
34
 
@@ -35,7 +37,26 @@ interface I18nContext {
35
37
  locale: string;
36
38
  translations: Record<string, string>;
37
39
  }
38
- declare function t(str: string, params?: Record<string, string>): string;
39
40
  declare function getTranslations(locale: string): Record<string, string>;
41
+ declare function useI18nContext(): I18nContext;
42
+ declare function useTranslations(): (str: string, params?: Record<string, string>) => string;
40
43
 
41
- export { ErrorPage, ErrorPageProps, HEAD_CONTEXT, Head, HeadProps, I18N_CONTEXT, I18nContext, SCRIPT_CONTEXT, Script, ScriptProps, getTranslations, t };
44
+ interface RequestContext {
45
+ /** The route file. */
46
+ route: Route;
47
+ /**
48
+ * Route param values. E.g. for a route like `routes/blog/[slug].tsx`,
49
+ * visiting `/blog/foo` will pass {slug: 'foo'} here.
50
+ */
51
+ routeParams: Record<string, string>;
52
+ /** Props passed to the route's server component. */
53
+ props: any;
54
+ /** The current locale. */
55
+ locale: string;
56
+ /** Translations map for the current locale. */
57
+ translations: Record<string, string>;
58
+ }
59
+ declare const REQUEST_CONTEXT: preact.Context<RequestContext | null>;
60
+ declare function useRequestContext(): RequestContext;
61
+
62
+ export { ErrorPage, ErrorPageProps, HEAD_CONTEXT, Head, HeadProps, I18N_CONTEXT, I18nContext, REQUEST_CONTEXT, RequestContext, SCRIPT_CONTEXT, Script, ScriptProps, getTranslations, useI18nContext, useRequestContext, useTranslations };
package/dist/core.js CHANGED
@@ -1,13 +1,20 @@
1
+ import {
2
+ configureServerPlugins,
3
+ getVitePlugins
4
+ } from "./chunk-ZB7R6ZOY.js";
1
5
  import {
2
6
  ErrorPage,
3
7
  HEAD_CONTEXT,
4
8
  Head,
5
9
  I18N_CONTEXT,
10
+ REQUEST_CONTEXT,
6
11
  SCRIPT_CONTEXT,
7
12
  Script,
8
13
  getTranslations,
9
- t
10
- } from "./chunk-4SVK7R4Z.js";
14
+ useI18nContext,
15
+ useRequestContext,
16
+ useTranslations
17
+ } from "./chunk-5FVR2OXQ.js";
11
18
 
12
19
  // src/core/config.ts
13
20
  function defineConfig(config) {
@@ -18,10 +25,15 @@ export {
18
25
  HEAD_CONTEXT,
19
26
  Head,
20
27
  I18N_CONTEXT,
28
+ REQUEST_CONTEXT,
21
29
  SCRIPT_CONTEXT,
22
30
  Script,
31
+ configureServerPlugins,
23
32
  defineConfig,
24
33
  getTranslations,
25
- t
34
+ getVitePlugins,
35
+ useI18nContext,
36
+ useRequestContext,
37
+ useTranslations
26
38
  };
27
39
  //# sourceMappingURL=core.js.map
package/dist/core.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/config.ts"],"sourcesContent":["import {UserConfig as ViteUserConfig} from 'vite';\n\nexport interface RootConfig {\n i18n?: RootI18nConfig;\n vite?: ViteUserConfig;\n sitemap?: boolean;\n}\n\nexport interface RootI18nConfig {\n locales?: string[];\n defaultLocale?: string;\n urlFormat?: string;\n}\n\nexport function defineConfig(config: RootConfig): RootConfig {\n return config;\n}\n"],"mappings":";;;;;;;;;;;;AAcO,sBAAsB,QAAgC;AAC3D,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/core/config.ts"],"sourcesContent":["import {Request, Response, NextFunction} from './types';\nimport {Plugin} from './plugin';\nimport {UserConfig as ViteUserConfig} from 'vite';\n\nexport interface RootUserConfig {\n /**\n * Config for auto-injecting custom element dependencies.\n */\n elements?: {\n /**\n * A list of directories to use to look for custom elements. The dir path\n * should be relative to the project dir, e.g. \"path/to/elements\" or\n * \"node_modules/my-package\".\n */\n include?: string[];\n\n /**\n * A list of RegEx patterns to exclude. The string passed to the RegEx is\n * the file URL relative to the project root, e.g. \"/elements/foo/foo.ts\".\n */\n exclude?: RegExp[];\n };\n\n /**\n * Config options for localization and internationalization.\n */\n i18n?: RootI18nConfig;\n\n /**\n * Config options for the Root.js express server.\n */\n server?: RootServerConfig;\n\n /**\n * Vite config.\n * @see {@link https://vitejs.dev/config/} for more information.\n */\n vite?: ViteUserConfig;\n\n /**\n * Whether to automatically minify HTML output.\n */\n minifyHtml?: boolean;\n\n /**\n * Whether to include a sitemap.xml file to the build output.\n */\n sitemap?: boolean;\n\n /**\n * Plugins.\n */\n plugins?: Plugin[];\n}\n\nexport type RootConfig = RootUserConfig & {\n rootDir: string;\n};\n\nexport interface RootI18nConfig {\n /**\n * Locales enabled for the site.\n */\n locales?: string[];\n\n /**\n * The default locale to use. Defaults is `en`.\n */\n defaultLocale?: string;\n\n /**\n * URL format for localized content. Default is `/{locale}/{path}`.\n */\n urlFormat?: string;\n}\n\nexport interface RootServerConfig {\n /**\n * An array of middleware to add to the express server. These middleware are\n * added to the beginning of the express app.\n */\n middlewares?: Array<\n (req: Request, res: Response, next: NextFunction) => void | Promise<void>\n >;\n}\n\nexport function defineConfig(config: RootUserConfig): RootUserConfig {\n return config;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsFO,SAAS,aAAa,QAAwC;AACnE,SAAO;AACT;","names":[]}
package/dist/render.d.ts CHANGED
@@ -1,69 +1,4 @@
1
- import { R as RootConfig } from './config-5b8f6033.js';
1
+ export { l as Renderer } from './config-9fd26091.js';
2
+ import 'express';
2
3
  import 'vite';
3
-
4
- declare type GetStaticProps<T = unknown> = (ctx: {
5
- params: Record<string, string>;
6
- }) => Promise<{
7
- props: T;
8
- notFound?: boolean;
9
- }>;
10
- declare type GetStaticPaths<T = Record<string, string>> = () => Promise<{
11
- paths: Array<{
12
- params: T;
13
- }>;
14
- }>;
15
-
16
- interface RouteModule {
17
- default: any;
18
- getStaticPaths?: GetStaticPaths;
19
- getStaticProps?: GetStaticProps;
20
- }
21
- interface Route {
22
- modulePath: string;
23
- module: RouteModule;
24
- locale: string;
25
- }
26
-
27
- interface Asset {
28
- moduleId: string;
29
- assetUrl: string;
30
- getCssDeps(): Promise<string[]>;
31
- getJsDeps(): Promise<string[]>;
32
- }
33
- interface AssetMap {
34
- get: (moduleId: string) => Promise<Asset | null>;
35
- }
36
-
37
- interface RenderOptions {
38
- assetMap: AssetMap;
39
- }
40
- declare class Renderer {
41
- private routes;
42
- constructor(config: RootConfig);
43
- render(url: string, options: RenderOptions): Promise<{
44
- html: string;
45
- notFound?: boolean;
46
- }>;
47
- renderRoute(route: Route, options: {
48
- routeParams: Record<string, string>;
49
- assetMap: AssetMap;
50
- }): Promise<{
51
- html: string;
52
- notFound?: boolean;
53
- }>;
54
- getSitemap(): Promise<Record<string, {
55
- route: Route;
56
- params: Record<string, string>;
57
- }>>;
58
- private renderHtml;
59
- render404(): Promise<{
60
- html: string;
61
- notFound: boolean;
62
- }>;
63
- renderError(error: unknown): Promise<{
64
- html: string;
65
- }>;
66
- private getScriptDeps;
67
- }
68
-
69
- export { Renderer };
4
+ import 'preact';