@blinkk/root 2.4.9 → 2.5.1

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.
@@ -1273,6 +1273,7 @@ async function findOpenPort(min, max) {
1273
1273
  }
1274
1274
 
1275
1275
  // src/utils/rand.ts
1276
+ import crypto from "crypto";
1276
1277
  function randString(len) {
1277
1278
  const result = [];
1278
1279
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
@@ -1282,6 +1283,18 @@ function randString(len) {
1282
1283
  }
1283
1284
  return result.join("");
1284
1285
  }
1286
+ function deterministicSessionSecret(seed) {
1287
+ return crypto.createHash("sha256").update(seed).digest("hex");
1288
+ }
1289
+ function getSessionCookieSecret(rootConfig, rootDir) {
1290
+ if (rootConfig.server?.sessionCookieSecret) {
1291
+ return rootConfig.server.sessionCookieSecret;
1292
+ }
1293
+ if (process.env.NODE_ENV === "development") {
1294
+ return deterministicSessionSecret(rootDir);
1295
+ }
1296
+ return randString(36);
1297
+ }
1285
1298
 
1286
1299
  // src/cli/dev.ts
1287
1300
  var __dirname3 = path7.dirname(fileURLToPath3(import.meta.url));
@@ -1358,7 +1371,7 @@ async function createDevServer(options) {
1358
1371
  server.use(rootProjectMiddleware({ rootConfig }));
1359
1372
  server.use(viteMiddleware);
1360
1373
  server.use(hooksMiddleware());
1361
- const sessionCookieSecret = rootConfig.server?.sessionCookieSecret || randString(36);
1374
+ const sessionCookieSecret = getSessionCookieSecret(rootConfig, rootDir);
1362
1375
  server.use(cookieParser(sessionCookieSecret));
1363
1376
  server.use(sessionMiddleware());
1364
1377
  const plugins = rootConfig.plugins || [];
@@ -1733,7 +1746,7 @@ async function createPreviewServer(options) {
1733
1746
  server.use(rootProjectMiddleware({ rootConfig }));
1734
1747
  server.use(await rootPreviewRendererMiddleware({ rootConfig, distDir }));
1735
1748
  server.use(hooksMiddleware());
1736
- const sessionCookieSecret = rootConfig.server?.sessionCookieSecret || randString(36);
1749
+ const sessionCookieSecret = getSessionCookieSecret(rootConfig, rootDir);
1737
1750
  server.use(cookieParser2(sessionCookieSecret));
1738
1751
  server.use(sessionMiddleware());
1739
1752
  const plugins = rootConfig.plugins || [];
@@ -1879,7 +1892,7 @@ async function createProdServer(options) {
1879
1892
  server.use(rootProjectMiddleware({ rootConfig }));
1880
1893
  server.use(await rootProdRendererMiddleware({ rootConfig, distDir }));
1881
1894
  server.use(hooksMiddleware());
1882
- const sessionCookieSecret = rootConfig.server?.sessionCookieSecret || randString(36);
1895
+ const sessionCookieSecret = getSessionCookieSecret(rootConfig, rootDir);
1883
1896
  server.use(cookieParser3(sessionCookieSecret));
1884
1897
  server.use(sessionMiddleware());
1885
1898
  const plugins = rootConfig.plugins || [];
@@ -2085,4 +2098,4 @@ export {
2085
2098
  createProdServer,
2086
2099
  CliRunner
2087
2100
  };
2088
- //# sourceMappingURL=chunk-34TYSSRN.js.map
2101
+ //# sourceMappingURL=chunk-YHTIC7DK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/cli.ts","../src/cli/build.ts","../src/node/element-graph.ts","../src/render/asset-map/build-asset-map.ts","../src/utils/batch.ts","../src/cli/codegen.ts","../src/cli/create-package.ts","../src/cli/dev.ts","../src/middleware/hooks.ts","../src/middleware/redirects.ts","../src/render/asset-map/dev-asset-map.ts","../src/utils/ports.ts","../src/utils/rand.ts","../src/cli/gae-deploy.ts","../src/cli/preview.ts","../src/cli/start.ts"],"sourcesContent":["import {Command, InvalidArgumentError} from 'commander';\nimport {bgGreen, black} from 'kleur/colors';\nimport {build, BuildOptions} from './build.js';\nimport {codegen} from './codegen.js';\nimport {createPackage} from './create-package.js';\nimport {dev, createDevServer} from './dev.js';\nimport {gaeDeploy} from './gae-deploy.js';\nimport {preview, createPreviewServer} from './preview.js';\nimport {start, createProdServer} from './start.js';\n\nclass CliRunner {\n private name: string;\n private version: string;\n\n constructor(name: string, version: string) {\n this.name = name;\n this.version = version;\n }\n\n async run(argv: string[]) {\n const program = new Command('root');\n program.version(this.version);\n program.option('-q, --quiet', 'quiet');\n program.hook('preAction', (cmd) => {\n if (!cmd.opts().quiet) {\n console.log(\n `🥕 ${bgGreen(black(` ${this.name} `))} v${this.version}\\n`\n );\n }\n });\n program\n .command('build [path]')\n .description('generates a static build')\n .option('--ssr-only', 'produce a ssr-only build')\n .option(\n '--mode <mode>',\n 'see: https://vitejs.dev/guide/env-and-mode.html#modes',\n 'production'\n )\n .option(\n '-c, --concurrency <num>',\n 'number of files to build concurrently',\n '10'\n )\n .option(\n '--filter <urlPathRegex>',\n 'builds the url paths that match the given regex, e.g. \"/products/.*\"',\n ''\n )\n .action(build);\n program\n .command('codegen [type] [name]')\n .description('generates boilerplate code')\n .option('--out <outdir>', 'output dir')\n .action(codegen);\n program\n .command('create-package [path]')\n .alias('package')\n .description(\n 'creates a standalone npm package for deployment to various hosting services'\n )\n .option('--target <target>', 'hosting target, i.e. appengine or firebase')\n .option('--out <outdir>', 'output dir')\n .option('--mode <mode>', 'deployment mode, i.e. production or preview')\n .option(\n '--app-yaml <path>',\n 'for appengine targets, path to app.yaml (defaults to \"app.yaml\")'\n )\n .action((rootPackageDir, options) => {\n options.version = this.version;\n createPackage(rootPackageDir, options);\n });\n program\n .command('dev [path]')\n .description('starts the server in development mode')\n .option(\n '--host <host>',\n 'network address the server should listen on, e.g. 127.0.0.1'\n )\n .action(dev);\n program\n .command('gae-deploy <appdir>')\n .description(\n 'appengine deploy utility that can optionally run healthchecks before diverting traffic to the new version and clean up old versions'\n )\n .option('--project <project>', 'GCP project id')\n .option('--prefix <prefix>', 'prefix to append the version')\n .option(\n '--promote',\n 'whether to promote the version (if healthchecks pass)'\n )\n .option(\n '--healthcheck-url <url>',\n 'healthcheck url path (e.g. \"/healthcheck\") which should return a 200 status with the text \"OK\"'\n )\n .option(\n '--max-versions <num>',\n 'the max number of versions to keep',\n numberFlag\n )\n .action(gaeDeploy);\n program\n .command('preview [path]')\n .description('starts the server in preview mode')\n .option(\n '--host <host>',\n 'network address the server should listen on, e.g. 127.0.0.1'\n )\n .action(preview);\n program\n .command('start [path]')\n .description('starts the server in production mode')\n .option(\n '--host <host>',\n 'network address the server should listen on, e.g. 127.0.0.1'\n )\n .action(start);\n await program.parseAsync(argv);\n }\n}\n\nfunction numberFlag(value: string) {\n const num = parseInt(value);\n if (isNaN(num)) {\n throw new InvalidArgumentError(`not a number: ${value}`);\n }\n return num;\n}\n\nexport {\n CliRunner,\n build,\n BuildOptions,\n createPackage,\n dev,\n createDevServer,\n preview,\n createPreviewServer,\n start,\n createProdServer,\n};\n","/* 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, Sitemap} from '../core/types.js';\nimport {getElements} from '../node/element-graph.js';\nimport {bundleRootConfig, 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\nexport interface BuildOptions {\n ssrOnly?: boolean;\n mode?: string;\n concurrency?: string | number;\n filter?: string;\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\n for (const plugin of rootPlugins) {\n if (plugin.hooks?.preBuild) {\n await plugin.hooks.preBuild(rootConfig);\n }\n }\n\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/[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 sourcemap: 'inline',\n },\n ssr: {\n ...viteConfig.ssr,\n target: 'node',\n noExternal: ['@blinkk/root', '@blinkk/root-cms/richtext', ...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/[hash].min.js',\n assetFileNames: 'assets/[hash][extname]',\n chunkFileNames: 'chunks/[hash].min.js',\n sanitizeFileName: sanitizeFileName,\n ...viteConfig?.build?.rollupOptions?.output,\n },\n },\n outDir: path.join(distDir, '.build/routes'),\n ssr: true,\n ssrManifest: false,\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/[hash].min.js',\n assetFileNames: 'assets/[hash][extname]',\n chunkFileNames: 'chunks/[hash].min.js',\n sanitizeFileName: sanitizeFileName,\n ...viteConfig?.build?.rollupOptions?.output,\n },\n },\n outDir: path.join(distDir, '.build/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(\n path.join(distDir, '.build/client/.vite/manifest.json'),\n '{}'\n );\n }\n\n // Bundle the root.config.ts file to dist/root.config.js.\n await bundleRootConfig(rootDir, path.join(distDir, 'root.config.js'));\n\n // Copy CSS files from `dist/.build/routes/**/*.css` to\n // `dist/.build/client/` and flatten the routes manifest to ignore any\n // imported modules. Then add the route assets to the client manifest.\n await copyGlob(\n '**/*.css',\n path.join(distDir, '.build/routes'),\n path.join(distDir, '.build/client')\n );\n const routesManifest = await loadJson<Manifest>(\n path.join(distDir, '.build/routes/.vite/manifest.json')\n );\n const clientManifest = await loadJson<Manifest>(\n path.join(distDir, '.build/client/.vite/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 root's asset map to `dist/.root/manifest.json` for use by the prod\n // SSR server.\n const rootManifest = assetMap.toJson();\n await writeFile(\n path.join(distDir, '.root/manifest.json'),\n JSON.stringify(rootManifest, null, 2)\n );\n\n // Save the element graph to `dist/.root/elements.json` for use by the prod\n // SSR server.\n const elementGraphJson = elementGraph.toJson();\n await writeFile(\n path.join(distDir, '.root/elements.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 const seenAssets = new Set<string>();\n async function copyAssetToDistHtml(assetUrl: string) {\n if (seenAssets.has(assetUrl)) {\n return;\n }\n seenAssets.add(assetUrl);\n const assetRelPath = assetUrl.slice(1);\n const assetFrom = path.join(distDir, '.build/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 // 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 const assetData = rootManifest[src];\n // Only imported css from routes files should be included in build output.\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 const importedCss = assetData.importedCss || [];\n for (const cssAssetUrl of importedCss) {\n await copyAssetToDistHtml(cssAssetUrl);\n }\n return;\n }\n\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\n // Copy assets and any imported css files.\n await copyAssetToDistHtml(assetData.assetUrl);\n const importedCss = assetData.importedCss || [];\n for (const cssAssetUrl of importedCss) {\n await copyAssetToDistHtml(cssAssetUrl);\n }\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 let sitemap = await renderer.getSitemap();\n\n // If the `--filter` flag is passed, build only the paths that match the\n // given regex.\n if (options?.filter) {\n const filterRegex = new RegExp(`^${options.filter}`);\n const filteredSitemap: Sitemap = {};\n Object.entries(sitemap).forEach(([urlPath, sitemapItem]) => {\n if (urlPath.match(filterRegex)) {\n filteredSitemap[urlPath] = sitemapItem;\n }\n });\n sitemap = filteredSitemap;\n }\n\n const sitemapXmlItems: Array<{\n url: string;\n locale: string;\n alts: Array<{locale: string; hreflang: string; url: string}>;\n }> = [];\n if (rootConfig.sitemap && !rootConfig.domain) {\n throw new Error(\n 'missing \"domain\" in root.config.ts, required when using {sitemap: true}'\n );\n }\n const domain = rootConfig.domain!;\n\n console.log('\\nhtml output:');\n const batchSize = Number(options?.concurrency || 10);\n\n await batchAsyncCalls(\n Object.entries(sitemap),\n batchSize,\n async ([urlPath, sitemapItem]) => {\n // If \"excludeDefaultLocaleFromIntlPaths\" is true, ignore /intl/en/... in\n // the SSG build and exclude it from sitemap.xml.\n if (rootConfig.build?.excludeDefaultLocaleFromIntlPaths) {\n const defaultLocale = rootConfig.i18n?.defaultLocale || 'en';\n if (sitemapItem.locale === defaultLocale) {\n return;\n }\n }\n\n try {\n const routeModule = sitemapItem.route.module;\n if (routeModule.getStaticContent) {\n let props: any;\n if (routeModule.getStaticProps) {\n props = await routeModule.getStaticProps({\n rootConfig,\n params: sitemapItem.params,\n });\n if (props?.notFound) {\n return;\n }\n } else {\n props = {rootConfig, params: sitemapItem.params};\n }\n const result = await routeModule.getStaticContent(props);\n let body: string;\n if (typeof result === 'string') {\n body = result;\n } else if (result && typeof result === 'object') {\n body = result.body;\n } else {\n body = '';\n }\n const outFilePath = urlPath.slice(1);\n const outPath = path.join(buildDir, outFilePath);\n await makeDir(path.dirname(outPath));\n await writeFile(outPath, body);\n printFileOutput(fileSize(outPath), 'dist/html/', outFilePath);\n return;\n }\n\n const data = await renderer.renderRoute(sitemapItem.route, {\n routeParams: sitemapItem.params,\n });\n if (data.notFound) {\n return;\n }\n\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 // Save the url to sitemap.xml. Ignore error files (e.g. 404.html).\n if (rootConfig.sitemap && outFilePath.endsWith('index.html')) {\n const sitemapXmlItem: {\n url: string;\n locale: string;\n alts: Array<{locale: string; hreflang: string; url: string}>;\n } = {\n url: `${domain}${urlPath}`,\n locale: sitemapItem.locale,\n alts: [],\n };\n sitemapXmlItems.push(sitemapXmlItem);\n if (sitemapItem.alts) {\n Object.entries(sitemapItem.alts).forEach(([altLocale, item]) => {\n sitemapXmlItem.alts.push({\n url: `${domain}${item.urlPath}`,\n locale: altLocale,\n hreflang: item.hrefLang,\n });\n });\n }\n }\n\n // Render html and save the file to dist/html.\n // TODO(stevenle): consolidate post-build html transformation logic.\n let html = data.html || '';\n if (rootConfig.prettyHtml) {\n html = await htmlPretty(html, rootConfig.prettyHtmlOptions);\n } else if (rootConfig.minifyHtml) {\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(\n {route: sitemapItem.route, params: sitemapItem.params, urlPath},\n e\n );\n throw new Error(\n `BuildError: ${urlPath} (${sitemapItem.route.src}) failed to build.`\n );\n }\n }\n );\n\n // Generate sitemap.xml.\n if (rootConfig.sitemap) {\n const sitemapXmlBuilder: string[] = [];\n sitemapXmlItems.sort((a, b) => a.url.localeCompare(b.url));\n sitemapXmlItems.forEach((item) => {\n sitemapXmlBuilder.push('<url>');\n sitemapXmlBuilder.push(` <loc>${item.url}</loc>`);\n if (item.alts.length > 0) {\n item.alts.sort((a, b) => a.hreflang.localeCompare(b.hreflang));\n item.alts.forEach((alt) => {\n if (item.locale !== alt.locale) {\n sitemapXmlBuilder.push(\n ` <xhtml:link rel=\"alternate\" hreflang=\"${alt.hreflang}\" href=\"${alt.url}\" />`\n );\n }\n });\n }\n sitemapXmlBuilder.push('</url>');\n });\n\n const sitemapXmlLines = [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">',\n ...sitemapXmlBuilder,\n '</urlset>',\n ];\n const sitemapXml = sitemapXmlLines.join('\\n');\n const outPath = path.join(buildDir, 'sitemap.xml');\n await writeFile(outPath, sitemapXml);\n printFileOutput(fileSize(outPath), 'dist/html/', 'sitemap.xml');\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';\nimport glob from 'tiny-glob';\nimport {searchForWorkspaceRoot} from 'vite';\nimport {RootConfig} from '../core/config.js';\nimport {isValidTagName, parseTagNames} from '../utils/elements.js';\nimport {directoryContains, isDirectory, isJsFile} from '../utils/fsutils.js';\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';\nimport {Manifest} from 'vite';\nimport {RootConfig} from '../../core/config.js';\nimport {ElementGraph} from '../../node/element-graph.js';\nimport {isJsFile} from '../../utils/fsutils.js';\nimport {Asset, AssetMap} from './asset-map.js';\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 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 {promises as fs} from 'node:fs';\nimport path from 'node:path';\nimport {fileURLToPath} from 'node:url';\nimport glob from 'tiny-glob';\nimport {dirExists, makeDir, rmDir, writeFile} from '../utils/fsutils.js';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\ninterface CodegenOptions {\n out?: string;\n}\n\ninterface Template {\n read: () => Promise<string>;\n}\n\ntype TemplateMap = Record<string, Template>;\n\nexport async function codegen(\n type: string,\n name: string,\n options?: CodegenOptions\n) {\n const rootDir = path.resolve(process.cwd());\n const project = new Project(rootDir);\n await project.generateCode(type, name, options);\n}\n\nclass Project {\n rootDir: string;\n tplDirs: string[];\n\n constructor(rootDir: string) {\n this.rootDir = rootDir;\n this.tplDirs = [\n path.join(rootDir, 'codegen'),\n path.join(__dirname, '../codegen'),\n ];\n }\n\n async generateCode(type: string, name: string, options?: CodegenOptions) {\n const files = await this.loadFiles(type);\n if (Object.keys(files).length === 0) {\n console.log(`no files in codegen/${type}/*.tpl`);\n return;\n }\n\n // By default, running `root codegen template Foo` outputs to\n // `<rootDir>/templates/Foo`.\n const outname = options?.out || `${type}s`;\n const outdir = path.join(this.rootDir, outname, name);\n if (await dirExists(outdir)) {\n await rmDir(outdir);\n }\n await makeDir(outdir);\n\n for (const tplName in files) {\n const tpl = await files[tplName].read();\n const content = tpl\n .replaceAll('[[name]]', name)\n .replaceAll('[[name:camel_upper]]', toCamelCaseUpper(name));\n const filename = tplName.replace('[name]', name);\n const filepath = path.join(outdir, filename);\n await writeFile(filepath, content);\n console.log(`saved ${filepath}`);\n }\n }\n\n /**\n * Searches the project's \"codegen\" dir (or fallsback to root's \"codegen\" dir)\n * and returns a `TemplateMap` for all files in `codgen/<type>/*.tpl`.\n */\n async loadFiles(type: string): Promise<TemplateMap> {\n for (const tplDir of this.tplDirs) {\n const typeDir = path.join(tplDir, type);\n if (await dirExists(typeDir)) {\n return this.loadTplFiles(typeDir);\n }\n }\n return {};\n }\n\n /**\n * Reads files matching `*.tpl` in a given directory.\n */\n private async loadTplFiles(dirpath: string): Promise<TemplateMap> {\n const tplFiles: TemplateMap = {};\n const files = await glob('*.tpl', {cwd: dirpath});\n for (const filename of files) {\n const filepath = path.join(dirpath, filename);\n // Remove `.tpl`.\n const name = filename.slice(0, -4);\n tplFiles[name] = {\n read: () => fs.readFile(filepath, 'utf-8'),\n };\n }\n return tplFiles;\n }\n}\n\nfunction toCamelCaseUpper(str: string) {\n const segments = str.split('-');\n return segments.map((part) => toTitleCase(part)).join('');\n}\n\nfunction toTitleCase(str: string) {\n const ch = String(str).charAt(0).toUpperCase();\n return `${ch}${str.slice(1)}`;\n}\n","import {promises as fs} from 'node:fs';\nimport path from 'node:path';\nimport {build as esbuild} from 'esbuild';\nimport {flattenPackageDepsFromMonorepo} from '../node/monorepo.js';\nimport {\n copyDir,\n dirExists,\n fileExists,\n loadJson,\n makeDir,\n rmDir,\n writeJson,\n} from '../utils/fsutils.js';\nimport {build as rootBuild} from './build.js';\n\ntype DeployTarget = 'appengine' | 'firebase';\n\ninterface CreatePackageOptions {\n mode?: string;\n out?: string;\n target?: DeployTarget;\n version?: string;\n appYaml?: string;\n}\n\ninterface PeerDependencyMeta {\n optional?: boolean;\n}\n\ninterface PackageJson {\n [key: string]: any;\n scripts?: Record<string, string>;\n dependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n peerDependenciesMeta?: Record<string, PeerDependencyMeta>;\n workspaces?: string[];\n}\n\nexport async function createPackage(\n rootProjectDir?: string,\n options?: CreatePackageOptions\n) {\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 target = options?.target || (await getDefaultTarget(rootDir));\n const outDir = path.resolve(options?.out || target || 'out');\n\n // Build the site in ssr-only mode.\n await rootBuild(rootProjectDir, {ssrOnly: true, mode: mode});\n\n // Create `outDir` and copy the generated `distDir` files to it.\n await rmDir(outDir);\n await makeDir(outDir);\n await copyDir(distDir, path.resolve(outDir, 'dist'));\n\n // Copy the \"collections\" dir if it exists.\n const collectionsDir = path.resolve(rootDir, 'collections');\n if (await dirExists(collectionsDir)) {\n await copyDir(collectionsDir, path.join(outDir, 'collections'));\n }\n\n // Create package.json.\n const packageJson = await generatePackageJson(rootDir, options);\n\n // Set root.js versions.\n if (options?.version && packageJson.dependencies) {\n if (packageJson.dependencies['@blinkk/root']) {\n packageJson.dependencies['@blinkk/root'] = options.version;\n }\n if (packageJson.dependencies['@blinkk/root-cms']) {\n packageJson.dependencies['@blinkk/root-cms'] = options.version;\n }\n if (packageJson.dependencies['@blinkk/root-password-protect']) {\n packageJson.dependencies['@blinkk/root-password-protect'] =\n options.version;\n }\n }\n\n // Run target-specific updates to the output.\n if (target === 'appengine') {\n const appYamlPath = options?.appYaml || path.join(rootDir, 'app.yaml');\n await onAppEngine({packageJson, outDir, appYamlPath});\n } else if (target === 'firebase') {\n await onFirebase({rootDir, packageJson, outDir});\n }\n\n // Save `outDir/package.json`.\n await writeJson(path.resolve(outDir, 'package.json'), packageJson);\n\n console.log('done!');\n console.log(`saved package to ${outDir}`);\n}\n\nasync function getDefaultTarget(rootDir: string): Promise<DeployTarget | null> {\n // Default to firebase if a firebase.json file exists in the root dir.\n const firebaseConfigPath = path.resolve(rootDir, 'firebase.json');\n if (await fileExists(firebaseConfigPath)) {\n return 'firebase';\n }\n\n // Default to appengine.\n const appEngineConfigPath = path.resolve(rootDir, 'app.yaml');\n if (await fileExists(appEngineConfigPath)) {\n return 'appengine';\n }\n\n return null;\n}\n\nasync function generatePackageJson(\n rootDir: string,\n options?: CreatePackageOptions\n): Promise<PackageJson> {\n // Read the package.json.\n const packageJson: PackageJson = await loadJson<any>(\n path.resolve(rootDir, 'package.json')\n );\n\n // Flatten any deps from the monorepo, and remove peerDependencies and\n // devDependencies.\n const allDeps = flattenPackageDepsFromMonorepo(rootDir);\n packageJson.dependencies ??= {} as Record<string, string>;\n for (const depName in allDeps) {\n if (!packageJson.dependencies[depName]) {\n packageJson.dependencies[depName] = allDeps[depName];\n }\n }\n\n Object.entries(packageJson.dependencies).forEach(([depName, depVersion]) => {\n if (depName.startsWith('@blinkk/root') && options?.version) {\n // Replace root version with the current version.\n packageJson.dependencies![depName] = options.version;\n } else if (depVersion.startsWith('workspace:')) {\n // Remove `workspace:` deps.\n delete packageJson.dependencies![depName];\n }\n });\n if (packageJson.peerDependencies) {\n delete packageJson.peerDependencies;\n }\n if (packageJson.devDependencies) {\n delete packageJson.devDependencies;\n }\n\n return packageJson;\n}\n\n/**\n * Called for App Engine targets.\n */\nasync function onAppEngine(options: {\n packageJson: PackageJson;\n outDir: string;\n appYamlPath: string;\n}) {\n const {outDir, packageJson, appYamlPath} = options;\n if (await fileExists(appYamlPath)) {\n await fs.copyFile(appYamlPath, path.resolve(outDir, 'app.yaml'));\n }\n\n // Only include the \"start\" script.\n if (packageJson.scripts?.start) {\n packageJson.scripts = {start: packageJson.scripts.start};\n } else {\n packageJson.scripts = {start: 'root start --host=0.0.0.0'};\n }\n}\n\n/**\n * Called for Firebase Hosting targets.\n */\nasync function onFirebase(options: {\n rootDir: string;\n packageJson: PackageJson;\n outDir: string;\n}) {\n const {rootDir, outDir, packageJson} = options;\n\n // If the outDir is called `functions/` and an index.ts file exists in the\n // root project dir, automatically compile it through esbuild.\n const outBasename = path.basename(outDir);\n if (outBasename === 'functions') {\n const indexTsFile = path.resolve(rootDir, 'index.ts');\n if (await fileExists(indexTsFile)) {\n await bundleTsFile(indexTsFile, path.resolve(outDir, 'index.js'));\n }\n }\n\n // Only include the \"start\" script.\n if (packageJson.scripts?.start) {\n packageJson.scripts = {start: packageJson.scripts.start};\n } else {\n packageJson.scripts = {start: 'root start --host=0.0.0.0'};\n }\n}\n\n/**\n * Compiles a `.ts` file to `.js`.\n */\nexport async function bundleTsFile(srcPath: string, outPath: string) {\n await esbuild({\n entryPoints: [srcPath],\n bundle: true,\n minify: true,\n platform: 'node',\n outfile: outPath,\n sourcemap: 'inline',\n metafile: true,\n format: 'esm',\n plugins: [\n {\n name: 'externalize-deps',\n setup(build: any) {\n build.onResolve({filter: /.*/}, (args: any) => {\n const id = args.path;\n if (id[0] !== '.' && !path.isAbsolute(id)) {\n return {\n external: true,\n };\n }\n return null;\n });\n },\n },\n ],\n });\n}\n","import http from 'node:http';\nimport 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 {ViteDevServer} from 'vite';\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 headersMiddleware,\n rootProjectMiddleware,\n trailingSlashMiddleware,\n} from '../middleware/middleware.js';\nimport {redirectsMiddleware} from '../middleware/redirects.js';\nimport {sessionMiddleware} from '../middleware/session.js';\nimport {getElements, getElementsDirs} from '../node/element-graph.js';\nimport {loadRootConfigWithDeps} 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 {getSessionCookieSecret} 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\n let currentServer: http.Server | null = null;\n let currentViteServer: ViteDevServer | null = null;\n\n async function start() {\n const server = await createDevServer({rootDir, port});\n const rootConfig: RootConfig = server.get('rootConfig');\n const viteServer: ViteDevServer = server.get('viteServer');\n currentViteServer = viteServer;\n\n const basePath = rootConfig.base || '';\n const homePagePath = rootConfig.server?.homePagePath || basePath;\n console.log();\n console.log(`${dim('┃')} project: ${rootDir}`);\n console.log(`${dim('┃')} server: http://${host}:${port}${homePagePath}`);\n if (testCmsEnabled(rootConfig)) {\n console.log(`${dim('┃')} cms: http://${host}:${port}/cms/`);\n }\n console.log(`${dim('┃')} mode: development`);\n console.log();\n currentServer = server.listen(port, host);\n\n // Watch for config changes.\n const rootConfigDependencies: string[] = server.get(\n 'rootConfigDependencies'\n );\n const dependencies = [\n path.resolve(rootDir, 'root.config.ts'),\n ...rootConfigDependencies,\n ];\n viteServer.watcher.add(dependencies);\n viteServer.watcher.on('change', async (file) => {\n if (dependencies.includes(file)) {\n console.log(\n `\\n${dim('┃')} root.config.ts changed. restarting server...`\n );\n await restart();\n }\n });\n }\n\n async function restart() {\n if (currentServer) {\n currentServer.close();\n currentServer = null;\n }\n if (currentViteServer) {\n await currentViteServer.close();\n currentViteServer = null;\n }\n await start();\n }\n\n await start();\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, dependencies} = await loadRootConfigWithDeps(rootDir, {\n command: 'dev',\n });\n const port = options?.port;\n\n const server: Server = express();\n server.set('rootConfig', rootConfig);\n server.set('rootConfigDependencies', dependencies);\n server.disable('x-powered-by');\n\n // Create viteServer.\n const {viteServer, viteMiddleware} = await createViteMiddleware({\n rootConfig,\n port,\n });\n server.set('viteServer', viteServer);\n\n // Inject req context vars.\n server.use(rootProjectMiddleware({rootConfig}));\n server.use(viteMiddleware);\n server.use(hooksMiddleware());\n\n // Session middleware for handling session cookies.\n const sessionCookieSecret = getSessionCookieSecret(rootConfig, rootDir);\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 redirects middlewares.\n if (rootConfig.server?.redirects) {\n server.use(\n redirectsMiddleware({redirects: rootConfig.server.redirects})\n );\n }\n\n // Add http headers middleware.\n if (rootConfig.server?.headers) {\n server.use(headersMiddleware({rootConfig: rootConfig}));\n }\n\n // Add static file middleware.\n const publicDir = path.join(rootDir, 'public');\n if (await dirExists(publicDir)) {\n server.use(rootPublicDirMiddleware({publicDir, viteServer}));\n }\n\n // NOTE: The trailing slash middleware needs to come after public files so\n // that slashes are not appended to public file routes.\n server.use(trailingSlashMiddleware({rootConfig}));\n\n // Add the root.js dev server middlewares.\n server.use(rootDevServerMiddleware());\n\n // Add any custom plugin 404 handlers.\n plugins.forEach((plugin) => {\n if (plugin.handle404) {\n server.use(plugin.handle404);\n }\n });\n\n // Add error handlers.\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 createViteMiddleware(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 const viteMiddleware = async (\n req: Request,\n res: Response,\n next: NextFunction\n ) => {\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 return {viteServer, viteMiddleware};\n}\n\nfunction rootPublicDirMiddleware(options: {\n publicDir: string;\n viteServer: ViteDevServer;\n}) {\n const publicDir = options.publicDir;\n\n // The `{dev: false}` option is used for performance reasons. When dev is set\n // to `true`, every request will traverse the filesystem to check if a\n // matching file exists. Setting it to `false` uses a cache, which can be\n // reloaded whenever a file change is detected in the `public` directory.\n const sirvOptions = {dev: false};\n let handler = sirv(publicDir, sirvOptions);\n\n const reloadPublicDirCache = debounce(() => {\n handler = sirv(publicDir, sirvOptions);\n }, 1000);\n\n function isInPublicDir(changedFilePath: string) {\n const filePath = path.resolve(changedFilePath);\n return filePath.startsWith(publicDir);\n }\n\n const watcher = options.viteServer.watcher;\n watcher.on('all', (event, filepath) => {\n if (isInPublicDir(filepath)) {\n reloadPublicDirCache();\n }\n });\n\n return (req: Request, res: Response, next: NextFunction) => {\n handler(req, res, next);\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\nfunction testCmsEnabled(rootConfig: RootConfig) {\n const plugins = rootConfig.plugins || [];\n return Boolean(plugins.find((plugin) => plugin.name === 'root-cms'));\n}\n\nfunction debounce(fn: (...args: any[]) => any, timeout: number) {\n let timer: NodeJS.Timeout;\n return (...args: any[]) => {\n clearTimeout(timer);\n timer = setTimeout(() => fn(...args), timeout);\n };\n}\n","import {Request, Response, NextFunction} from '../core/types.js';\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 {RootRedirectConfig} from '../core/config.js';\nimport {NextFunction, Request, Response} from '../core/types.js';\nimport {RouteTrie} from '../render/route-trie.js';\n\nexport interface RedirectsMiddlewareOptions {\n redirects: RootRedirectConfig[];\n}\n\n/**\n * Middleware for handling server-side redirects from the `server.redirects`\n * config in `root.config.ts`.\n */\nexport function redirectsMiddleware(options: RedirectsMiddlewareOptions) {\n const routeTrie = new RouteTrie<RootRedirectConfig>();\n const redirects = options.redirects || [];\n redirects.forEach((redirect) => {\n if (!verifyRedirectConfig(redirect)) {\n console.warn('ignoring invalid redirect config:', redirect);\n return;\n }\n routeTrie.add(redirect.source!, redirect);\n });\n\n return (req: Request, res: Response, next: NextFunction) => {\n const [redirect, params] = routeTrie.get(req.path);\n if (redirect) {\n const destination = replaceParams(redirect.destination!, params);\n const code = redirect.type || 302;\n res.setHeader(\n 'cache-control',\n 'no-cache, no-store, max-age=0, must-revalidate'\n );\n res.redirect(code, destination);\n return;\n }\n next();\n };\n}\n\nfunction verifyRedirectConfig(redirect: RootRedirectConfig) {\n if (!redirect.source) {\n return false;\n }\n if (!redirect.source.startsWith('/')) {\n return false;\n }\n if (!redirect.destination) {\n return false;\n }\n if (!testIsRedirectValid(redirect.destination)) {\n return false;\n }\n // TODO(stevenle): verify all destination params exist within source.\n return true;\n}\n\n/**\n * Replaces placeholders in a URL path format string with actual values.\n *\n * @param urlPathFormat The URL path format string containing parameter placeholders in the format `[key]` or `[...key]`.\n * @param params A map of parameter names to their corresponding values.\n * @returns The URL path with all parameter placeholders replaced by their corresponding values.\n */\nfunction replaceParams(urlPathFormat: string, params: Record<string, string>) {\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\n/**\n * Only support full urls (e.g. https://...) and relative paths (e.g. /foo/...).\n */\nfunction testIsRedirectValid(url: string) {\n if (url.startsWith('/')) {\n return true;\n }\n if (url.match(/^https?:\\/\\//)) {\n return true;\n }\n return false;\n}\n","import path from 'node:path';\nimport {ModuleGraph, ModuleNode, searchForWorkspaceRoot} from 'vite';\nimport {RootConfig} from '../../core/config.js';\nimport {directoryContains} from '../../utils/fsutils.js';\nimport {Asset, AssetMap} from './asset-map.js';\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","import crypto from 'node:crypto';\n\nimport {RootConfig} from '../core/config.js';\n\nexport 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\n/**\n * Generates a deterministic session secret based on a seed string (e.g., project path).\n * This ensures the same secret is generated for the same seed across dev server restarts,\n * while still allowing different projects to have unique secrets.\n */\nfunction deterministicSessionSecret(seed: string): string {\n return crypto.createHash('sha256').update(seed).digest('hex');\n}\n\n/**\n * Gets the session cookie secret for the server.\n *\n * Returns the configured session cookie secret, or generates one if not provided:\n * - In development: uses a deterministic secret based on rootDir for session persistence\n * - In production: generates a random secret (sessions won't persist across restarts)\n */\nexport function getSessionCookieSecret(\n rootConfig: RootConfig,\n rootDir: string\n): string | string[] {\n // Use configured secret if provided.\n if (rootConfig.server?.sessionCookieSecret) {\n return rootConfig.server.sessionCookieSecret;\n }\n\n // Use deterministic secret in dev mode for consistent sessions across server restarts.\n if (process.env.NODE_ENV === 'development') {\n return deterministicSessionSecret(rootDir);\n }\n\n return randString(36);\n}\n","import {execSync} from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport yaml from 'js-yaml';\n\nexport interface GaeDeployOptions {\n /** GCP project id. */\n project?: string;\n /** Prefix to append to the version. */\n prefix?: string;\n /** Whether to divert traffic to the new version. */\n promote?: boolean;\n /** If provided, verifies that the given URL path returns a 200 response. */\n healthcheckUrl?: string;\n /** If provided, the latest N versions are preserved, all others are deleted */\n maxVersions?: number;\n}\n\ntype AppYaml = any;\n\ninterface AppVersionInfo {\n service: string;\n id: string;\n traffic_split: number;\n last_deployed_time: {\n datetime: string;\n };\n}\n\nexport async function gaeDeploy(appDir: string, options?: GaeDeployOptions) {\n if (!appDir) {\n throw new Error(\n '[gae-deplopy] Missing app dir, e.g. `root gae-deploy <app dir>`'\n );\n }\n\n const project = options?.project;\n if (!project) {\n throw new Error('[gae-deplopy] Missing: --project');\n }\n\n // Change cwd to the app dir.\n process.chdir(appDir);\n\n const appYamlPath = 'app.yaml';\n if (!fs.existsSync(appYamlPath)) {\n throw new Error(`[gae-deplopy] Missing: ${appYamlPath}`);\n }\n\n // Read the service from `app.yaml` and deploy it.\n const appYaml = yaml.load(fs.readFileSync(appYamlPath, 'utf8')) as AppYaml;\n const service = appYaml.service;\n if (!service) {\n throw new Error(\n '[gae-deploy] Missing service definition. Ensure \"service\" is defined in app.yaml.'\n );\n }\n\n let prefix = options?.prefix;\n if (!prefix) {\n prefix = options?.promote ? 'prod' : 'staging';\n }\n const version = `${prefix}-${getTimestamp()}`;\n if (testVersionTooLong(version, service, project)) {\n throw new Error(`version \"${version}\" should not exceed 63 chars`);\n }\n\n console.log('[gae-deploy] 🚀 starting deployment...');\n\n // If the env_variables has placeholders like `MY_SECRET_TOKEN: '{MY_SECRET_TOKEN}'`,\n // replace with the current env value.\n const appYamlHasPlaceholders = testHasEnvPlaceholders(appYaml);\n let backupAppYaml = '';\n if (appYamlHasPlaceholders) {\n backupAppYaml = updateAppYamlEnv(appYamlPath, appYaml);\n }\n\n // Deploy the app.\n execSync(\n `gcloud app deploy -q --project=${project} --version=${version} --no-promote app.yaml`,\n {stdio: 'inherit'}\n );\n\n // Restore the original app.yaml, if needed.\n if (backupAppYaml) {\n fs.copyFileSync(backupAppYaml, 'app.yaml');\n }\n\n // Check the health of the new version and abort if unhealthy.\n if (options?.healthcheckUrl) {\n const healthcheckPassed = await testHealth(\n project,\n service,\n version,\n options.healthcheckUrl\n );\n if (!healthcheckPassed) {\n throw new Error(\n `[gae-deploy] ❌ health check failed. check logs: \\n${getLogsURL(\n project,\n service,\n version\n )}`\n );\n }\n console.log('[gae-deploy] ✅ health check succeeded!');\n }\n\n if (options?.promote) {\n console.log(`[gae-deploy] promoting version ${version}...`);\n execSync(\n `gcloud app -q --project=${project} services set-traffic ${service} --splits ${version}=1`,\n {stdio: 'inherit'}\n );\n }\n\n if (options?.maxVersions) {\n // List all managed versions.\n const resp = execSync(\n `gcloud app versions list --project ${project} --service ${service} --format json`\n ).toString();\n const versions = JSON.parse(resp.toString()) as AppVersionInfo[];\n const managedVersions = versions\n .filter((appInfo: AppVersionInfo) =>\n testManagedVersion(service, appInfo, prefix)\n )\n .sort(\n (a, b) =>\n new Date(b.last_deployed_time.datetime).getTime() -\n new Date(a.last_deployed_time.datetime).getTime()\n );\n\n console.log(\n `[gae-deploy] 📦 all managed versions (${managedVersions.length}):`\n );\n for (const eachVersion of managedVersions) {\n console.log(` ${eachVersion.id}`);\n }\n\n // Delete the oldest managed versions.\n for (const eachVersion of managedVersions.slice(options.maxVersions - 1)) {\n console.log(`[gae-deploy] ✂️ deleting old version ${eachVersion.id}`);\n execSync(\n `gcloud app versions delete -q --project=${project} --service=${service} ${eachVersion.id}`,\n {stdio: 'inherit'}\n );\n }\n }\n\n console.log(\n `[gae-deploy] ✨ deployment complete\\nversions: ${getVersionsURL(\n project,\n service\n )}`\n );\n}\n\n/**\n * Returns whether a given version name is too long (a subdomain part should not\n * exceed 63 characters).\n */\nfunction testVersionTooLong(version: string, service: string, project: string) {\n const subdomain = `${version}-dot-${service}-dot-${project}`;\n // console.log(subdomain, subdomain.length);\n return subdomain.length > 63;\n}\n\n/** Returns the logs viewer URL in the Google Cloud Console. */\nfunction getLogsURL(project: string, service: string, version: string) {\n return `https://console.cloud.google.com/logs/query;query=resource.type%3D\"gae_app\"%0Aresource.labels.module_id%3D\"${service}\"%0Aresource.labels.version_id%3D\"${version}\"?project=${project}`;\n}\n\n/** Returns the App Engine versions viewer URL in the Google Cloud Console. */\nfunction getVersionsURL(project: string, service: string) {\n return `https://console.cloud.google.com/appengine/versions?project=${project}&serviceId=${service}`;\n}\n\n/**\n * Returns whether the `env_variables` key in app.yaml has placeholders.\n *\n * Example:\n * ```yaml\n * env_variables:\n * MY_SECRET_TOKEN: '{MY_SECRET_TOKEN}'\n * ```\n */\nfunction testHasEnvPlaceholders(appYaml: AppYaml) {\n if (typeof appYaml?.env_variables !== 'object') {\n return false;\n }\n const envVars: Record<string, string> = appYaml.env_variables;\n return Object.values(envVars).some((envValue: string) => {\n return testIsEnvPlaceholder(envValue);\n });\n}\n\nfunction testIsEnvPlaceholder(envValue: any) {\n if (typeof envValue === 'string') {\n return envValue.startsWith('{') && envValue.endsWith('}');\n }\n return false;\n}\n\n/** Updates any placeholders used in environment variables with their values. */\nfunction updateAppYamlEnv(appYamlPath: string, appYaml: AppYaml) {\n // Copy the original app.yaml to a backup file.\n const backupAppYaml = `${appYamlPath}.bak`;\n fs.copyFileSync(appYamlPath, backupAppYaml);\n let content = fs.readFileSync(appYamlPath, 'utf8');\n\n // Replace env_variables placeholders like `MY_SECRET_TOKEN: '{MY_SECRET_TOKEN}'`.\n const envVars: Record<string, string> = appYaml.env_variables;\n Object.entries(envVars).forEach(([envVar, envValue]) => {\n if (testIsEnvPlaceholder(envValue)) {\n const value = process.env[envVar];\n if (!value && content.includes(`{${envVar}}`)) {\n console.warn(`[gae-deploy] Missing environment variable: ${envVar}`);\n content = content.replaceAll(`{${envVar}}`, '');\n } else if (value && content.includes(`{${envVar}}`)) {\n content = content.replaceAll(`{${envVar}}`, value);\n }\n }\n });\n\n fs.writeFileSync(appYamlPath, content, 'utf8');\n return backupAppYaml;\n}\n\n/**\n * Returns a timestamp for the version name, formatted `YYYYMMDDtHHMM`.\n */\nfunction getTimestamp() {\n const pretty = (num: number) => (num + '').padStart(2, '0');\n const date = new Date();\n return `${date.getFullYear()}${pretty(date.getMonth() + 1)}${pretty(\n date.getDate()\n )}t${pretty(date.getHours())}${pretty(date.getMinutes())}`;\n}\n\n/**\n * Returns whether the App Engine service succeeds in handling a health check\n * request.\n */\nexport async function testHealth(\n project: string,\n service: string,\n version: string,\n healthcheckUrl: string\n) {\n if (!healthcheckUrl.startsWith('/')) {\n healthcheckUrl = `/${healthcheckUrl}`;\n }\n const url = `https://${version}-dot-${service}-dot-${project}.appspot.com${healthcheckUrl}`;\n const response = await fetch(url);\n return response.status === 200;\n}\n\n/**\n * Returns whether a version is considered to be managed by this script, and\n * whether it's an \"old\" prod version (e.g. a version that receives no traffic).\n * This script only manages old prod versions.\n */\nfunction testManagedVersion(\n service: string,\n appInfo: AppVersionInfo,\n prefix: string\n) {\n const re = new RegExp(`${prefix}-\\\\d{8}t\\\\d{4}`);\n return (\n appInfo.service === service &&\n re.exec(appInfo.id) &&\n appInfo.traffic_split === 0.0\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.js';\nimport {configureServerPlugins} from '../core/plugin.js';\nimport {Request, Response, NextFunction, Server} from '../core/types.js';\nimport {hooksMiddleware} from '../middleware/hooks.js';\nimport {\n headersMiddleware,\n rootProjectMiddleware,\n trailingSlashMiddleware,\n} from '../middleware/middleware.js';\nimport {redirectsMiddleware} from '../middleware/redirects.js';\nimport {sessionMiddleware} from '../middleware/session.js';\nimport {ElementGraph} from '../node/element-graph.js';\nimport {loadBundledConfig} from '../node/load-config.js';\nimport {\n BuildAssetManifest,\n BuildAssetMap,\n} from '../render/asset-map/build-asset-map.js';\nimport {fileExists, loadJson} from '../utils/fsutils.js';\nimport {getSessionCookieSecret} from '../utils/rand.js';\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 loadBundledConfig(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 = getSessionCookieSecret(rootConfig, rootDir);\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 userMiddlewares.forEach((middleware) => {\n server.use(middleware);\n });\n\n // Add redirects middleware.\n if (rootConfig.server?.redirects) {\n server.use(\n redirectsMiddleware({redirects: rootConfig.server.redirects})\n );\n }\n\n // Add http headers middleware.\n if (rootConfig.server?.headers) {\n server.use(headersMiddleware({rootConfig: rootConfig}));\n }\n\n // Add static file middleware.\n const publicDir = path.join(distDir, 'html');\n server.use(sirv(publicDir, {dev: false}));\n\n // NOTE: The trailing slash middleware needs to come after public files so\n // that slashes are not appended to public file routes.\n server.use(trailingSlashMiddleware({rootConfig}));\n\n // Add the root.js preview server middlewares.\n server.use(rootPreviewServerMiddleware());\n\n // Add any custom plugin 404 handlers.\n plugins.forEach((plugin) => {\n if (plugin.handle404) {\n server.use(plugin.handle404);\n }\n });\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, '.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(distDir, '.root/elements.json');\n if (!(await fileExists(elementGraphJsonPath))) {\n throw new Error(\n `could not find ${elementGraphJsonPath}. run \\`root build\\` before \\`root preview\\`.`\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.renderDevServer500(req, 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.js';\nimport {configureServerPlugins} from '../core/plugin.js';\nimport {Request, Response, NextFunction, Server} from '../core/types.js';\nimport {hooksMiddleware} from '../middleware/hooks.js';\nimport {\n headersMiddleware,\n rootProjectMiddleware,\n trailingSlashMiddleware,\n} from '../middleware/middleware.js';\nimport {redirectsMiddleware} from '../middleware/redirects.js';\nimport {sessionMiddleware} from '../middleware/session.js';\nimport {ElementGraph} from '../node/element-graph.js';\nimport {loadBundledConfig} from '../node/load-config.js';\nimport {\n BuildAssetManifest,\n BuildAssetMap,\n} from '../render/asset-map/build-asset-map.js';\nimport {fileExists, loadJson} from '../utils/fsutils.js';\nimport {getSessionCookieSecret} from '../utils/rand.js';\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 loadBundledConfig(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 = getSessionCookieSecret(rootConfig, rootDir);\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 userMiddlewares.forEach((middleware) => {\n server.use(middleware);\n });\n\n // Add redirects middleware.\n if (rootConfig.server?.redirects) {\n server.use(\n redirectsMiddleware({redirects: rootConfig.server.redirects})\n );\n }\n\n // Add http headers middleware.\n if (rootConfig.server?.headers) {\n server.use(headersMiddleware({rootConfig: rootConfig}));\n }\n\n // Add static file middleware.\n const publicDir = path.join(distDir, 'html');\n server.use(sirv(publicDir, {dev: false}));\n\n // NOTE: The trailing slash middleware needs to come after public files so\n // that slashes are not appended to public file routes.\n server.use(trailingSlashMiddleware({rootConfig}));\n\n // Add the root.js preview server middlewares.\n server.use(rootProdServerMiddleware());\n\n // Add any custom plugin 404 handlers.\n plugins.forEach((plugin) => {\n if (plugin.handle404) {\n server.use(plugin.handle404);\n }\n });\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, '.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(distDir, '.root/elements.json');\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAQ,SAAS,4BAA2B;AAC5C,SAAQ,SAAS,aAAY;;;ACA7B,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;AACjB,OAAO,UAAU;AACjB,SAAQ,8BAA6B;AAgB9B,IAAM,eAAN,MAAM,cAAa;AAAA;AAAA;AAAA;AAAA,EAIf,cAAsD,CAAC;AAAA;AAAA;AAAA;AAAA,EAKxD,OAAiC,CAAC;AAAA,EAE1C,YAAY,aAAqD;AAC/D,SAAK,cAAc;AAAA,EACrB;AAAA,EAEA,SAAS;AACP,eAAW,WAAW,KAA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AAQ,YAAY,EACpB,YAAY,uCAAuC,EACnD;AAAA,MACC;AAAA,MACA;AAAA,IACF,EACC,OAAO,GAAG;AACb,YACG,QAAQ,qBAAqB,EAC7B;AAAA,MACC;AAAA,IACF,EACC,OAAO,uBAAuB,gBAAgB,EAC9C,OAAO,qBAAqB,8BAA8B,EAC1D;AAAA,MACC;AAAA,MACA;AAAA,IACF,EACC;AAAA,MACC;AAAA,MACA;AAAA,IACF,EACC;AAAA,MACC;AAAA,MACA;AAAA,MACA;AAAA,IACF,EACC,OAAO,SAAS;AACnB,YACG,QAAQ,gBAAgB,EACxB,YAAY,mCAAmC,EAC/C;AAAA,MACC;AAAA,MACA;AAAA,IACF,EACC,OAAO,OAAO;AACjB,YACG,QAAQ,cAAc,EACtB,YAAY,sCAAsC,EAClD;AAAA,MACC;AAAA,MACA;AAAA,IACF,EACC,OAAO,KAAK;AACf,UAAM,QAAQ,WAAW,IAAI;AAAA,EAC/B;AACF;AAEA,SAAS,WAAW,OAAe;AACjC,QAAM,MAAM,SAAS,KAAK;AAC1B,MAAI,MAAM,GAAG,GAAG;AACd,UAAM,IAAI,qBAAqB,iBAAiB,KAAK,EAAE;AAAA,EACzD;AACA,SAAO;AACT;","names":["path","glob","fs","path","asset","path","fs","path","glob","importedCss","outFilePath","outPath","fileSize","fs","path","fileURLToPath","glob","__dirname","path","fileURLToPath","glob","fs","fs","path","path","fs","build","path","fileURLToPath","dim","glob","path","searchForWorkspaceRoot","path","searchForWorkspaceRoot","__dirname","path","fileURLToPath","start","dim","glob","fs","path","cookieParser","express","dim","sirv","path","dim","express","cookieParser","sirv","path","compression","cookieParser","express","dim","sirv","path","dim","express","compression","cookieParser","sirv"]}
package/dist/cli.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { S as Server } from './types-B9tb-VO5.js';
1
+ import { S as Server } from './types-Dgm9L6UG.js';
2
2
  import 'express';
3
3
  import 'preact';
4
4
  import 'vite';
package/dist/cli.js CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  dev,
9
9
  preview,
10
10
  start
11
- } from "./chunk-34TYSSRN.js";
11
+ } from "./chunk-YHTIC7DK.js";
12
12
  import "./chunk-N677DHZI.js";
13
13
  import "./chunk-QOA6JQXL.js";
14
14
  import "./chunk-V2WNR3EX.js";
package/dist/core.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { R as Route } from './types-B9tb-VO5.js';
2
- export { j as ConfigureServerHook, k as ConfigureServerOptions, C as ContentSecurityPolicyConfig, v as GetStaticContent, p as GetStaticPaths, G as GetStaticProps, t as Handler, H as HandlerContext, y as HandlerRenderFn, x as HandlerRenderOptions, L as LocaleGroup, M as MultipartFile, N as NextFunction, l as Plugin, P as PluginHooks, r as Request, q as RequestMiddleware, s as Response, d as RootBuildConfig, b as RootConfig, f as RootHeaderConfig, c as RootI18nConfig, e as RootRedirectConfig, g as RootSecurityConfig, h as RootServerConfig, a as RootUserConfig, w as RouteModule, o as RouteParams, S as Server, z as Sitemap, A as SitemapItem, u as StaticContentResult, X as XFrameOptionsConfig, m as configureServerPlugins, i as defineConfig, n as getVitePlugins } from './types-B9tb-VO5.js';
1
+ import { R as Route } from './types-Dgm9L6UG.js';
2
+ export { j as ConfigureServerHook, k as ConfigureServerOptions, C as ContentSecurityPolicyConfig, v as GetStaticContent, p as GetStaticPaths, G as GetStaticProps, t as Handler, H as HandlerContext, y as HandlerRenderFn, x as HandlerRenderOptions, L as LocaleGroup, M as MultipartFile, N as NextFunction, l as Plugin, P as PluginHooks, r as Request, q as RequestMiddleware, s as Response, d as RootBuildConfig, b as RootConfig, f as RootHeaderConfig, c as RootI18nConfig, e as RootRedirectConfig, g as RootSecurityConfig, h as RootServerConfig, a as RootUserConfig, w as RouteModule, o as RouteParams, S as Server, z as Sitemap, A as SitemapItem, u as StaticContentResult, X as XFrameOptionsConfig, m as configureServerPlugins, i as defineConfig, n as getVitePlugins } from './types-Dgm9L6UG.js';
3
3
  import * as preact$1 from 'preact';
4
4
  import { FunctionalComponent, ComponentChildren } from 'preact';
5
5
  import 'express';
package/dist/core.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/config.ts","../src/core/components/Body.tsx","../src/core/components/Head.ts","../src/core/components/Script.ts","../src/core/hooks/useStringParams.tsx","../src/core/hooks/useTranslationsMiddleware.tsx","../src/core/hooks/useTranslations.ts"],"sourcesContent":["import {UserConfig as ViteUserConfig} from 'vite';\nimport {HtmlMinifyOptions} from '../render/html-minify.js';\nimport {HtmlPrettyOptions} from '../render/html-pretty.js';\nimport {Plugin} from './plugin.js';\nimport {RequestMiddleware} from './types.js';\n\nexport interface RootUserConfig {\n /**\n * Canonical domain the website will serve on. Useful for things like the\n * sitemap, SEO tags, etc.\n */\n domain?: string;\n\n /**\n * The base URL path that the site will serve on. Defaults to `/`;\n */\n base?: string;\n\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\".\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 * Build options for the `root build` command.\n */\n build?: RootBuildConfig;\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. This is enabled by default,\n * in order to disable, pass `minifyHtml: false` to root.config.ts.\n */\n minifyHtml?: boolean;\n\n /**\n * Options to pass to html-minifier-terser.\n */\n minifyHtmlOptions?: HtmlMinifyOptions;\n\n /**\n * Whether to pretty print HTML output.\n */\n prettyHtml?: boolean;\n\n /**\n * Options to pass to js-beautify.\n */\n prettyHtmlOptions?: HtmlPrettyOptions;\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 /**\n * Experimental config options. Note: these are subject to change at any time.\n */\n experiments?: {\n /** Whether to render `<script>` tags with `async`. */\n enableScriptAsync?: boolean;\n };\n}\n\nexport type RootConfig = RootUserConfig & {\n rootDir: string;\n};\n\nexport interface LocaleGroup {\n label?: string;\n locales: 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]/[base]/[path]`.\n */\n urlFormat?: string;\n\n /**\n * Localization groups, to help UIs (like Root.js CMS) logically group\n * locales.\n */\n groups?: Record<string, LocaleGroup>;\n}\n\nexport interface RootBuildConfig {\n /**\n * Excludes the `/intl/{defaultLocale}/...` path from the SSG build.\n */\n excludeDefaultLocaleFromIntlPaths?: boolean;\n}\n\nexport interface RootRedirectConfig {\n /**\n * The source path to redirect. Accepts placeholders in the format\n * `[key]` or `[...key]`. Use `[key]` for single segments and\n * `[...key]` for multi-segment wildcards.\n * @example \"/old-path/[id]\" or \"/old-path/[...wildcard]\"\n */\n source: string;\n\n /**\n * The destination to redirect to. Placeholders from the source can\n * optionally be inserted into the destination using the same\n * placeholder format.\n * @example \"/new-path/[id]\" or \"/new-path/[...wildcard]\"\n */\n destination: string;\n\n /**\n * The redirect type (`301` = permanent, `302` = temporary). If unspecified,\n * defaults to `302` (temporary).\n */\n type?: 301 | 302;\n}\n\nexport interface RootHeaderConfig {\n /** A glob pattern match (regex not supported yet). */\n source: string;\n headers: Array<{\n key: string;\n value: string;\n }>;\n}\n\nexport interface ContentSecurityPolicyConfig {\n directives?: Record<string, string[]>;\n reportOnly?: boolean;\n}\n\nexport interface XFrameOptionsConfig {\n action: 'DENY' | 'SAMEORIGIN';\n}\n\nexport interface RootSecurityConfig {\n /**\n * Content-Security-Policy config. If enabled, a nonce is auto-generated\n * for every request and appended to script and stylesheet tags. You can\n * validate your CSP headers using a tool like {@link https://csp-evaluator.withgoogle.com/}.\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP}\n */\n contentSecurityPolicy?: ContentSecurityPolicyConfig | boolean;\n\n /**\n * Strict-Transport-Security config. When enabled, the header value is set\n * to `Strict-Transport-Security: max-age=63072000; includeSubDomains; preload`.\n */\n strictTransportSecurity?: boolean;\n\n /**\n * X-Content-Type-Options config. When enabled, the header value is set to\n * `X-Content-Type-Options: nosniff`.\n */\n xContentTypeOptions?: boolean;\n\n /**\n * X-Frame-Options config. Setting this value to `true` will default the\n * header value to `X-Frame-Options: SAMEORIGIN`.\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options}\n */\n xFrameOptions?: 'DENY' | 'SAMEORIGIN' | boolean;\n\n /**\n * X-XSS-Protection config. When enabled, the header value is set to\n * `X-XSS-Protection: 1; mode=block`.\n */\n xXssProtection?: boolean;\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?: RequestMiddleware[];\n\n /**\n * The `trailingSlash` config allows you to control how the server handles\n * trailing slashes. This config only affects URLs that do not have a file\n * extension (i.e. HTML paths).\n *\n * - When `true`, the server redirects URLs to add a trailing slash\n * - When `false`, the server redirects URLs to remove a trailing slash\n * - When unspecified, the server allows URLs with and without trailing slash\n */\n trailingSlash?: boolean;\n\n /**\n * Cookie secret for the session middleware.\n */\n sessionCookieSecret?: string | string[];\n\n /**\n * List of redirects. Supports optional wildcards.\n *\n * @example\n * ```ts\n * redirects: [\n * {\n * source: '/old-path/[id]',\n * destination: '/new-path/[id]',\n * type: 301,\n * },\n * {\n * source: '/old-path/[...wildcard]',\n * destination: '/new-path/[...wildcard]',\n * },\n * ]\n * ```\n */\n redirects?: RootRedirectConfig[];\n\n /**\n * HTTP headers to add to a response.\n */\n headers?: RootHeaderConfig[];\n\n /**\n * HTTP security settings. By default, all security settings are enabled with\n * commonly used default values.\n */\n security?: RootSecurityConfig;\n\n /**\n * Home page URL path, which is printed when the dev server starts.\n */\n homePagePath?: string;\n}\n\nexport function defineConfig(config: RootUserConfig): RootUserConfig {\n return config;\n}\n","import {ComponentChildren, FunctionalComponent} from 'preact';\nimport {useContext} from 'preact/hooks';\nimport {HTML_CONTEXT} from './Html.js';\n\nexport type BodyProps = preact.JSX.HTMLAttributes<HTMLBodyElement> & {\n children?: ComponentChildren;\n};\n\n/**\n * The `<Body>` component can be used to update attrs in the `<body>` tag.\n *\n * Usage:\n *\n * ```tsx\n * <Body className=\"body\">\n * <h1>Hello world</h1>\n * </Body>\n * ```\n *\n * Output:\n *\n * ```html\n * <body class=\"body\">\n * <h1>Hello world</h1>\n * </body>\n */\nexport const Body: FunctionalComponent<BodyProps> = ({children, ...attrs}) => {\n const context = useContext(HTML_CONTEXT);\n if (!context) {\n throw new Error(\n 'HTML_CONTEXT not found, double-check usage of the <Body> component'\n );\n }\n context.bodyAttrs = attrs;\n return <>{children}</>;\n};\n","import {ComponentChildren, FunctionalComponent} from 'preact';\nimport {useContext} from 'preact/hooks';\nimport {HTML_CONTEXT} from './Html.js';\n\nexport type HeadProps = preact.JSX.HTMLAttributes<HTMLHeadElement> & {\n children?: ComponentChildren;\n};\n\n/**\n * The <Head> component can be used for injecting elements into the HTML head\n * tag from any part of a page. The <Head> can be added via any component or\n * sub-component and will automatically be hoisted to the `<head>` element.\n *\n * Usage:\n *\n * ```tsx\n * <Head>\n * <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\" />\n * </Head>\n * ```\n */\nexport const Head: FunctionalComponent<HeadProps> = ({children, ...attrs}) => {\n const context = useContext(HTML_CONTEXT);\n if (!context) {\n throw new Error(\n 'HTML_CONTEXT not found, double-check usage of the <Head> component'\n );\n }\n context.headComponents.push(children);\n context.headAttrs = attrs;\n return null;\n};\n","import {FunctionalComponent} from 'preact';\nimport {useContext} from 'preact/hooks';\nimport {HTML_CONTEXT} from './Html.js';\n\nexport type ScriptProps = preact.JSX.HTMLAttributes<HTMLScriptElement> & {\n // Cast the \"src\" attr to string. See:\n // https://github.com/blinkk/rootjs/issues/519\n src?: string;\n};\n\n/**\n * The <Script> component is used for rendering any custom script modules. At\n * the moment, the system only pre-renders and bundles files that are in the\n * `/bundles` folder at the root of the project.\n *\n * Usage:\n *\n * ```tsx\n * <Script src=\"/bundles/main.ts\" />\n * ```\n */\nexport const Script: FunctionalComponent<ScriptProps> = (props) => {\n const context = useContext(HTML_CONTEXT);\n if (!context) {\n throw new Error(\n 'HTML_CONTEXT not found, double-check usage of the <Script> component'\n );\n }\n context.scriptDeps.push(props);\n return null;\n};\n","import {ComponentChildren, FunctionalComponent, createContext} from 'preact';\nimport {useContext} from 'preact/hooks';\n\nexport type StringParamsContext = Record<string, string>;\n\nexport const STRING_PARAMS_CONTEXT = createContext<StringParamsContext | null>(\n null\n);\n\nexport interface StringParamsProviderProps {\n value?: StringParamsContext;\n children?: ComponentChildren;\n}\n\nexport const StringParamsProvider: FunctionalComponent<\n StringParamsProviderProps\n> = (props) => {\n // Allow for nested param values from parent content providers.\n const parent = useContext(STRING_PARAMS_CONTEXT) || {};\n const merged = {...parent, ...props.value};\n return (\n <STRING_PARAMS_CONTEXT.Provider value={merged}>\n {props.children}\n </STRING_PARAMS_CONTEXT.Provider>\n );\n};\n\n/**\n * A hook that returns a map of string params, configured via the\n * `StringParamsProvider` context provider. These params are automatically\n * applied to the `useTranslations()` hook.\n *\n *\n * Usage:\n *\n * ```\n * export default function Page() {\n * return (\n * <StringParamsProvider value={{name: 'Alice'}}>\n * <SayHello />\n * </StringParamsProvider>\n * );\n * }\n *\n * function SayHello() {\n * const t = useTranslations();\n * return <h1>{t('Hello, {name}!')}</h1>;\n * }\n * ```\n *\n * This should render `<h1>Hello, Alice!</h1>`.\n */\nexport function useStringParams() {\n return useContext(STRING_PARAMS_CONTEXT) || {};\n}\n","import {ComponentChildren, FunctionalComponent, createContext} from 'preact';\nimport {useContext} from 'preact/hooks';\n\ntype TransformFn = (str: string) => string;\n\nexport interface TranslationMiddleware {\n /** Transform the string before translation lookup. */\n beforeTranslate?: TransformFn;\n /** Transform the string after translation lookup. */\n afterTranslate?: TransformFn;\n /** Transform the string before `{param}` values are replaced. */\n beforeReplaceParams?: TransformFn;\n /** Transform the string after `{param}` values are replaced. */\n afterReplaceParams?: TransformFn;\n}\n\nexport interface TranslationMiddlewareContext {\n beforeTranslateFns: TransformFn[];\n afterTranslateFns: TransformFn[];\n beforeReplaceParamsFns: TransformFn[];\n afterReplaceParamsFns: TransformFn[];\n}\n\nconst TRANSLATION_MIDDLEWARE_CONTEXT =\n createContext<TranslationMiddlewareContext | null>(null);\n\nexport interface TranslationMiddlewareProviderProps {\n value?: TranslationMiddleware;\n children?: ComponentChildren;\n}\n\nexport const TranslationMiddlewareProvider: FunctionalComponent<\n TranslationMiddlewareProviderProps\n> = (props) => {\n const parent = useContext(TRANSLATION_MIDDLEWARE_CONTEXT) || {\n beforeTranslateFns: [],\n afterTranslateFns: [],\n beforeReplaceParamsFns: [],\n afterReplaceParamsFns: [],\n };\n const merged: TranslationMiddlewareContext = {\n beforeTranslateFns: [...parent.beforeTranslateFns],\n afterTranslateFns: [...parent.afterTranslateFns],\n beforeReplaceParamsFns: [...parent.beforeReplaceParamsFns],\n afterReplaceParamsFns: [...parent.afterReplaceParamsFns],\n };\n if (props.value?.beforeTranslate) {\n merged.beforeTranslateFns.push(props.value.beforeTranslate);\n }\n if (props.value?.afterTranslate) {\n merged.afterTranslateFns.push(props.value.afterTranslate);\n }\n if (props.value?.beforeReplaceParams) {\n merged.beforeReplaceParamsFns.push(props.value.beforeReplaceParams);\n }\n if (props.value?.afterReplaceParams) {\n merged.afterReplaceParamsFns.push(props.value.afterReplaceParams);\n }\n return (\n <TRANSLATION_MIDDLEWARE_CONTEXT.Provider value={merged}>\n {props.children}\n </TRANSLATION_MIDDLEWARE_CONTEXT.Provider>\n );\n};\n\nexport function useTranslationMiddleware(): TranslationMiddlewareContext {\n return (\n useContext(TRANSLATION_MIDDLEWARE_CONTEXT) || {\n beforeTranslateFns: [],\n afterTranslateFns: [],\n beforeReplaceParamsFns: [],\n afterReplaceParamsFns: [],\n }\n );\n}\n","import {I18nContext, useI18nContext} from './useI18nContext.js';\nimport {useStringParams} from './useStringParams.js';\nimport {useTranslationMiddleware} from './useTranslationsMiddleware.js';\n\n/**\n * A hook that returns a function that can be used to translate a string, and\n * optionally replace any parameterized values that are surrounded in curly\n * braces.\n *\n * Usage:\n *\n * ```ts\n * const t = useTranslations();\n * t('Hello {name}', {name: 'Bob'});\n * // => 'Bounjour Bob'\n * ```\n */\nexport function useTranslations() {\n // Ignore I18nContext not found error when used with client-side rehydration.\n let i18nContext: I18nContext | null = null;\n try {\n i18nContext = useI18nContext();\n } catch (err) {\n console.warn('I18nContext not found');\n }\n const translations = i18nContext?.translations || {};\n const stringParams = useStringParams();\n const middleware = useTranslationMiddleware();\n\n function t(str: string, params?: Record<string, string | number>): string;\n function t(\n str: string | null | undefined,\n params?: Record<string, string | number>\n ): string | undefined {\n // Suppress verbatim `'undefined'` and `'null'` output, which can occur when\n // using `useTranslations` with undefined values.\n if (typeof str === 'undefined' || str === null) {\n // Return `undefined` to suppress empty props, e.g.\n // <a title={t(undefined)}>Learn more</a>\n return undefined;\n }\n let input = normalizeString(str);\n middleware.beforeTranslateFns.forEach((fn) => {\n input = fn(input);\n });\n let translation = translations[input] ?? input ?? '';\n middleware.afterTranslateFns.forEach((fn) => {\n translation = fn(translation);\n });\n\n // Replace string params, e.g. \"Hello, {name}\".\n middleware.beforeReplaceParamsFns.forEach((fn) => {\n translation = fn(translation);\n });\n if (testHasStringParams(translation)) {\n translation = replaceStringParams(translation, {\n ...stringParams,\n ...params,\n });\n }\n middleware.afterReplaceParamsFns.forEach((fn) => {\n translation = fn(translation);\n });\n\n return translation;\n }\n return t;\n}\n\n/**\n * Cleans a string that's used for translations. Performs the following:\n * - Removes any leading/trailing whitespace\n * - Removes spaces at the end of any line\n */\nexport function normalizeString(str: string) {\n const lines = String(str)\n .trim()\n .split('\\n')\n .map((line) => removeTrailingWhitespace(line));\n return lines.join('\\n');\n}\n\nfunction removeTrailingWhitespace(str: string) {\n return String(str)\n .trimEnd()\n .replace(/&nbsp;$/, '');\n}\n\nfunction testHasStringParams(str: string) {\n return str.includes('{') && str.includes('}');\n}\n\n/**\n * Replaces string placeholder params, e.g.\n *\n * ```\n * replaceStringParams('Hello, {name}!', {name: 'Joe'})\n * // => 'Hello, Joe!'\n * ```\n */\nfunction replaceStringParams(\n str: string,\n params: Record<string, string | number>\n): string {\n return str.replace(/{([^}]+)}/g, (match, key) => {\n if (key in params) {\n return String(params[key]);\n }\n return match;\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkRO,SAAS,aAAa,QAAwC;AACnE,SAAO;AACT;;;ACnRA,SAAQ,kBAAiB;AAiChB;AARF,IAAM,OAAuC,CAAC,EAAC,UAAU,GAAG,MAAK,MAAM;AAC5E,QAAM,UAAU,WAAW,YAAY;AACvC,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,UAAQ,YAAY;AACpB,SAAO,gCAAG,UAAS;AACrB;;;AClCA,SAAQ,cAAAA,mBAAiB;AAoBlB,IAAM,OAAuC,CAAC,EAAC,UAAU,GAAG,MAAK,MAAM;AAC5E,QAAM,UAAUC,YAAW,YAAY;AACvC,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,UAAQ,eAAe,KAAK,QAAQ;AACpC,UAAQ,YAAY;AACpB,SAAO;AACT;;;AC9BA,SAAQ,cAAAC,mBAAiB;AAoBlB,IAAM,SAA2C,CAAC,UAAU;AACjE,QAAM,UAAUC,YAAW,YAAY;AACvC,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,UAAQ,WAAW,KAAK,KAAK;AAC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AS,gBAAgB,KAAa;AAC3C,QAAM,QAAQ,OAAO,GAAG,EACrB,KAAK,EACL,MAAM,IAAI,EACV,IAAI,CAAC,SAAS,yBAAyB,IAAI,CAAC;AAC/C,SAAO,MAAM,KAAK,IAAI;AACxB;AAEA,SAAS,yBAAyB,KAAa;AAC7C,SAAO,OAAO,GAAG,EACd,QAAQ,EACR,QAAQ,WAAW,EAAE;AAC1B;AAEA,SAAS,oBAAoB,KAAa;AACxC,SAAO,IAAI,SAAS,GAAG,KAAK,IAAI,SAAS,GAAG;AAC9C;AAUA,SAAS,oBACP,KACA,QACQ;AACR,SAAO,IAAI,QAAQ,cAAc,CAAC,OAAO,QAAQ;AAC/C,QAAI,OAAO,QAAQ;AACjB,aAAO,OAAO,OAAO,GAAG,CAAC;AAAA,IAC3B;AACA,WAAO;AAAA,EACT,CAAC;AACH;","names":["useContext","useContext","useContext","useContext","useContext","jsx","createContext","useContext","jsx"]}
1
+ {"version":3,"sources":["../src/core/config.ts","../src/core/components/Body.tsx","../src/core/components/Head.ts","../src/core/components/Script.ts","../src/core/hooks/useStringParams.tsx","../src/core/hooks/useTranslationsMiddleware.tsx","../src/core/hooks/useTranslations.ts"],"sourcesContent":["import {UserConfig as ViteUserConfig} from 'vite';\nimport {HtmlMinifyOptions} from '../render/html-minify.js';\nimport {HtmlPrettyOptions} from '../render/html-pretty.js';\nimport {Plugin} from './plugin.js';\nimport {RequestMiddleware} from './types.js';\n\nexport interface RootUserConfig {\n /**\n * Canonical domain the website will serve on. Useful for things like the\n * sitemap, SEO tags, etc.\n */\n domain?: string;\n\n /**\n * The base URL path that the site will serve on. Defaults to `/`;\n */\n base?: string;\n\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\".\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 * Build options for the `root build` command.\n */\n build?: RootBuildConfig;\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. This is enabled by default,\n * in order to disable, pass `minifyHtml: false` to root.config.ts.\n */\n minifyHtml?: boolean;\n\n /**\n * Options to pass to html-minifier-terser.\n */\n minifyHtmlOptions?: HtmlMinifyOptions;\n\n /**\n * Whether to pretty print HTML output.\n */\n prettyHtml?: boolean;\n\n /**\n * Options to pass to js-beautify.\n */\n prettyHtmlOptions?: HtmlPrettyOptions;\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 /**\n * Experimental config options. Note: these are subject to change at any time.\n */\n experiments?: {\n /** Whether to render `<script>` tags with `async`. */\n enableScriptAsync?: boolean;\n };\n}\n\nexport type RootConfig = RootUserConfig & {\n rootDir: string;\n};\n\nexport interface LocaleGroup {\n label?: string;\n locales: 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]/[base]/[path]`.\n */\n urlFormat?: string;\n\n /**\n * Localization groups, to help UIs (like Root.js CMS) logically group\n * locales.\n */\n groups?: Record<string, LocaleGroup>;\n}\n\nexport interface RootBuildConfig {\n /**\n * Excludes the `/intl/{defaultLocale}/...` path from the SSG build.\n */\n excludeDefaultLocaleFromIntlPaths?: boolean;\n}\n\nexport interface RootRedirectConfig {\n /**\n * The source path to redirect. Accepts placeholders in the format\n * `[key]` or `[...key]`. Use `[key]` for single segments and\n * `[...key]` for multi-segment wildcards.\n * @example \"/old-path/[id]\" or \"/old-path/[...wildcard]\"\n */\n source: string;\n\n /**\n * The destination to redirect to. Placeholders from the source can\n * optionally be inserted into the destination using the same\n * placeholder format.\n * @example \"/new-path/[id]\" or \"/new-path/[...wildcard]\"\n */\n destination: string;\n\n /**\n * The redirect type (`301` = permanent, `302` = temporary). If unspecified,\n * defaults to `302` (temporary).\n */\n type?: 301 | 302;\n}\n\nexport interface RootHeaderConfig {\n /** A glob pattern match (regex not supported yet). */\n source: string;\n headers: Array<{\n key: string;\n value: string;\n }>;\n}\n\nexport interface ContentSecurityPolicyConfig {\n directives?: Record<string, string[]>;\n reportOnly?: boolean;\n}\n\nexport interface XFrameOptionsConfig {\n action: 'DENY' | 'SAMEORIGIN';\n}\n\nexport interface RootSecurityConfig {\n /**\n * Content-Security-Policy config. If enabled, a nonce is auto-generated\n * for every request and appended to script and stylesheet tags. You can\n * validate your CSP headers using a tool like {@link https://csp-evaluator.withgoogle.com/}.\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP}\n */\n contentSecurityPolicy?: ContentSecurityPolicyConfig | boolean;\n\n /**\n * Strict-Transport-Security config. When enabled, the header value is set\n * to `Strict-Transport-Security: max-age=63072000; includeSubDomains; preload`.\n */\n strictTransportSecurity?: boolean;\n\n /**\n * X-Content-Type-Options config. When enabled, the header value is set to\n * `X-Content-Type-Options: nosniff`.\n */\n xContentTypeOptions?: boolean;\n\n /**\n * X-Frame-Options config. Setting this value to `true` will default the\n * header value to `X-Frame-Options: SAMEORIGIN`.\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options}\n */\n xFrameOptions?: 'DENY' | 'SAMEORIGIN' | boolean;\n\n /**\n * X-XSS-Protection config. When enabled, the header value is set to\n * `X-XSS-Protection: 1; mode=block`.\n */\n xXssProtection?: boolean;\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?: RequestMiddleware[];\n\n /**\n * The `trailingSlash` config allows you to control how the server handles\n * trailing slashes. This config only affects URLs that do not have a file\n * extension (i.e. HTML paths).\n *\n * - When `true`, the server redirects URLs to add a trailing slash\n * - When `false`, the server redirects URLs to remove a trailing slash\n * - When unspecified, the server allows URLs with and without trailing slash\n */\n trailingSlash?: boolean;\n\n /**\n * Cookie secret for the session middleware.\n *\n * Generate a secure secret with:\n * ```\n * node -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\"\n * ```\n */\n sessionCookieSecret?: string | string[];\n\n /**\n * List of redirects. Supports optional wildcards.\n *\n * @example\n * ```ts\n * redirects: [\n * {\n * source: '/old-path/[id]',\n * destination: '/new-path/[id]',\n * type: 301,\n * },\n * {\n * source: '/old-path/[...wildcard]',\n * destination: '/new-path/[...wildcard]',\n * },\n * ]\n * ```\n */\n redirects?: RootRedirectConfig[];\n\n /**\n * HTTP headers to add to a response.\n */\n headers?: RootHeaderConfig[];\n\n /**\n * HTTP security settings. By default, all security settings are enabled with\n * commonly used default values.\n */\n security?: RootSecurityConfig;\n\n /**\n * Home page URL path, which is printed when the dev server starts.\n */\n homePagePath?: string;\n}\n\nexport function defineConfig(config: RootUserConfig): RootUserConfig {\n return config;\n}\n","import {ComponentChildren, FunctionalComponent} from 'preact';\nimport {useContext} from 'preact/hooks';\nimport {HTML_CONTEXT} from './Html.js';\n\nexport type BodyProps = preact.JSX.HTMLAttributes<HTMLBodyElement> & {\n children?: ComponentChildren;\n};\n\n/**\n * The `<Body>` component can be used to update attrs in the `<body>` tag.\n *\n * Usage:\n *\n * ```tsx\n * <Body className=\"body\">\n * <h1>Hello world</h1>\n * </Body>\n * ```\n *\n * Output:\n *\n * ```html\n * <body class=\"body\">\n * <h1>Hello world</h1>\n * </body>\n */\nexport const Body: FunctionalComponent<BodyProps> = ({children, ...attrs}) => {\n const context = useContext(HTML_CONTEXT);\n if (!context) {\n throw new Error(\n 'HTML_CONTEXT not found, double-check usage of the <Body> component'\n );\n }\n context.bodyAttrs = attrs;\n return <>{children}</>;\n};\n","import {ComponentChildren, FunctionalComponent} from 'preact';\nimport {useContext} from 'preact/hooks';\nimport {HTML_CONTEXT} from './Html.js';\n\nexport type HeadProps = preact.JSX.HTMLAttributes<HTMLHeadElement> & {\n children?: ComponentChildren;\n};\n\n/**\n * The <Head> component can be used for injecting elements into the HTML head\n * tag from any part of a page. The <Head> can be added via any component or\n * sub-component and will automatically be hoisted to the `<head>` element.\n *\n * Usage:\n *\n * ```tsx\n * <Head>\n * <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\" />\n * </Head>\n * ```\n */\nexport const Head: FunctionalComponent<HeadProps> = ({children, ...attrs}) => {\n const context = useContext(HTML_CONTEXT);\n if (!context) {\n throw new Error(\n 'HTML_CONTEXT not found, double-check usage of the <Head> component'\n );\n }\n context.headComponents.push(children);\n context.headAttrs = attrs;\n return null;\n};\n","import {FunctionalComponent} from 'preact';\nimport {useContext} from 'preact/hooks';\nimport {HTML_CONTEXT} from './Html.js';\n\nexport type ScriptProps = preact.JSX.HTMLAttributes<HTMLScriptElement> & {\n // Cast the \"src\" attr to string. See:\n // https://github.com/blinkk/rootjs/issues/519\n src?: string;\n};\n\n/**\n * The <Script> component is used for rendering any custom script modules. At\n * the moment, the system only pre-renders and bundles files that are in the\n * `/bundles` folder at the root of the project.\n *\n * Usage:\n *\n * ```tsx\n * <Script src=\"/bundles/main.ts\" />\n * ```\n */\nexport const Script: FunctionalComponent<ScriptProps> = (props) => {\n const context = useContext(HTML_CONTEXT);\n if (!context) {\n throw new Error(\n 'HTML_CONTEXT not found, double-check usage of the <Script> component'\n );\n }\n context.scriptDeps.push(props);\n return null;\n};\n","import {ComponentChildren, FunctionalComponent, createContext} from 'preact';\nimport {useContext} from 'preact/hooks';\n\nexport type StringParamsContext = Record<string, string>;\n\nexport const STRING_PARAMS_CONTEXT = createContext<StringParamsContext | null>(\n null\n);\n\nexport interface StringParamsProviderProps {\n value?: StringParamsContext;\n children?: ComponentChildren;\n}\n\nexport const StringParamsProvider: FunctionalComponent<\n StringParamsProviderProps\n> = (props) => {\n // Allow for nested param values from parent content providers.\n const parent = useContext(STRING_PARAMS_CONTEXT) || {};\n const merged = {...parent, ...props.value};\n return (\n <STRING_PARAMS_CONTEXT.Provider value={merged}>\n {props.children}\n </STRING_PARAMS_CONTEXT.Provider>\n );\n};\n\n/**\n * A hook that returns a map of string params, configured via the\n * `StringParamsProvider` context provider. These params are automatically\n * applied to the `useTranslations()` hook.\n *\n *\n * Usage:\n *\n * ```\n * export default function Page() {\n * return (\n * <StringParamsProvider value={{name: 'Alice'}}>\n * <SayHello />\n * </StringParamsProvider>\n * );\n * }\n *\n * function SayHello() {\n * const t = useTranslations();\n * return <h1>{t('Hello, {name}!')}</h1>;\n * }\n * ```\n *\n * This should render `<h1>Hello, Alice!</h1>`.\n */\nexport function useStringParams() {\n return useContext(STRING_PARAMS_CONTEXT) || {};\n}\n","import {ComponentChildren, FunctionalComponent, createContext} from 'preact';\nimport {useContext} from 'preact/hooks';\n\ntype TransformFn = (str: string) => string;\n\nexport interface TranslationMiddleware {\n /** Transform the string before translation lookup. */\n beforeTranslate?: TransformFn;\n /** Transform the string after translation lookup. */\n afterTranslate?: TransformFn;\n /** Transform the string before `{param}` values are replaced. */\n beforeReplaceParams?: TransformFn;\n /** Transform the string after `{param}` values are replaced. */\n afterReplaceParams?: TransformFn;\n}\n\nexport interface TranslationMiddlewareContext {\n beforeTranslateFns: TransformFn[];\n afterTranslateFns: TransformFn[];\n beforeReplaceParamsFns: TransformFn[];\n afterReplaceParamsFns: TransformFn[];\n}\n\nconst TRANSLATION_MIDDLEWARE_CONTEXT =\n createContext<TranslationMiddlewareContext | null>(null);\n\nexport interface TranslationMiddlewareProviderProps {\n value?: TranslationMiddleware;\n children?: ComponentChildren;\n}\n\nexport const TranslationMiddlewareProvider: FunctionalComponent<\n TranslationMiddlewareProviderProps\n> = (props) => {\n const parent = useContext(TRANSLATION_MIDDLEWARE_CONTEXT) || {\n beforeTranslateFns: [],\n afterTranslateFns: [],\n beforeReplaceParamsFns: [],\n afterReplaceParamsFns: [],\n };\n const merged: TranslationMiddlewareContext = {\n beforeTranslateFns: [...parent.beforeTranslateFns],\n afterTranslateFns: [...parent.afterTranslateFns],\n beforeReplaceParamsFns: [...parent.beforeReplaceParamsFns],\n afterReplaceParamsFns: [...parent.afterReplaceParamsFns],\n };\n if (props.value?.beforeTranslate) {\n merged.beforeTranslateFns.push(props.value.beforeTranslate);\n }\n if (props.value?.afterTranslate) {\n merged.afterTranslateFns.push(props.value.afterTranslate);\n }\n if (props.value?.beforeReplaceParams) {\n merged.beforeReplaceParamsFns.push(props.value.beforeReplaceParams);\n }\n if (props.value?.afterReplaceParams) {\n merged.afterReplaceParamsFns.push(props.value.afterReplaceParams);\n }\n return (\n <TRANSLATION_MIDDLEWARE_CONTEXT.Provider value={merged}>\n {props.children}\n </TRANSLATION_MIDDLEWARE_CONTEXT.Provider>\n );\n};\n\nexport function useTranslationMiddleware(): TranslationMiddlewareContext {\n return (\n useContext(TRANSLATION_MIDDLEWARE_CONTEXT) || {\n beforeTranslateFns: [],\n afterTranslateFns: [],\n beforeReplaceParamsFns: [],\n afterReplaceParamsFns: [],\n }\n );\n}\n","import {I18nContext, useI18nContext} from './useI18nContext.js';\nimport {useStringParams} from './useStringParams.js';\nimport {useTranslationMiddleware} from './useTranslationsMiddleware.js';\n\n/**\n * A hook that returns a function that can be used to translate a string, and\n * optionally replace any parameterized values that are surrounded in curly\n * braces.\n *\n * Usage:\n *\n * ```ts\n * const t = useTranslations();\n * t('Hello {name}', {name: 'Bob'});\n * // => 'Bounjour Bob'\n * ```\n */\nexport function useTranslations() {\n // Ignore I18nContext not found error when used with client-side rehydration.\n let i18nContext: I18nContext | null = null;\n try {\n i18nContext = useI18nContext();\n } catch (err) {\n console.warn('I18nContext not found');\n }\n const translations = i18nContext?.translations || {};\n const stringParams = useStringParams();\n const middleware = useTranslationMiddleware();\n\n function t(str: string, params?: Record<string, string | number>): string;\n function t(\n str: string | null | undefined,\n params?: Record<string, string | number>\n ): string | undefined {\n // Suppress verbatim `'undefined'` and `'null'` output, which can occur when\n // using `useTranslations` with undefined values.\n if (typeof str === 'undefined' || str === null) {\n // Return `undefined` to suppress empty props, e.g.\n // <a title={t(undefined)}>Learn more</a>\n return undefined;\n }\n let input = normalizeString(str);\n middleware.beforeTranslateFns.forEach((fn) => {\n input = fn(input);\n });\n let translation = translations[input] ?? input ?? '';\n middleware.afterTranslateFns.forEach((fn) => {\n translation = fn(translation);\n });\n\n // Replace string params, e.g. \"Hello, {name}\".\n middleware.beforeReplaceParamsFns.forEach((fn) => {\n translation = fn(translation);\n });\n if (testHasStringParams(translation)) {\n translation = replaceStringParams(translation, {\n ...stringParams,\n ...params,\n });\n }\n middleware.afterReplaceParamsFns.forEach((fn) => {\n translation = fn(translation);\n });\n\n return translation;\n }\n return t;\n}\n\n/**\n * Cleans a string that's used for translations. Performs the following:\n * - Removes any leading/trailing whitespace\n * - Removes spaces at the end of any line\n */\nexport function normalizeString(str: string) {\n const lines = String(str)\n .trim()\n .split('\\n')\n .map((line) => removeTrailingWhitespace(line));\n return lines.join('\\n');\n}\n\nfunction removeTrailingWhitespace(str: string) {\n return String(str)\n .trimEnd()\n .replace(/&nbsp;$/, '');\n}\n\nfunction testHasStringParams(str: string) {\n return str.includes('{') && str.includes('}');\n}\n\n/**\n * Replaces string placeholder params, e.g.\n *\n * ```\n * replaceStringParams('Hello, {name}!', {name: 'Joe'})\n * // => 'Hello, Joe!'\n * ```\n */\nfunction replaceStringParams(\n str: string,\n params: Record<string, string | number>\n): string {\n return str.replace(/{([^}]+)}/g, (match, key) => {\n if (key in params) {\n return String(params[key]);\n }\n return match;\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuRO,SAAS,aAAa,QAAwC;AACnE,SAAO;AACT;;;ACxRA,SAAQ,kBAAiB;AAiChB;AARF,IAAM,OAAuC,CAAC,EAAC,UAAU,GAAG,MAAK,MAAM;AAC5E,QAAM,UAAU,WAAW,YA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AAO;AAAA,IACT;AACA,QAAI,QAAQ,gBAAgB,GAAG;AAC/B,eAAW,mBAAmB,QAAQ,CAAC,OAAO;AAC5C,cAAQ,GAAG,KAAK;AAAA,IAClB,CAAC;AACD,QAAI,cAAc,aAAa,KAAK,KAAK,SAAS;AAClD,eAAW,kBAAkB,QAAQ,CAAC,OAAO;AAC3C,oBAAc,GAAG,WAAW;AAAA,IAC9B,CAAC;AAGD,eAAW,uBAAuB,QAAQ,CAAC,OAAO;AAChD,oBAAc,GAAG,WAAW;AAAA,IAC9B,CAAC;AACD,QAAI,oBAAoB,WAAW,GAAG;AACpC,oBAAc,oBAAoB,aAAa;AAAA,QAC7C,GAAG;AAAA,QACH,GAAG;AAAA,MACL,CAAC;AAAA,IACH;AACA,eAAW,sBAAsB,QAAQ,CAAC,OAAO;AAC/C,oBAAc,GAAG,WAAW;AAAA,IAC9B,CAAC;AAED,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAOO,SAAS,gBAAgB,KAAa;AAC3C,QAAM,QAAQ,OAAO,GAAG,EACrB,KAAK,EACL,MAAM,IAAI,EACV,IAAI,CAAC,SAAS,yBAAyB,IAAI,CAAC;AAC/C,SAAO,MAAM,KAAK,IAAI;AACxB;AAEA,SAAS,yBAAyB,KAAa;AAC7C,SAAO,OAAO,GAAG,EACd,QAAQ,EACR,QAAQ,WAAW,EAAE;AAC1B;AAEA,SAAS,oBAAoB,KAAa;AACxC,SAAO,IAAI,SAAS,GAAG,KAAK,IAAI,SAAS,GAAG;AAC9C;AAUA,SAAS,oBACP,KACA,QACQ;AACR,SAAO,IAAI,QAAQ,cAAc,CAAC,OAAO,QAAQ;AAC/C,QAAI,OAAO,QAAQ;AACjB,aAAO,OAAO,OAAO,GAAG,CAAC;AAAA,IAC3B;AACA,WAAO;AAAA,EACT,CAAC;AACH;","names":["useContext","useContext","useContext","useContext","useContext","jsx","createContext","useContext","jsx"]}
package/dist/functions.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createPreviewServer,
3
3
  createProdServer
4
- } from "./chunk-34TYSSRN.js";
4
+ } from "./chunk-YHTIC7DK.js";
5
5
  import "./chunk-N677DHZI.js";
6
6
  import "./chunk-QOA6JQXL.js";
7
7
  import "./chunk-V2WNR3EX.js";
@@ -1,5 +1,5 @@
1
- import { b as RootConfig, r as Request, s as Response, N as NextFunction } from './types-B9tb-VO5.js';
2
- export { B as SESSION_COOKIE, E as SaveSessionOptions, I as Session, D as SessionMiddlewareOptions, F as sessionMiddleware } from './types-B9tb-VO5.js';
1
+ import { b as RootConfig, r as Request, s as Response, N as NextFunction } from './types-Dgm9L6UG.js';
2
+ export { B as SESSION_COOKIE, E as SaveSessionOptions, I as Session, D as SessionMiddlewareOptions, F as sessionMiddleware } from './types-Dgm9L6UG.js';
3
3
  import { RequestHandler } from 'express';
4
4
  import 'preact';
5
5
  import 'vite';
package/dist/node.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { b as RootConfig } from './types-B9tb-VO5.js';
1
+ import { b as RootConfig } from './types-Dgm9L6UG.js';
2
2
  import { PackageInfo } from 'workspace-tools';
3
3
  import { ViteDevServer } from 'vite';
4
4
  import 'express';
package/dist/render.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { J as Renderer } from './types-B9tb-VO5.js';
1
+ export { J as Renderer } from './types-Dgm9L6UG.js';
2
2
  import 'express';
3
3
  import 'preact';
4
4
  import 'vite';
@@ -292,6 +292,11 @@ interface RootServerConfig {
292
292
  trailingSlash?: boolean;
293
293
  /**
294
294
  * Cookie secret for the session middleware.
295
+ *
296
+ * Generate a secure secret with:
297
+ * ```
298
+ * node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
299
+ * ```
295
300
  */
296
301
  sessionCookieSecret?: string | string[];
297
302
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blinkk/root",
3
- "version": "2.4.9",
3
+ "version": "2.5.1",
4
4
  "author": "s@blinkk.com",
5
5
  "license": "MIT",
6
6
  "engines": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/cli.ts","../src/cli/build.ts","../src/node/element-graph.ts","../src/render/asset-map/build-asset-map.ts","../src/utils/batch.ts","../src/cli/codegen.ts","../src/cli/create-package.ts","../src/cli/dev.ts","../src/middleware/hooks.ts","../src/middleware/redirects.ts","../src/render/asset-map/dev-asset-map.ts","../src/utils/ports.ts","../src/utils/rand.ts","../src/cli/gae-deploy.ts","../src/cli/preview.ts","../src/cli/start.ts"],"sourcesContent":["import {Command, InvalidArgumentError} from 'commander';\nimport {bgGreen, black} from 'kleur/colors';\nimport {build, BuildOptions} from './build.js';\nimport {codegen} from './codegen.js';\nimport {createPackage} from './create-package.js';\nimport {dev, createDevServer} from './dev.js';\nimport {gaeDeploy} from './gae-deploy.js';\nimport {preview, createPreviewServer} from './preview.js';\nimport {start, createProdServer} from './start.js';\n\nclass CliRunner {\n private name: string;\n private version: string;\n\n constructor(name: string, version: string) {\n this.name = name;\n this.version = version;\n }\n\n async run(argv: string[]) {\n const program = new Command('root');\n program.version(this.version);\n program.option('-q, --quiet', 'quiet');\n program.hook('preAction', (cmd) => {\n if (!cmd.opts().quiet) {\n console.log(\n `🥕 ${bgGreen(black(` ${this.name} `))} v${this.version}\\n`\n );\n }\n });\n program\n .command('build [path]')\n .description('generates a static build')\n .option('--ssr-only', 'produce a ssr-only build')\n .option(\n '--mode <mode>',\n 'see: https://vitejs.dev/guide/env-and-mode.html#modes',\n 'production'\n )\n .option(\n '-c, --concurrency <num>',\n 'number of files to build concurrently',\n '10'\n )\n .option(\n '--filter <urlPathRegex>',\n 'builds the url paths that match the given regex, e.g. \"/products/.*\"',\n ''\n )\n .action(build);\n program\n .command('codegen [type] [name]')\n .description('generates boilerplate code')\n .option('--out <outdir>', 'output dir')\n .action(codegen);\n program\n .command('create-package [path]')\n .alias('package')\n .description(\n 'creates a standalone npm package for deployment to various hosting services'\n )\n .option('--target <target>', 'hosting target, i.e. appengine or firebase')\n .option('--out <outdir>', 'output dir')\n .option('--mode <mode>', 'deployment mode, i.e. production or preview')\n .option(\n '--app-yaml <path>',\n 'for appengine targets, path to app.yaml (defaults to \"app.yaml\")'\n )\n .action((rootPackageDir, options) => {\n options.version = this.version;\n createPackage(rootPackageDir, options);\n });\n program\n .command('dev [path]')\n .description('starts the server in development mode')\n .option(\n '--host <host>',\n 'network address the server should listen on, e.g. 127.0.0.1'\n )\n .action(dev);\n program\n .command('gae-deploy <appdir>')\n .description(\n 'appengine deploy utility that can optionally run healthchecks before diverting traffic to the new version and clean up old versions'\n )\n .option('--project <project>', 'GCP project id')\n .option('--prefix <prefix>', 'prefix to append the version')\n .option(\n '--promote',\n 'whether to promote the version (if healthchecks pass)'\n )\n .option(\n '--healthcheck-url <url>',\n 'healthcheck url path (e.g. \"/healthcheck\") which should return a 200 status with the text \"OK\"'\n )\n .option(\n '--max-versions <num>',\n 'the max number of versions to keep',\n numberFlag\n )\n .action(gaeDeploy);\n program\n .command('preview [path]')\n .description('starts the server in preview mode')\n .option(\n '--host <host>',\n 'network address the server should listen on, e.g. 127.0.0.1'\n )\n .action(preview);\n program\n .command('start [path]')\n .description('starts the server in production mode')\n .option(\n '--host <host>',\n 'network address the server should listen on, e.g. 127.0.0.1'\n )\n .action(start);\n await program.parseAsync(argv);\n }\n}\n\nfunction numberFlag(value: string) {\n const num = parseInt(value);\n if (isNaN(num)) {\n throw new InvalidArgumentError(`not a number: ${value}`);\n }\n return num;\n}\n\nexport {\n CliRunner,\n build,\n BuildOptions,\n createPackage,\n dev,\n createDevServer,\n preview,\n createPreviewServer,\n start,\n createProdServer,\n};\n","/* 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, Sitemap} from '../core/types.js';\nimport {getElements} from '../node/element-graph.js';\nimport {bundleRootConfig, 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\nexport interface BuildOptions {\n ssrOnly?: boolean;\n mode?: string;\n concurrency?: string | number;\n filter?: string;\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\n for (const plugin of rootPlugins) {\n if (plugin.hooks?.preBuild) {\n await plugin.hooks.preBuild(rootConfig);\n }\n }\n\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/[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 sourcemap: 'inline',\n },\n ssr: {\n ...viteConfig.ssr,\n target: 'node',\n noExternal: ['@blinkk/root', '@blinkk/root-cms/richtext', ...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/[hash].min.js',\n assetFileNames: 'assets/[hash][extname]',\n chunkFileNames: 'chunks/[hash].min.js',\n sanitizeFileName: sanitizeFileName,\n ...viteConfig?.build?.rollupOptions?.output,\n },\n },\n outDir: path.join(distDir, '.build/routes'),\n ssr: true,\n ssrManifest: false,\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/[hash].min.js',\n assetFileNames: 'assets/[hash][extname]',\n chunkFileNames: 'chunks/[hash].min.js',\n sanitizeFileName: sanitizeFileName,\n ...viteConfig?.build?.rollupOptions?.output,\n },\n },\n outDir: path.join(distDir, '.build/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(\n path.join(distDir, '.build/client/.vite/manifest.json'),\n '{}'\n );\n }\n\n // Bundle the root.config.ts file to dist/root.config.js.\n await bundleRootConfig(rootDir, path.join(distDir, 'root.config.js'));\n\n // Copy CSS files from `dist/.build/routes/**/*.css` to\n // `dist/.build/client/` and flatten the routes manifest to ignore any\n // imported modules. Then add the route assets to the client manifest.\n await copyGlob(\n '**/*.css',\n path.join(distDir, '.build/routes'),\n path.join(distDir, '.build/client')\n );\n const routesManifest = await loadJson<Manifest>(\n path.join(distDir, '.build/routes/.vite/manifest.json')\n );\n const clientManifest = await loadJson<Manifest>(\n path.join(distDir, '.build/client/.vite/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 root's asset map to `dist/.root/manifest.json` for use by the prod\n // SSR server.\n const rootManifest = assetMap.toJson();\n await writeFile(\n path.join(distDir, '.root/manifest.json'),\n JSON.stringify(rootManifest, null, 2)\n );\n\n // Save the element graph to `dist/.root/elements.json` for use by the prod\n // SSR server.\n const elementGraphJson = elementGraph.toJson();\n await writeFile(\n path.join(distDir, '.root/elements.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 const seenAssets = new Set<string>();\n async function copyAssetToDistHtml(assetUrl: string) {\n if (seenAssets.has(assetUrl)) {\n return;\n }\n seenAssets.add(assetUrl);\n const assetRelPath = assetUrl.slice(1);\n const assetFrom = path.join(distDir, '.build/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 // 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 const assetData = rootManifest[src];\n // Only imported css from routes files should be included in build output.\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 const importedCss = assetData.importedCss || [];\n for (const cssAssetUrl of importedCss) {\n await copyAssetToDistHtml(cssAssetUrl);\n }\n return;\n }\n\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\n // Copy assets and any imported css files.\n await copyAssetToDistHtml(assetData.assetUrl);\n const importedCss = assetData.importedCss || [];\n for (const cssAssetUrl of importedCss) {\n await copyAssetToDistHtml(cssAssetUrl);\n }\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 let sitemap = await renderer.getSitemap();\n\n // If the `--filter` flag is passed, build only the paths that match the\n // given regex.\n if (options?.filter) {\n const filterRegex = new RegExp(`^${options.filter}`);\n const filteredSitemap: Sitemap = {};\n Object.entries(sitemap).forEach(([urlPath, sitemapItem]) => {\n if (urlPath.match(filterRegex)) {\n filteredSitemap[urlPath] = sitemapItem;\n }\n });\n sitemap = filteredSitemap;\n }\n\n const sitemapXmlItems: Array<{\n url: string;\n locale: string;\n alts: Array<{locale: string; hreflang: string; url: string}>;\n }> = [];\n if (rootConfig.sitemap && !rootConfig.domain) {\n throw new Error(\n 'missing \"domain\" in root.config.ts, required when using {sitemap: true}'\n );\n }\n const domain = rootConfig.domain!;\n\n console.log('\\nhtml output:');\n const batchSize = Number(options?.concurrency || 10);\n\n await batchAsyncCalls(\n Object.entries(sitemap),\n batchSize,\n async ([urlPath, sitemapItem]) => {\n // If \"excludeDefaultLocaleFromIntlPaths\" is true, ignore /intl/en/... in\n // the SSG build and exclude it from sitemap.xml.\n if (rootConfig.build?.excludeDefaultLocaleFromIntlPaths) {\n const defaultLocale = rootConfig.i18n?.defaultLocale || 'en';\n if (sitemapItem.locale === defaultLocale) {\n return;\n }\n }\n\n try {\n const routeModule = sitemapItem.route.module;\n if (routeModule.getStaticContent) {\n let props: any;\n if (routeModule.getStaticProps) {\n props = await routeModule.getStaticProps({\n rootConfig,\n params: sitemapItem.params,\n });\n if (props?.notFound) {\n return;\n }\n } else {\n props = {rootConfig, params: sitemapItem.params};\n }\n const result = await routeModule.getStaticContent(props);\n let body: string;\n if (typeof result === 'string') {\n body = result;\n } else if (result && typeof result === 'object') {\n body = result.body;\n } else {\n body = '';\n }\n const outFilePath = urlPath.slice(1);\n const outPath = path.join(buildDir, outFilePath);\n await makeDir(path.dirname(outPath));\n await writeFile(outPath, body);\n printFileOutput(fileSize(outPath), 'dist/html/', outFilePath);\n return;\n }\n\n const data = await renderer.renderRoute(sitemapItem.route, {\n routeParams: sitemapItem.params,\n });\n if (data.notFound) {\n return;\n }\n\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 // Save the url to sitemap.xml. Ignore error files (e.g. 404.html).\n if (rootConfig.sitemap && outFilePath.endsWith('index.html')) {\n const sitemapXmlItem: {\n url: string;\n locale: string;\n alts: Array<{locale: string; hreflang: string; url: string}>;\n } = {\n url: `${domain}${urlPath}`,\n locale: sitemapItem.locale,\n alts: [],\n };\n sitemapXmlItems.push(sitemapXmlItem);\n if (sitemapItem.alts) {\n Object.entries(sitemapItem.alts).forEach(([altLocale, item]) => {\n sitemapXmlItem.alts.push({\n url: `${domain}${item.urlPath}`,\n locale: altLocale,\n hreflang: item.hrefLang,\n });\n });\n }\n }\n\n // Render html and save the file to dist/html.\n // TODO(stevenle): consolidate post-build html transformation logic.\n let html = data.html || '';\n if (rootConfig.prettyHtml) {\n html = await htmlPretty(html, rootConfig.prettyHtmlOptions);\n } else if (rootConfig.minifyHtml) {\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(\n {route: sitemapItem.route, params: sitemapItem.params, urlPath},\n e\n );\n throw new Error(\n `BuildError: ${urlPath} (${sitemapItem.route.src}) failed to build.`\n );\n }\n }\n );\n\n // Generate sitemap.xml.\n if (rootConfig.sitemap) {\n const sitemapXmlBuilder: string[] = [];\n sitemapXmlItems.sort((a, b) => a.url.localeCompare(b.url));\n sitemapXmlItems.forEach((item) => {\n sitemapXmlBuilder.push('<url>');\n sitemapXmlBuilder.push(` <loc>${item.url}</loc>`);\n if (item.alts.length > 0) {\n item.alts.sort((a, b) => a.hreflang.localeCompare(b.hreflang));\n item.alts.forEach((alt) => {\n if (item.locale !== alt.locale) {\n sitemapXmlBuilder.push(\n ` <xhtml:link rel=\"alternate\" hreflang=\"${alt.hreflang}\" href=\"${alt.url}\" />`\n );\n }\n });\n }\n sitemapXmlBuilder.push('</url>');\n });\n\n const sitemapXmlLines = [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">',\n ...sitemapXmlBuilder,\n '</urlset>',\n ];\n const sitemapXml = sitemapXmlLines.join('\\n');\n const outPath = path.join(buildDir, 'sitemap.xml');\n await writeFile(outPath, sitemapXml);\n printFileOutput(fileSize(outPath), 'dist/html/', 'sitemap.xml');\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';\nimport glob from 'tiny-glob';\nimport {searchForWorkspaceRoot} from 'vite';\nimport {RootConfig} from '../core/config.js';\nimport {isValidTagName, parseTagNames} from '../utils/elements.js';\nimport {directoryContains, isDirectory, isJsFile} from '../utils/fsutils.js';\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';\nimport {Manifest} from 'vite';\nimport {RootConfig} from '../../core/config.js';\nimport {ElementGraph} from '../../node/element-graph.js';\nimport {isJsFile} from '../../utils/fsutils.js';\nimport {Asset, AssetMap} from './asset-map.js';\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 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 {promises as fs} from 'node:fs';\nimport path from 'node:path';\nimport {fileURLToPath} from 'node:url';\nimport glob from 'tiny-glob';\nimport {dirExists, makeDir, rmDir, writeFile} from '../utils/fsutils.js';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\ninterface CodegenOptions {\n out?: string;\n}\n\ninterface Template {\n read: () => Promise<string>;\n}\n\ntype TemplateMap = Record<string, Template>;\n\nexport async function codegen(\n type: string,\n name: string,\n options?: CodegenOptions\n) {\n const rootDir = path.resolve(process.cwd());\n const project = new Project(rootDir);\n await project.generateCode(type, name, options);\n}\n\nclass Project {\n rootDir: string;\n tplDirs: string[];\n\n constructor(rootDir: string) {\n this.rootDir = rootDir;\n this.tplDirs = [\n path.join(rootDir, 'codegen'),\n path.join(__dirname, '../codegen'),\n ];\n }\n\n async generateCode(type: string, name: string, options?: CodegenOptions) {\n const files = await this.loadFiles(type);\n if (Object.keys(files).length === 0) {\n console.log(`no files in codegen/${type}/*.tpl`);\n return;\n }\n\n // By default, running `root codegen template Foo` outputs to\n // `<rootDir>/templates/Foo`.\n const outname = options?.out || `${type}s`;\n const outdir = path.join(this.rootDir, outname, name);\n if (await dirExists(outdir)) {\n await rmDir(outdir);\n }\n await makeDir(outdir);\n\n for (const tplName in files) {\n const tpl = await files[tplName].read();\n const content = tpl\n .replaceAll('[[name]]', name)\n .replaceAll('[[name:camel_upper]]', toCamelCaseUpper(name));\n const filename = tplName.replace('[name]', name);\n const filepath = path.join(outdir, filename);\n await writeFile(filepath, content);\n console.log(`saved ${filepath}`);\n }\n }\n\n /**\n * Searches the project's \"codegen\" dir (or fallsback to root's \"codegen\" dir)\n * and returns a `TemplateMap` for all files in `codgen/<type>/*.tpl`.\n */\n async loadFiles(type: string): Promise<TemplateMap> {\n for (const tplDir of this.tplDirs) {\n const typeDir = path.join(tplDir, type);\n if (await dirExists(typeDir)) {\n return this.loadTplFiles(typeDir);\n }\n }\n return {};\n }\n\n /**\n * Reads files matching `*.tpl` in a given directory.\n */\n private async loadTplFiles(dirpath: string): Promise<TemplateMap> {\n const tplFiles: TemplateMap = {};\n const files = await glob('*.tpl', {cwd: dirpath});\n for (const filename of files) {\n const filepath = path.join(dirpath, filename);\n // Remove `.tpl`.\n const name = filename.slice(0, -4);\n tplFiles[name] = {\n read: () => fs.readFile(filepath, 'utf-8'),\n };\n }\n return tplFiles;\n }\n}\n\nfunction toCamelCaseUpper(str: string) {\n const segments = str.split('-');\n return segments.map((part) => toTitleCase(part)).join('');\n}\n\nfunction toTitleCase(str: string) {\n const ch = String(str).charAt(0).toUpperCase();\n return `${ch}${str.slice(1)}`;\n}\n","import {promises as fs} from 'node:fs';\nimport path from 'node:path';\nimport {build as esbuild} from 'esbuild';\nimport {flattenPackageDepsFromMonorepo} from '../node/monorepo.js';\nimport {\n copyDir,\n dirExists,\n fileExists,\n loadJson,\n makeDir,\n rmDir,\n writeJson,\n} from '../utils/fsutils.js';\nimport {build as rootBuild} from './build.js';\n\ntype DeployTarget = 'appengine' | 'firebase';\n\ninterface CreatePackageOptions {\n mode?: string;\n out?: string;\n target?: DeployTarget;\n version?: string;\n appYaml?: string;\n}\n\ninterface PeerDependencyMeta {\n optional?: boolean;\n}\n\ninterface PackageJson {\n [key: string]: any;\n scripts?: Record<string, string>;\n dependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n peerDependenciesMeta?: Record<string, PeerDependencyMeta>;\n workspaces?: string[];\n}\n\nexport async function createPackage(\n rootProjectDir?: string,\n options?: CreatePackageOptions\n) {\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 target = options?.target || (await getDefaultTarget(rootDir));\n const outDir = path.resolve(options?.out || target || 'out');\n\n // Build the site in ssr-only mode.\n await rootBuild(rootProjectDir, {ssrOnly: true, mode: mode});\n\n // Create `outDir` and copy the generated `distDir` files to it.\n await rmDir(outDir);\n await makeDir(outDir);\n await copyDir(distDir, path.resolve(outDir, 'dist'));\n\n // Copy the \"collections\" dir if it exists.\n const collectionsDir = path.resolve(rootDir, 'collections');\n if (await dirExists(collectionsDir)) {\n await copyDir(collectionsDir, path.join(outDir, 'collections'));\n }\n\n // Create package.json.\n const packageJson = await generatePackageJson(rootDir, options);\n\n // Set root.js versions.\n if (options?.version && packageJson.dependencies) {\n if (packageJson.dependencies['@blinkk/root']) {\n packageJson.dependencies['@blinkk/root'] = options.version;\n }\n if (packageJson.dependencies['@blinkk/root-cms']) {\n packageJson.dependencies['@blinkk/root-cms'] = options.version;\n }\n if (packageJson.dependencies['@blinkk/root-password-protect']) {\n packageJson.dependencies['@blinkk/root-password-protect'] =\n options.version;\n }\n }\n\n // Run target-specific updates to the output.\n if (target === 'appengine') {\n const appYamlPath = options?.appYaml || path.join(rootDir, 'app.yaml');\n await onAppEngine({packageJson, outDir, appYamlPath});\n } else if (target === 'firebase') {\n await onFirebase({rootDir, packageJson, outDir});\n }\n\n // Save `outDir/package.json`.\n await writeJson(path.resolve(outDir, 'package.json'), packageJson);\n\n console.log('done!');\n console.log(`saved package to ${outDir}`);\n}\n\nasync function getDefaultTarget(rootDir: string): Promise<DeployTarget | null> {\n // Default to firebase if a firebase.json file exists in the root dir.\n const firebaseConfigPath = path.resolve(rootDir, 'firebase.json');\n if (await fileExists(firebaseConfigPath)) {\n return 'firebase';\n }\n\n // Default to appengine.\n const appEngineConfigPath = path.resolve(rootDir, 'app.yaml');\n if (await fileExists(appEngineConfigPath)) {\n return 'appengine';\n }\n\n return null;\n}\n\nasync function generatePackageJson(\n rootDir: string,\n options?: CreatePackageOptions\n): Promise<PackageJson> {\n // Read the package.json.\n const packageJson: PackageJson = await loadJson<any>(\n path.resolve(rootDir, 'package.json')\n );\n\n // Flatten any deps from the monorepo, and remove peerDependencies and\n // devDependencies.\n const allDeps = flattenPackageDepsFromMonorepo(rootDir);\n packageJson.dependencies ??= {} as Record<string, string>;\n for (const depName in allDeps) {\n if (!packageJson.dependencies[depName]) {\n packageJson.dependencies[depName] = allDeps[depName];\n }\n }\n\n Object.entries(packageJson.dependencies).forEach(([depName, depVersion]) => {\n if (depName.startsWith('@blinkk/root') && options?.version) {\n // Replace root version with the current version.\n packageJson.dependencies![depName] = options.version;\n } else if (depVersion.startsWith('workspace:')) {\n // Remove `workspace:` deps.\n delete packageJson.dependencies![depName];\n }\n });\n if (packageJson.peerDependencies) {\n delete packageJson.peerDependencies;\n }\n if (packageJson.devDependencies) {\n delete packageJson.devDependencies;\n }\n\n return packageJson;\n}\n\n/**\n * Called for App Engine targets.\n */\nasync function onAppEngine(options: {\n packageJson: PackageJson;\n outDir: string;\n appYamlPath: string;\n}) {\n const {outDir, packageJson, appYamlPath} = options;\n if (await fileExists(appYamlPath)) {\n await fs.copyFile(appYamlPath, path.resolve(outDir, 'app.yaml'));\n }\n\n // Only include the \"start\" script.\n if (packageJson.scripts?.start) {\n packageJson.scripts = {start: packageJson.scripts.start};\n } else {\n packageJson.scripts = {start: 'root start --host=0.0.0.0'};\n }\n}\n\n/**\n * Called for Firebase Hosting targets.\n */\nasync function onFirebase(options: {\n rootDir: string;\n packageJson: PackageJson;\n outDir: string;\n}) {\n const {rootDir, outDir, packageJson} = options;\n\n // If the outDir is called `functions/` and an index.ts file exists in the\n // root project dir, automatically compile it through esbuild.\n const outBasename = path.basename(outDir);\n if (outBasename === 'functions') {\n const indexTsFile = path.resolve(rootDir, 'index.ts');\n if (await fileExists(indexTsFile)) {\n await bundleTsFile(indexTsFile, path.resolve(outDir, 'index.js'));\n }\n }\n\n // Only include the \"start\" script.\n if (packageJson.scripts?.start) {\n packageJson.scripts = {start: packageJson.scripts.start};\n } else {\n packageJson.scripts = {start: 'root start --host=0.0.0.0'};\n }\n}\n\n/**\n * Compiles a `.ts` file to `.js`.\n */\nexport async function bundleTsFile(srcPath: string, outPath: string) {\n await esbuild({\n entryPoints: [srcPath],\n bundle: true,\n minify: true,\n platform: 'node',\n outfile: outPath,\n sourcemap: 'inline',\n metafile: true,\n format: 'esm',\n plugins: [\n {\n name: 'externalize-deps',\n setup(build: any) {\n build.onResolve({filter: /.*/}, (args: any) => {\n const id = args.path;\n if (id[0] !== '.' && !path.isAbsolute(id)) {\n return {\n external: true,\n };\n }\n return null;\n });\n },\n },\n ],\n });\n}\n","import http from 'node:http';\nimport 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 {ViteDevServer} from 'vite';\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 headersMiddleware,\n rootProjectMiddleware,\n trailingSlashMiddleware,\n} from '../middleware/middleware.js';\nimport {redirectsMiddleware} from '../middleware/redirects.js';\nimport {sessionMiddleware} from '../middleware/session.js';\nimport {getElements, getElementsDirs} from '../node/element-graph.js';\nimport {loadRootConfigWithDeps} 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\n let currentServer: http.Server | null = null;\n let currentViteServer: ViteDevServer | null = null;\n\n async function start() {\n const server = await createDevServer({rootDir, port});\n const rootConfig: RootConfig = server.get('rootConfig');\n const viteServer: ViteDevServer = server.get('viteServer');\n currentViteServer = viteServer;\n\n const basePath = rootConfig.base || '';\n const homePagePath = rootConfig.server?.homePagePath || basePath;\n console.log();\n console.log(`${dim('┃')} project: ${rootDir}`);\n console.log(`${dim('┃')} server: http://${host}:${port}${homePagePath}`);\n if (testCmsEnabled(rootConfig)) {\n console.log(`${dim('┃')} cms: http://${host}:${port}/cms/`);\n }\n console.log(`${dim('┃')} mode: development`);\n console.log();\n currentServer = server.listen(port, host);\n\n // Watch for config changes.\n const rootConfigDependencies: string[] = server.get(\n 'rootConfigDependencies'\n );\n const dependencies = [\n path.resolve(rootDir, 'root.config.ts'),\n ...rootConfigDependencies,\n ];\n viteServer.watcher.add(dependencies);\n viteServer.watcher.on('change', async (file) => {\n if (dependencies.includes(file)) {\n console.log(\n `\\n${dim('┃')} root.config.ts changed. restarting server...`\n );\n await restart();\n }\n });\n }\n\n async function restart() {\n if (currentServer) {\n currentServer.close();\n currentServer = null;\n }\n if (currentViteServer) {\n await currentViteServer.close();\n currentViteServer = null;\n }\n await start();\n }\n\n await start();\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, dependencies} = await loadRootConfigWithDeps(rootDir, {\n command: 'dev',\n });\n const port = options?.port;\n\n const server: Server = express();\n server.set('rootConfig', rootConfig);\n server.set('rootConfigDependencies', dependencies);\n server.disable('x-powered-by');\n\n // Create viteServer.\n const {viteServer, viteMiddleware} = await createViteMiddleware({\n rootConfig,\n port,\n });\n server.set('viteServer', viteServer);\n\n // Inject req context vars.\n server.use(rootProjectMiddleware({rootConfig}));\n server.use(viteMiddleware);\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 redirects middlewares.\n if (rootConfig.server?.redirects) {\n server.use(\n redirectsMiddleware({redirects: rootConfig.server.redirects})\n );\n }\n\n // Add http headers middleware.\n if (rootConfig.server?.headers) {\n server.use(headersMiddleware({rootConfig: rootConfig}));\n }\n\n // Add static file middleware.\n const publicDir = path.join(rootDir, 'public');\n if (await dirExists(publicDir)) {\n server.use(rootPublicDirMiddleware({publicDir, viteServer}));\n }\n\n // NOTE: The trailing slash middleware needs to come after public files so\n // that slashes are not appended to public file routes.\n server.use(trailingSlashMiddleware({rootConfig}));\n\n // Add the root.js dev server middlewares.\n server.use(rootDevServerMiddleware());\n\n // Add any custom plugin 404 handlers.\n plugins.forEach((plugin) => {\n if (plugin.handle404) {\n server.use(plugin.handle404);\n }\n });\n\n // Add error handlers.\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 createViteMiddleware(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 const viteMiddleware = async (\n req: Request,\n res: Response,\n next: NextFunction\n ) => {\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 return {viteServer, viteMiddleware};\n}\n\nfunction rootPublicDirMiddleware(options: {\n publicDir: string;\n viteServer: ViteDevServer;\n}) {\n const publicDir = options.publicDir;\n\n // The `{dev: false}` option is used for performance reasons. When dev is set\n // to `true`, every request will traverse the filesystem to check if a\n // matching file exists. Setting it to `false` uses a cache, which can be\n // reloaded whenever a file change is detected in the `public` directory.\n const sirvOptions = {dev: false};\n let handler = sirv(publicDir, sirvOptions);\n\n const reloadPublicDirCache = debounce(() => {\n handler = sirv(publicDir, sirvOptions);\n }, 1000);\n\n function isInPublicDir(changedFilePath: string) {\n const filePath = path.resolve(changedFilePath);\n return filePath.startsWith(publicDir);\n }\n\n const watcher = options.viteServer.watcher;\n watcher.on('all', (event, filepath) => {\n if (isInPublicDir(filepath)) {\n reloadPublicDirCache();\n }\n });\n\n return (req: Request, res: Response, next: NextFunction) => {\n handler(req, res, next);\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\nfunction testCmsEnabled(rootConfig: RootConfig) {\n const plugins = rootConfig.plugins || [];\n return Boolean(plugins.find((plugin) => plugin.name === 'root-cms'));\n}\n\nfunction debounce(fn: (...args: any[]) => any, timeout: number) {\n let timer: NodeJS.Timeout;\n return (...args: any[]) => {\n clearTimeout(timer);\n timer = setTimeout(() => fn(...args), timeout);\n };\n}\n","import {Request, Response, NextFunction} from '../core/types.js';\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 {RootRedirectConfig} from '../core/config.js';\nimport {NextFunction, Request, Response} from '../core/types.js';\nimport {RouteTrie} from '../render/route-trie.js';\n\nexport interface RedirectsMiddlewareOptions {\n redirects: RootRedirectConfig[];\n}\n\n/**\n * Middleware for handling server-side redirects from the `server.redirects`\n * config in `root.config.ts`.\n */\nexport function redirectsMiddleware(options: RedirectsMiddlewareOptions) {\n const routeTrie = new RouteTrie<RootRedirectConfig>();\n const redirects = options.redirects || [];\n redirects.forEach((redirect) => {\n if (!verifyRedirectConfig(redirect)) {\n console.warn('ignoring invalid redirect config:', redirect);\n return;\n }\n routeTrie.add(redirect.source!, redirect);\n });\n\n return (req: Request, res: Response, next: NextFunction) => {\n const [redirect, params] = routeTrie.get(req.path);\n if (redirect) {\n const destination = replaceParams(redirect.destination!, params);\n const code = redirect.type || 302;\n res.setHeader(\n 'cache-control',\n 'no-cache, no-store, max-age=0, must-revalidate'\n );\n res.redirect(code, destination);\n return;\n }\n next();\n };\n}\n\nfunction verifyRedirectConfig(redirect: RootRedirectConfig) {\n if (!redirect.source) {\n return false;\n }\n if (!redirect.source.startsWith('/')) {\n return false;\n }\n if (!redirect.destination) {\n return false;\n }\n if (!testIsRedirectValid(redirect.destination)) {\n return false;\n }\n // TODO(stevenle): verify all destination params exist within source.\n return true;\n}\n\n/**\n * Replaces placeholders in a URL path format string with actual values.\n *\n * @param urlPathFormat The URL path format string containing parameter placeholders in the format `[key]` or `[...key]`.\n * @param params A map of parameter names to their corresponding values.\n * @returns The URL path with all parameter placeholders replaced by their corresponding values.\n */\nfunction replaceParams(urlPathFormat: string, params: Record<string, string>) {\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\n/**\n * Only support full urls (e.g. https://...) and relative paths (e.g. /foo/...).\n */\nfunction testIsRedirectValid(url: string) {\n if (url.startsWith('/')) {\n return true;\n }\n if (url.match(/^https?:\\/\\//)) {\n return true;\n }\n return false;\n}\n","import path from 'node:path';\nimport {ModuleGraph, ModuleNode, searchForWorkspaceRoot} from 'vite';\nimport {RootConfig} from '../../core/config.js';\nimport {directoryContains} from '../../utils/fsutils.js';\nimport {Asset, AssetMap} from './asset-map.js';\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 {execSync} from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport yaml from 'js-yaml';\n\nexport interface GaeDeployOptions {\n /** GCP project id. */\n project?: string;\n /** Prefix to append to the version. */\n prefix?: string;\n /** Whether to divert traffic to the new version. */\n promote?: boolean;\n /** If provided, verifies that the given URL path returns a 200 response. */\n healthcheckUrl?: string;\n /** If provided, the latest N versions are preserved, all others are deleted */\n maxVersions?: number;\n}\n\ntype AppYaml = any;\n\ninterface AppVersionInfo {\n service: string;\n id: string;\n traffic_split: number;\n last_deployed_time: {\n datetime: string;\n };\n}\n\nexport async function gaeDeploy(appDir: string, options?: GaeDeployOptions) {\n if (!appDir) {\n throw new Error(\n '[gae-deplopy] Missing app dir, e.g. `root gae-deploy <app dir>`'\n );\n }\n\n const project = options?.project;\n if (!project) {\n throw new Error('[gae-deplopy] Missing: --project');\n }\n\n // Change cwd to the app dir.\n process.chdir(appDir);\n\n const appYamlPath = 'app.yaml';\n if (!fs.existsSync(appYamlPath)) {\n throw new Error(`[gae-deplopy] Missing: ${appYamlPath}`);\n }\n\n // Read the service from `app.yaml` and deploy it.\n const appYaml = yaml.load(fs.readFileSync(appYamlPath, 'utf8')) as AppYaml;\n const service = appYaml.service;\n if (!service) {\n throw new Error(\n '[gae-deploy] Missing service definition. Ensure \"service\" is defined in app.yaml.'\n );\n }\n\n let prefix = options?.prefix;\n if (!prefix) {\n prefix = options?.promote ? 'prod' : 'staging';\n }\n const version = `${prefix}-${getTimestamp()}`;\n if (testVersionTooLong(version, service, project)) {\n throw new Error(`version \"${version}\" should not exceed 63 chars`);\n }\n\n console.log('[gae-deploy] 🚀 starting deployment...');\n\n // If the env_variables has placeholders like `MY_SECRET_TOKEN: '{MY_SECRET_TOKEN}'`,\n // replace with the current env value.\n const appYamlHasPlaceholders = testHasEnvPlaceholders(appYaml);\n let backupAppYaml = '';\n if (appYamlHasPlaceholders) {\n backupAppYaml = updateAppYamlEnv(appYamlPath, appYaml);\n }\n\n // Deploy the app.\n execSync(\n `gcloud app deploy -q --project=${project} --version=${version} --no-promote app.yaml`,\n {stdio: 'inherit'}\n );\n\n // Restore the original app.yaml, if needed.\n if (backupAppYaml) {\n fs.copyFileSync(backupAppYaml, 'app.yaml');\n }\n\n // Check the health of the new version and abort if unhealthy.\n if (options?.healthcheckUrl) {\n const healthcheckPassed = await testHealth(\n project,\n service,\n version,\n options.healthcheckUrl\n );\n if (!healthcheckPassed) {\n throw new Error(\n `[gae-deploy] ❌ health check failed. check logs: \\n${getLogsURL(\n project,\n service,\n version\n )}`\n );\n }\n console.log('[gae-deploy] ✅ health check succeeded!');\n }\n\n if (options?.promote) {\n console.log(`[gae-deploy] promoting version ${version}...`);\n execSync(\n `gcloud app -q --project=${project} services set-traffic ${service} --splits ${version}=1`,\n {stdio: 'inherit'}\n );\n }\n\n if (options?.maxVersions) {\n // List all managed versions.\n const resp = execSync(\n `gcloud app versions list --project ${project} --service ${service} --format json`\n ).toString();\n const versions = JSON.parse(resp.toString()) as AppVersionInfo[];\n const managedVersions = versions\n .filter((appInfo: AppVersionInfo) =>\n testManagedVersion(service, appInfo, prefix)\n )\n .sort(\n (a, b) =>\n new Date(b.last_deployed_time.datetime).getTime() -\n new Date(a.last_deployed_time.datetime).getTime()\n );\n\n console.log(\n `[gae-deploy] 📦 all managed versions (${managedVersions.length}):`\n );\n for (const eachVersion of managedVersions) {\n console.log(` ${eachVersion.id}`);\n }\n\n // Delete the oldest managed versions.\n for (const eachVersion of managedVersions.slice(options.maxVersions - 1)) {\n console.log(`[gae-deploy] ✂️ deleting old version ${eachVersion.id}`);\n execSync(\n `gcloud app versions delete -q --project=${project} --service=${service} ${eachVersion.id}`,\n {stdio: 'inherit'}\n );\n }\n }\n\n console.log(\n `[gae-deploy] ✨ deployment complete\\nversions: ${getVersionsURL(\n project,\n service\n )}`\n );\n}\n\n/**\n * Returns whether a given version name is too long (a subdomain part should not\n * exceed 63 characters).\n */\nfunction testVersionTooLong(version: string, service: string, project: string) {\n const subdomain = `${version}-dot-${service}-dot-${project}`;\n // console.log(subdomain, subdomain.length);\n return subdomain.length > 63;\n}\n\n/** Returns the logs viewer URL in the Google Cloud Console. */\nfunction getLogsURL(project: string, service: string, version: string) {\n return `https://console.cloud.google.com/logs/query;query=resource.type%3D\"gae_app\"%0Aresource.labels.module_id%3D\"${service}\"%0Aresource.labels.version_id%3D\"${version}\"?project=${project}`;\n}\n\n/** Returns the App Engine versions viewer URL in the Google Cloud Console. */\nfunction getVersionsURL(project: string, service: string) {\n return `https://console.cloud.google.com/appengine/versions?project=${project}&serviceId=${service}`;\n}\n\n/**\n * Returns whether the `env_variables` key in app.yaml has placeholders.\n *\n * Example:\n * ```yaml\n * env_variables:\n * MY_SECRET_TOKEN: '{MY_SECRET_TOKEN}'\n * ```\n */\nfunction testHasEnvPlaceholders(appYaml: AppYaml) {\n if (typeof appYaml?.env_variables !== 'object') {\n return false;\n }\n const envVars: Record<string, string> = appYaml.env_variables;\n return Object.values(envVars).some((envValue: string) => {\n return testIsEnvPlaceholder(envValue);\n });\n}\n\nfunction testIsEnvPlaceholder(envValue: any) {\n if (typeof envValue === 'string') {\n return envValue.startsWith('{') && envValue.endsWith('}');\n }\n return false;\n}\n\n/** Updates any placeholders used in environment variables with their values. */\nfunction updateAppYamlEnv(appYamlPath: string, appYaml: AppYaml) {\n // Copy the original app.yaml to a backup file.\n const backupAppYaml = `${appYamlPath}.bak`;\n fs.copyFileSync(appYamlPath, backupAppYaml);\n let content = fs.readFileSync(appYamlPath, 'utf8');\n\n // Replace env_variables placeholders like `MY_SECRET_TOKEN: '{MY_SECRET_TOKEN}'`.\n const envVars: Record<string, string> = appYaml.env_variables;\n Object.entries(envVars).forEach(([envVar, envValue]) => {\n if (testIsEnvPlaceholder(envValue)) {\n const value = process.env[envVar];\n if (!value && content.includes(`{${envVar}}`)) {\n console.warn(`[gae-deploy] Missing environment variable: ${envVar}`);\n content = content.replaceAll(`{${envVar}}`, '');\n } else if (value && content.includes(`{${envVar}}`)) {\n content = content.replaceAll(`{${envVar}}`, value);\n }\n }\n });\n\n fs.writeFileSync(appYamlPath, content, 'utf8');\n return backupAppYaml;\n}\n\n/**\n * Returns a timestamp for the version name, formatted `YYYYMMDDtHHMM`.\n */\nfunction getTimestamp() {\n const pretty = (num: number) => (num + '').padStart(2, '0');\n const date = new Date();\n return `${date.getFullYear()}${pretty(date.getMonth() + 1)}${pretty(\n date.getDate()\n )}t${pretty(date.getHours())}${pretty(date.getMinutes())}`;\n}\n\n/**\n * Returns whether the App Engine service succeeds in handling a health check\n * request.\n */\nexport async function testHealth(\n project: string,\n service: string,\n version: string,\n healthcheckUrl: string\n) {\n if (!healthcheckUrl.startsWith('/')) {\n healthcheckUrl = `/${healthcheckUrl}`;\n }\n const url = `https://${version}-dot-${service}-dot-${project}.appspot.com${healthcheckUrl}`;\n const response = await fetch(url);\n return response.status === 200;\n}\n\n/**\n * Returns whether a version is considered to be managed by this script, and\n * whether it's an \"old\" prod version (e.g. a version that receives no traffic).\n * This script only manages old prod versions.\n */\nfunction testManagedVersion(\n service: string,\n appInfo: AppVersionInfo,\n prefix: string\n) {\n const re = new RegExp(`${prefix}-\\\\d{8}t\\\\d{4}`);\n return (\n appInfo.service === service &&\n re.exec(appInfo.id) &&\n appInfo.traffic_split === 0.0\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.js';\nimport {configureServerPlugins} from '../core/plugin.js';\nimport {Request, Response, NextFunction, Server} from '../core/types.js';\nimport {hooksMiddleware} from '../middleware/hooks.js';\nimport {\n headersMiddleware,\n rootProjectMiddleware,\n trailingSlashMiddleware,\n} from '../middleware/middleware.js';\nimport {redirectsMiddleware} from '../middleware/redirects.js';\nimport {sessionMiddleware} from '../middleware/session.js';\nimport {ElementGraph} from '../node/element-graph.js';\nimport {loadBundledConfig} from '../node/load-config.js';\nimport {\n BuildAssetManifest,\n BuildAssetMap,\n} from '../render/asset-map/build-asset-map.js';\nimport {fileExists, loadJson} from '../utils/fsutils.js';\nimport {randString} from '../utils/rand.js';\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 loadBundledConfig(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 await 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 redirects middleware.\n if (rootConfig.server?.redirects) {\n server.use(\n redirectsMiddleware({redirects: rootConfig.server.redirects})\n );\n }\n\n // Add http headers middleware.\n if (rootConfig.server?.headers) {\n server.use(headersMiddleware({rootConfig: rootConfig}));\n }\n\n // Add static file middleware.\n const publicDir = path.join(distDir, 'html');\n server.use(sirv(publicDir, {dev: false}));\n\n // NOTE: The trailing slash middleware needs to come after public files so\n // that slashes are not appended to public file routes.\n server.use(trailingSlashMiddleware({rootConfig}));\n\n // Add the root.js preview server middlewares.\n server.use(rootPreviewServerMiddleware());\n\n // Add any custom plugin 404 handlers.\n plugins.forEach((plugin) => {\n if (plugin.handle404) {\n server.use(plugin.handle404);\n }\n });\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, '.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(distDir, '.root/elements.json');\n if (!(await fileExists(elementGraphJsonPath))) {\n throw new Error(\n `could not find ${elementGraphJsonPath}. run \\`root build\\` before \\`root preview\\`.`\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.renderDevServer500(req, 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.js';\nimport {configureServerPlugins} from '../core/plugin.js';\nimport {Request, Response, NextFunction, Server} from '../core/types.js';\nimport {hooksMiddleware} from '../middleware/hooks.js';\nimport {\n headersMiddleware,\n rootProjectMiddleware,\n trailingSlashMiddleware,\n} from '../middleware/middleware.js';\nimport {redirectsMiddleware} from '../middleware/redirects.js';\nimport {sessionMiddleware} from '../middleware/session.js';\nimport {ElementGraph} from '../node/element-graph.js';\nimport {loadBundledConfig} from '../node/load-config.js';\nimport {\n BuildAssetManifest,\n BuildAssetMap,\n} from '../render/asset-map/build-asset-map.js';\nimport {fileExists, loadJson} from '../utils/fsutils.js';\nimport {randString} from '../utils/rand.js';\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 loadBundledConfig(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 await 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 redirects middleware.\n if (rootConfig.server?.redirects) {\n server.use(\n redirectsMiddleware({redirects: rootConfig.server.redirects})\n );\n }\n\n // Add http headers middleware.\n if (rootConfig.server?.headers) {\n server.use(headersMiddleware({rootConfig: rootConfig}));\n }\n\n // Add static file middleware.\n const publicDir = path.join(distDir, 'html');\n server.use(sirv(publicDir, {dev: false}));\n\n // NOTE: The trailing slash middleware needs to come after public files so\n // that slashes are not appended to public file routes.\n server.use(trailingSlashMiddleware({rootConfig}));\n\n // Add the root.js preview server middlewares.\n server.use(rootProdServerMiddleware());\n\n // Add any custom plugin 404 handlers.\n plugins.forEach((plugin) => {\n if (plugin.handle404) {\n server.use(plugin.handle404);\n }\n });\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, '.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(distDir, '.root/elements.json');\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAQ,SAAS,4BAA2B;AAC5C,SAAQ,SAAS,aAAY;;;ACA7B,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;AACjB,OAAO,UAAU;AACjB,SAAQ,8BAA6B;AAgB9B,IAAM,eAAN,MAAM,cAAa;AAAA;AAAA;AAAA;AAAA,EAIf,cAAsD,CAAC;AAAA;AAAA;AAAA;AAAA,EAKxD,OAAiC,CAAC;AAAA,EAE1C,YAAY,aAAqD;AAC/D,SAAK,cAAc;AAAA,EACrB;AAAA,E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A;AAAA,IACF,EACC;AAAA,MACC;AAAA,MACA;AAAA,MACA;AAAA,IACF,EACC,OAAO,SAAS;AACnB,YACG,QAAQ,gBAAgB,EACxB,YAAY,mCAAmC,EAC/C;AAAA,MACC;AAAA,MACA;AAAA,IACF,EACC,OAAO,OAAO;AACjB,YACG,QAAQ,cAAc,EACtB,YAAY,sCAAsC,EAClD;AAAA,MACC;AAAA,MACA;AAAA,IACF,EACC,OAAO,KAAK;AACf,UAAM,QAAQ,WAAW,IAAI;AAAA,EAC/B;AACF;AAEA,SAAS,WAAW,OAAe;AACjC,QAAM,MAAM,SAAS,KAAK;AAC1B,MAAI,MAAM,GAAG,GAAG;AACd,UAAM,IAAI,qBAAqB,iBAAiB,KAAK,EAAE;AAAA,EACzD;AACA,SAAO;AACT;","names":["path","glob","fs","path","asset","path","fs","path","glob","importedCss","outFilePath","outPath","fileSize","fs","path","fileURLToPath","glob","__dirname","path","fileURLToPath","glob","fs","fs","path","path","fs","build","path","fileURLToPath","dim","glob","path","searchForWorkspaceRoot","path","searchForWorkspaceRoot","__dirname","path","fileURLToPath","start","dim","glob","fs","path","cookieParser","express","dim","sirv","path","dim","express","cookieParser","sirv","path","compression","cookieParser","express","dim","sirv","path","dim","express","compression","cookieParser","sirv"]}