@staticbolt/core 1.0.0-beta.31 → 1.0.0-beta.32
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.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["#depsMap","#visiting","#app","#root","#collectPackageMetadataDeps","#collect","#resolveSource","c","bundleFunction","traverse","normalizePackageName","generator","resolveStaticValue","resolveStaticValue","c","#queue","#workers","#waiting","#workerUrl","#concurrency","#onResult","#onFailure","#keepWorking","#wake","#draining","#failure","#work","#waitForWork","#send","#runs","#exports","#context","#options","#run","#readJson","#resolve","#compile","#require","embeddedLanguages","embeddedLanguages","#app","#loaded","#bundleAbsolutePath","#entries","#occurrences","#diagnostics","#reportedNodes","#visit","#assemble","#noteCharset","#warn","#planImport","#hasKeptImports","#resolve","#error","#load","#loadFromDisk","#charsetParams","#report","#nodesOf","placeholderRe","executeExpression","functionCache","htmlData","embeddedLanguages","htmlData","embeddedLanguages","parse","placeholderRe","z","parseYaml","sleep","#configPath","#configName","#projectDirectory","#overrides","#config","#app","#createApp","#configModified","#modifiedTime","#queueRestart","#restartQueue","#restartIfModified","#latestChange","#restart","#loadNextConfig","#reusedPlugins"],"sources":["../../src/helpers/find-dependencies.ts","../../src/plugins/analyze-output/analyze-output-plugin.ts","../../src/plugins/bundle-packages/bundle-esbuild.ts","../../src/plugins/bundle-packages/collect-specifiers.ts","../../src/plugins/bundle-packages/helpers.ts","../../src/plugins/bundle-packages/bundle-packages-plugin.ts","../../src/plugins/convert-images/convert-images-plugin.ts","../../src/plugins/copy-assets/copy-assets-plugin.ts","../../src/plugins/custom-ease/easing-functions/ease-utilities.ts","../../src/plugins/custom-ease/easing-functions/ease.ts","../../src/plugins/custom-ease/custom-ease-plugin.ts","../../src/plugins/i18n/get-locales.ts","../../src/plugins/i18n/i18n-html-plugin.ts","../../src/plugins/i18n/i18n-cli-plugin.ts","../../src/ast-utilities/babel-utils/resolve-static-value.ts","../../src/plugins/i18n/i18n-script-plugin.ts","../../src/plugins/i18n/i18n-plugin.ts","../../src/plugins/import-as-string/parse-import-as-string.ts","../../src/plugins/import-as-string/import-as-string-plugin.ts","../../src/plugins/load-sources/load-sources-plugin.ts","../../src/plugins/robots-text/robots-text-plugin.ts","../../src/plugins/service-worker/service-worker-plugin.ts","../../src/plugins/sitemap/sitemap-plugin.ts","../../src/plugins/svgo/svgo-optimize.ts","../../src/plugins/svgo/svgo-plugin.ts","../../src/ast-utilities/postcss-utils/process-css.ts","../../src/plugins/transform-css/transform-css-plugin.ts","../../src/ast-utilities/babel-utils/use-transform.ts","../../src/plugins/transform-js/transform-js-plugin.ts","../../src/plugins/web-manifest/web-manifest-plugin.ts","../../src/helpers/worker-pool.ts","../../src/plugins/write-files/write-files-plugin.ts","../../src/helpers/execute-js-in-vm.ts","../../src/plugins/html-build-time-script/lsp.ts","../../src/plugins/html-build-time-script/html-build-time-script.ts","../../src/plugins/html-bundle-script/esbuild-plugin.ts","../../src/plugins/html-bundle-script/esbuild-bundle.ts","../../src/plugins/html-bundle-script/html-bundle-script-plugin.ts","../../src/ast-utilities/postcss-utils/import-prelude.ts","../../src/parsers/css-parser.ts","../../src/plugins/core-plugins/style-metadata/style-loader.ts","../../src/helpers/style-bundler.ts","../../src/plugins/html-bundle-style/html-bundle-style-plugin.ts","../../src/plugins/html-env-only/html-environment-only-plugin.ts","../../src/plugins/html-fragment/html-fragment-plugin.ts","../../src/plugins/html-iife-script/iife.ts","../../src/plugins/html-iife-script/html-iife-script-plugin.ts","../../src/plugins/html-inline-script/html-inline-script-plugin.ts","../../src/plugins/html-inline-style/html-inline-style-plugin.ts","../../src/plugins/html-inline-svg/html-inline-svg-plugin.ts","../../src/plugins/html-inline-text/html-inline-text-plugin.ts","../../src/plugins/html-insert/html-insert-plugin.ts","../../src/plugins/html-layout/fill-placeholders.ts","../../src/plugins/html-layout/inline-layout.ts","../../src/plugins/html-layout/options.ts","../../src/plugins/html-layout/lsp.ts","../../src/plugins/html-layout/html-layout-plugin.ts","../../src/plugins/html-markdown/html-markdown-plugin.ts","../../src/plugins/html-merge-styles/html-merge-styles-plugin.ts","../../src/plugins/core-plugins/base-plugin/base-plugin.ts","../../src/plugins/html-pages/calculate-page-path.ts","../../src/plugins/html-pages/fill-placeholders.ts","../../src/plugins/html-pages/dynamic-routes.ts","../../src/plugins/html-pages/html-pages-plugin.ts","../../src/plugins/html-preload/get-file-type.ts","../../src/plugins/html-preload/html-preload-plugin.ts","../../src/ast-utilities/html-utils/parse-html-sources.ts","../../src/parsers/html-parser.ts","../../src/plugins/core-plugins/html-metadata/html-loader.ts","../../src/plugins/core-plugins/html-metadata/lsp.ts","../../src/plugins/core-plugins/html-metadata/html-metadata-plugin.ts","../../src/plugins/core-plugins/markdown-metadata/markdown-metadata-plugin.ts","../../src/ast-utilities/babel-utils/parse-script-srouces.ts","../../src/parsers/js-parser.ts","../../src/plugins/core-plugins/script-metadata/script-loader.ts","../../src/plugins/core-plugins/script-metadata/script-metadata-plugin.ts","../../src/ast-utilities/postcss-utils/parse-style-srouces.ts","../../src/plugins/core-plugins/style-metadata/style-metadata-plugin.ts","../../src/plugins/core-plugins/svg-metadata/svg-loader.ts","../../src/plugins/core-plugins/svg-metadata/svg-metadata-plugin.ts","../../src/plugins/core-plugins/web-manifest-metadata/web-manifest-loader.ts","../../src/plugins/core-plugins/web-manifest-metadata/web-manifest-metadata-plugin.ts","../../src/plugins/core-plugins/development-server/claim-port.ts","../../src/plugins/core-plugins/development-server/inject-reload-script.ts","../../src/plugins/core-plugins/development-server/order-by-dependency-depth.ts","../../src/plugins/core-plugins/development-server/development-server-plugin.ts","../../src/helpers/pirnt-debug.ts","../../src/main.ts","../../src/plugins/cli-plugins/build/build-cli-plugin.ts","../../src/plugins/cli-plugins/convert-fonts/convert-fonts-cli-plugin.ts","../../src/plugins/cli-plugins/generate-font-face/generate-font-face.ts","../../src/plugins/cli-plugins/generate-font-face/generate-font-face-cli-plugin.ts","../../src/plugins/cli-plugins/material-you/material-you/utils/color.ts","../../src/plugins/cli-plugins/material-you/material-you/utils/color-utilities.ts","../../src/plugins/cli-plugins/material-you/material-you/utils/math-utilities.ts","../../src/plugins/cli-plugins/material-you/material-you/cam/hct-solver.ts","../../src/plugins/cli-plugins/material-you/material-you/cam/cam.ts","../../src/plugins/cli-plugins/material-you/material-you/monet/shades.ts","../../src/plugins/cli-plugins/material-you/material-you/monet/palette.ts","../../src/plugins/cli-plugins/material-you/material-you/index.ts","../../src/plugins/cli-plugins/material-you/material-you-cli-plugin.ts","../../src/plugins/cli-plugins/serve/serve-cli-plugin.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\n\nimport { isValidRelativePath, splitHtmlLink } from \"../utilities/html-links.ts\";\nimport { isPackageMetadata } from \"../utilities/metadata-utilities.ts\";\nimport { dirname, extname, isAbsolute, join, normalize, relative } from \"../utilities/path.ts\";\n\nimport type { App, MetadataBase, PackageMetadata } from \"@staticbolt/core\";\n\nexport class DependenciesFinder {\n readonly #depsMap = new Map<string, Set<string>>();\n readonly #visiting = new Set<string>();\n readonly #app: App;\n readonly #root: string;\n\n constructor(app: App, root: string) {\n this.#app = app;\n this.#root = root;\n }\n\n async findDeps(metadataItem: MetadataBase): Promise<Set<string>> {\n const cached = this.#depsMap.get(metadataItem.filePath);\n if (cached) {\n return cached;\n }\n\n if (this.#app.emitExclude.has(metadataItem)) {\n return new Set();\n }\n\n if (this.#visiting.has(metadataItem.filePath)) {\n return new Set();\n }\n\n this.#visiting.add(metadataItem.filePath);\n\n const usedFiles = new Set<string>();\n\n // No need to parse packages (expensive)\n if (isPackageMetadata(metadataItem)) {\n await this.#collectPackageMetadataDeps(metadataItem, usedFiles);\n } else {\n const sources = await this.#app.requestSources(metadataItem);\n for (const { source } of sources) {\n await this.#collect(source, metadataItem.filePath, usedFiles);\n }\n }\n\n this.#visiting.delete(metadataItem.filePath);\n this.#depsMap.set(metadataItem.filePath, usedFiles);\n\n return usedFiles;\n }\n\n async #collectPackageMetadataDeps(metadataItem: PackageMetadata, usedFiles: Set<string>) {\n for (const dependency of metadataItem.directDependencies) {\n const absPath = join(this.#root, dependency);\n usedFiles.add(absPath);\n\n const dependencyMetadata = this.#app.findMetadata({ filePath: dependency });\n if (!dependencyMetadata) continue;\n\n const subDependencies = await this.findDeps(dependencyMetadata);\n for (const subDependency of subDependencies) {\n usedFiles.add(subDependency);\n }\n }\n }\n\n async #collect(source: string, fromFile: string, usedFiles: Set<string>): Promise<void> {\n const absPath = this.#resolveSource(source, fromFile);\n if (!absPath) {\n return;\n }\n\n if (extname(absPath) === \".html\") {\n return;\n }\n\n usedFiles.add(absPath);\n\n const relativePath = relative(this.#root, absPath);\n\n const dependencyMetadata = this.#app.findMetadata({ filePath: relativePath });\n if (!dependencyMetadata) return;\n\n const dependencies = await this.findDeps(dependencyMetadata);\n for (const dependency of dependencies) {\n usedFiles.add(dependency);\n }\n }\n\n /** Resolves a source path relative to its containing file and the output directory. */\n #resolveSource(source: string, filePath: string): string | void {\n if (!isValidRelativePath(source)) return;\n\n const link = normalize(splitHtmlLink(source)[0]);\n\n let resolved = isAbsolute(link)\n ? join(this.#root, link) // absolute → resolve from root\n : join(this.#root, dirname(filePath), link); // relative → resolve from containing file\n\n const extension = extname(resolved);\n\n // Folder or path to index.html\n if (!extension) {\n // Try index.html\n const candidate = join(resolved, \"index.html\");\n if (existsSync(candidate)) {\n resolved = candidate;\n }\n\n // Try directory, we don't need it\n if (existsSync(resolved)) {\n return;\n }\n }\n\n return resolved;\n }\n}\n","import { readdirSync, rmdirSync, unlinkSync } from \"node:fs\";\nimport c from \"chalk\";\nimport { globSync } from \"glob\";\n\nimport { DependenciesFinder as DependenciesFinder } from \"../../helpers/find-dependencies.ts\";\nimport { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { basename, dirname, extname, join, isPathMatch, relative } from \"../../utilities/path.ts\";\nimport { bytesToKB, humanReadableBytes } from \"../../utilities/utilities.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface AnalyzeOutputOptions {\n /**\n * Delete unused files from the output directory.\n *\n * @default false\n */\n deleteUnused?: boolean;\n\n /**\n * Log unused files.\n *\n * @default true\n */\n logUnusedFiles?: boolean;\n\n /**\n * Glob patterns to skip files when analyzing.\n *\n * @default [\"robots.txt\", \"sitemap.xml\", \"sw.js\", \"workbox-*.js\"]\n */\n exclude?: string[];\n\n /**\n * Specifies the size limit (in kilobytes) for each file type to trigger a warning. Set to `false` to disable warnings.\n *\n * @default { \".js\": 150 }\n */\n maxFileSize?: Record<string, number> | false;\n}\n\n/**\n * Analyzes the production build output and reports three things:\n *\n * - Missing: files the HTML pages reference but that are not in the output directory (errors).\n * - Unused: files in the output directory no page reaches (warnings, deleted when \"deleteUnused\" is set).\n * - Oversized: files above the per-extension limit in \"maxFileSize\" (warnings, largest first).\n *\n * Notes:\n *\n * - Runs after the build and only in production.\n * - Reachability is walked from HTML pages only, so anything reachable through another entry point counts as unused.\n * - HTML files are never listed as unused or deleted.\n * - Empty directories under the output are removed on every run, not just when deleting unused files.\n * - \"exclude\" is matched against paths relative to the output directory and applies to every report, so a file a later plugin\n * writes (a service worker, say) can be referenced without being reported missing.\n */\nexport function analyzeOutputPlugin(options: AnalyzeOutputOptions = {}): Plugin {\n const isRemoveUnused = options.deleteUnused ?? false;\n const exclude = options.exclude ?? [\"robots.txt\", \"sitemap.xml\", \"sw.js\", \"workbox-*.js\"];\n const maxFileSize = options.maxFileSize ?? { \".js\": 150 };\n const isLogUnusedFiles = options.logUnusedFiles ?? true;\n\n return {\n name: \"analyze-output\",\n\n async postBuild() {\n if (!this.production) return;\n\n const dependenciesFinder = new DependenciesFinder(this, this.outdir);\n\n // Absolute paths\n const availableFiles = new Set(globSync(this.outdir + \"/**/*\", { ignore: \"**/*.html\", nodir: true }));\n\n // Find used files staring from HTML as entry points\n const htmlEntryPoints = this.metadataList.filter(meta => isHtmlMetadata(meta));\n const usedFiles = new Set<string>();\n\n for (const metadataItem of htmlEntryPoints) {\n const dependencies = await dependenciesFinder.findDeps(metadataItem);\n\n for (const dependency of dependencies) {\n usedFiles.add(dependency);\n }\n }\n\n const isExcluded = (file: string) => isPathMatch(relative(this.outdir, file), { include: exclude, root: this.outdir });\n\n // ------ Report missing files ------\n const missingFiles = [...usedFiles.difference(availableFiles)].filter(file => !isExcluded(file));\n\n let missingFilesLog = c.bold(\"The following files are missing:\");\n for (const missing of missingFiles) {\n missingFilesLog += \"\\n\" + c.red(\"File not found: \") + c.yellow(relative(this.root, missing));\n }\n\n if (missingFiles.length > 0) {\n this.log.error(missingFilesLog);\n }\n\n // ------ Report/Remove unused files ------\n const unusedFiles = availableFiles.difference(usedFiles);\n const unusedFilesLog: string[] = [];\n\n for (const unused of unusedFiles) {\n if (extname(unused) === \".html\") continue; // Entry point\n\n if (isExcluded(unused)) continue;\n\n if (isRemoveUnused) unlinkSync(unused);\n\n unusedFilesLog.push(c.yellow(join(basename(this.outdir), relative(this.outdir, unused))));\n }\n\n const logTitle = isRemoveUnused\n ? c.bold(c.red(\"Removed\"), \"(\" + c.yellow(unusedFilesLog.length) + \")\", \"unused files from the output directory\")\n : c.bold(\"Found\", \"(\" + c.yellow(unusedFilesLog.length) + \")\", \"unused files\");\n\n if (unusedFilesLog.length > 0) {\n this.log.warn(logTitle + (isLogUnusedFiles ? \"\\n\" + unusedFilesLog.join(\"\\n\") : \"\"));\n }\n\n // ------ Remove empty directories ------\n const directories = globSync(this.outdir + \"/**/*/\");\n const sortedDirectories = directories.toSorted((a, b) => a.localeCompare(b));\n\n for (const directory of sortedDirectories) {\n let currentPath = directory;\n\n while (currentPath !== this.outdir) {\n const isEmpty = readdirSync(currentPath).length === 0;\n if (!isEmpty) break;\n\n rmdirSync(currentPath);\n currentPath = dirname(currentPath);\n }\n }\n\n // ------ check files size ------\n if (maxFileSize) {\n const extensions = Object.keys(maxFileSize).map(extension => extension.slice(1));\n const patternExtensionPart = extensions.length > 1 ? `{${extensions.join(\",\")}}` : extensions[0];\n const filesStat = globSync(`**/*.${patternExtensionPart}`, {\n ignore: exclude,\n nodir: true,\n cwd: this.outdir,\n withFileTypes: true,\n stat: true,\n });\n\n const largeFilesLogs: string[] = [];\n\n const sortedFiles = filesStat.toSorted((a, b) => (b.size ?? 0) - (a.size ?? 0));\n for (const file of sortedFiles) {\n const maxSize = maxFileSize[extname(file.name)];\n if (typeof maxSize !== \"number\") continue;\n\n if (file.size === 0) {\n continue;\n }\n\n const fileSizeKB = bytesToKB(file.size ?? 0);\n if (fileSizeKB <= maxSize) continue;\n\n largeFilesLogs.push(\n c.yellow(file.relative()) +\n ` (${c.red.bold(humanReadableBytes(file.size ?? 0))} ${c.blue(\">\")} ${c.green(humanReadableBytes(maxSize * 1024))})`\n );\n }\n\n if (largeFilesLogs.length > 0) {\n this.log.warn(c.bold(\"The following files may be large:\\n\") + largeFilesLogs.join(\"\\n\"));\n }\n }\n },\n };\n}\n","import * as esbuild from \"esbuild\";\n\nimport { valueOrError, type ValueOrError } from \"../../utilities/value-or-error.ts\";\n\nconst bundleFunction = valueOrError(esbuild.build);\n\ninterface BundleOptions {\n contents?: string;\n entryPoint?: string;\n resolveDir: string;\n packageName: string;\n outfile: string;\n production: boolean;\n minify: boolean;\n treeShaking: boolean;\n\n onPackageResolve: (\n path: string,\n importer: string\n ) => esbuild.OnResolveResult | undefined | Promise<esbuild.OnResolveResult | undefined>;\n\n onFileResolve?: (source: string, importer: string) => esbuild.OnResolveResult | undefined;\n}\n\nexport async function bundlePackage(options: BundleOptions): Promise<ValueOrError<string>> {\n const { resolveDir, packageName, outfile, onPackageResolve, production, minify, treeShaking } = options;\n\n const plugins: esbuild.Plugin[] = [\n {\n name: \"esbuild-plugin-packages-resolver\",\n setup(build) {\n // Filter only packages excluding relative imports\n build.onResolve({ filter: new RegExp(\"^[^./].*\") }, async arguments_ => {\n // skip the package that is currently being bundled\n if (arguments_.path === packageName || arguments_.importer === \"<stdin>\") {\n return;\n }\n\n return await onPackageResolve(arguments_.path, arguments_.importer);\n });\n },\n },\n ];\n\n if (options.onFileResolve) {\n plugins.push({\n name: \"esbuild-plugin-relative-imports-resolver\",\n setup(build) {\n // Filter only relative imports\n build.onResolve({ filter: /^\\./ }, arguments_ => {\n return options.onFileResolve?.(arguments_.path, arguments_.importer);\n });\n },\n });\n }\n\n const [bundleResult, bundleError] = await bundleFunction({\n stdin: options.contents ? { contents: options.contents, resolveDir } : undefined,\n entryPoints: options.entryPoint ? [options.entryPoint] : undefined,\n outfile,\n absWorkingDir: resolveDir,\n bundle: true,\n minify,\n treeShaking,\n write: false,\n legalComments: \"none\",\n packages: \"bundle\",\n platform: \"browser\",\n format: \"esm\",\n target: \"es2022\",\n define: { \"process.env.NODE_ENV\": production ? '\"production\"' : '\"development\"' },\n logLevel: \"silent\",\n plugins,\n });\n\n if (bundleError) {\n return [null, bundleError];\n }\n\n const outCode = bundleResult?.outputFiles?.[0]?.text;\n\n if (typeof outCode !== \"string\") {\n return [null, new Error(`Failed to bundle the package \"${packageName}\"`)];\n }\n\n return [outCode, null];\n}\n","import _traverse from \"@babel/traverse\";\nimport * as t from \"@babel/types\";\n\nimport type { BabelAst, NodePath } from \"@staticbolt/core\";\n\nconst traverse = typeof _traverse === \"function\" ? _traverse : _traverse.default;\n\nexport type Specifier =\n | { type: \"unknown\" }\n | { type: \"default\"; publicName?: never; name: string; newDefaultName?: string; setDefaultName: (name: string) => void }\n | { type: \"namespace\"; publicName?: never; name: string }\n | { type: \"named\"; kind: \"import\" | \"export\"; publicName: string; name: string }\n | { type: \"side-effect\"; name?: never; imported?: never };\n\nexport function collectSpecifiers(path: NodePath): Specifier[] {\n const specifiers: Specifier[] = [];\n\n // import default from \"source\";\n // import { value } from \"source\";\n // import * as value from \"source\";\n // import \"source\";\n if (path.isImportDeclaration()) {\n collectImportDeclarationSpecifiers(path, specifiers);\n return specifiers;\n }\n\n // export * from \"source\";\n if (path.isExportAllDeclaration()) {\n collectExportAllDeclarationSpecifiers(path, specifiers);\n return specifiers;\n }\n\n // export default from \"source\";\n // export { value } from \"source\";\n // export * as value from \"source\";\n if (path.isExportNamedDeclaration()) {\n collectExportNamedDeclarationSpecifiers(path, specifiers);\n return specifiers;\n }\n\n // const value = (await import(\"source\")).value;\n // const value = (await import(\"source\")).default;\n // const { value } = await import(\"source\");\n // const { default } = await import(\"source\");\n // const all = await import(\"source\");\n if (path.isCallExpression()) {\n collectDynamicImportSpecifiers(path, specifiers);\n return specifiers;\n }\n\n return specifiers;\n}\n\nexport function collectSpecifiersFromAst(ast: BabelAst): { source: string; specifiers: Specifier[] }[] {\n const result: { source: string; specifiers: Specifier[] }[] = [];\n\n traverse(ast, {\n // import default from \"source\";\n // import { value } from \"source\";\n // import * as value from \"source\";\n // import \"source\";\n ImportDeclaration(path) {\n if (!t.isStringLiteral(path.node.source)) return;\n\n const kind = path.node.importKind ?? \"value\";\n if (kind === \"type\") return;\n\n const source = path.node.source.value;\n\n if (source.startsWith(\"node:\")) {\n return;\n }\n\n const specifiers: Specifier[] = [];\n\n collectImportDeclarationSpecifiers(path, specifiers);\n\n result.push({\n get source() {\n return source;\n },\n set source(newValue) {\n if (path.node) {\n path.node.source = t.stringLiteral(newValue);\n }\n },\n specifiers,\n });\n },\n\n // export * from \"source\";\n ExportAllDeclaration(path) {\n if (!path.node.source.value) return;\n\n const kind = path.node.exportKind ?? \"value\";\n if (kind === \"type\") return;\n\n const specifiers: Specifier[] = [];\n\n collectExportAllDeclarationSpecifiers(path, specifiers);\n\n result.push({\n get source() {\n return path.node.source.value;\n },\n set source(newValue) {\n path.node.source = t.stringLiteral(newValue);\n },\n specifiers,\n });\n },\n\n // export default from \"source\";\n // export { value } from \"source\";\n // export * as value from \"source\";\n ExportNamedDeclaration(path) {\n if (!t.isStringLiteral(path.node.source)) return;\n\n const kind = path.node.exportKind ?? \"value\";\n if (kind === \"type\") return;\n\n const source = path.node.source.value;\n\n if (source.startsWith(\"node:\")) {\n return;\n }\n\n const specifiers: Specifier[] = [];\n\n collectExportNamedDeclarationSpecifiers(path, specifiers);\n\n result.push({\n get source() {\n return source;\n },\n set source(newValue) {\n path.node.source = t.stringLiteral(newValue);\n },\n specifiers,\n });\n },\n\n // const value = (await import(\"source\")).value;\n // const value = (await import(\"source\")).default;\n // const { value } = await import(\"source\");\n // const { default } = await import(\"source\");\n // const all = await import(\"source\");\n CallExpression(path) {\n if (!t.isImport(path.node.callee) || !t.isStringLiteral(path.node.arguments[0])) return;\n\n const setSource = (newValue: string) => {\n path.node.arguments[0] = t.stringLiteral(newValue);\n };\n\n const source = path.node.arguments[0].value;\n if (source.startsWith(\"node:\")) {\n return;\n }\n\n const specifiers: Specifier[] = [];\n\n collectDynamicImportSpecifiers(path, specifiers);\n result.push({\n get source() {\n return source;\n },\n set source(newValue) {\n setSource(newValue);\n },\n specifiers,\n });\n },\n });\n\n return result;\n}\n\nexport function collectImportDeclarationSpecifiers(path: NodePath<t.ImportDeclaration>, specifiers: Specifier[]) {\n const node = path.node;\n\n if (!t.isStringLiteral(node.source) || (node.importKind && node.importKind !== \"value\")) return;\n\n let hasFoundSpecifier = false;\n\n for (let index = 0; index < node.specifiers.length; index++) {\n const specifier = node.specifiers[index];\n\n // Default: import React from \"react\";\n if (t.isImportDefaultSpecifier(specifier)) {\n // setDefaultName(\"custom\") → `import { custom as React } from \"react\";`\n const setDefaultName = (newName: string) => {\n const index = node.specifiers.indexOf(specifier);\n if (index === -1) return;\n node.specifiers[index] = t.importSpecifier(t.identifier(specifier.local.name), t.identifier(newName));\n };\n\n specifiers.push({ type: \"default\", name: specifier.local.name, setDefaultName });\n\n hasFoundSpecifier = true;\n continue;\n }\n\n // Named: import { useState } from \"react\";\n if (t.isImportSpecifier(specifier)) {\n const imported = getNodeName(specifier.imported);\n if (!imported) continue;\n\n specifiers.push({ type: \"named\", kind: \"import\", name: imported, publicName: specifier.local.name });\n hasFoundSpecifier = true;\n continue;\n }\n\n // Namespace: import * as z from \"zod\";\n if (t.isImportNamespaceSpecifier(specifier)) {\n const usedNames = collectUsedNames(path, specifier.local.name);\n\n for (const name of usedNames) {\n if (name === \"default\") {\n const capturedLocalName = specifier.local.name;\n const capturedPath = path;\n\n // setDefaultName(\"custom\") → keeps `import * as z from \"zod\";` but rewrites `z.default` → `z.custom` at all usage sites\n const setDefaultName = (newName: string) => {\n const binding = capturedPath.scope.getBinding(capturedLocalName);\n if (!binding) return;\n\n for (const referencePath of binding.referencePaths) {\n const parentNode = referencePath.parentPath?.node;\n if (\n t.isMemberExpression(parentNode) &&\n t.isIdentifier(parentNode.property) &&\n parentNode.property.name === \"default\"\n ) {\n parentNode.property = t.identifier(newName);\n }\n }\n };\n specifiers.push({ type: \"default\", name: capturedLocalName, setDefaultName });\n\n hasFoundSpecifier = true;\n\n continue;\n }\n\n specifiers.push({ type: \"named\", kind: \"import\", name, publicName: name });\n hasFoundSpecifier = true;\n }\n }\n }\n\n // Side-effect: import \"react\";\n if (!hasFoundSpecifier) {\n specifiers.push({ type: \"side-effect\" });\n }\n}\n\nexport function collectExportAllDeclarationSpecifiers(path: NodePath<t.ExportAllDeclaration>, specifiers: Specifier[]) {\n if (!path.node.source.value || path.node.exportKind !== \"value\") return;\n\n specifiers.push({ type: \"namespace\", name: \"*\" });\n}\n\nexport function collectExportNamedDeclarationSpecifiers(path: NodePath<t.ExportNamedDeclaration>, specifiers: Specifier[]) {\n const node = path.node;\n\n if (!t.isStringLiteral(node.source) || node.exportKind !== \"value\") return;\n\n for (let index = 0; index < node.specifiers.length; index++) {\n const specifier = node.specifiers[index];\n\n // Default: export default React from \"react\";\n if (t.isExportDefaultSpecifier(specifier) && t.isIdentifier(specifier.exported)) {\n // setDefaultName(\"custom\") → `export { custom as React } from \"react\";`\n const setDefaultName = (newName: string) => {\n const index = node.specifiers.indexOf(specifier);\n if (index === -1) return;\n node.specifiers[index] = t.exportSpecifier(t.identifier(newName), t.identifier(specifier.exported.name));\n };\n\n specifiers.push({ type: \"default\", name: specifier.exported.name, setDefaultName });\n continue;\n }\n\n // Named: export { useState } from \"react\";\n if (t.isExportSpecifier(specifier)) {\n const exported = t.isIdentifier(specifier.exported) ? specifier.exported.name : specifier.exported.value;\n specifiers.push({ type: \"named\", kind: \"export\", name: exported, publicName: specifier.local.name });\n continue;\n }\n\n // Namespace: export * as React from \"react\";\n if (t.isExportNamespaceSpecifier(specifier)) {\n specifiers.push({\n type: \"namespace\",\n // @ts-expect-error The types are wrong\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n name: t.isIdentifier(specifier.exported) ? specifier.exported.name : specifier.exported.value,\n });\n }\n }\n}\n\nfunction collectDynamicImportSpecifiers(path: NodePath<t.CallExpression>, specifiers: Specifier[]) {\n if (!t.isImport(path.node.callee)) return;\n\n // case: dynamic import name\n if (!t.isStringLiteral(path.node.arguments[0])) {\n specifiers.push({ type: \"unknown\" });\n return;\n }\n\n const parentPath = path.parentPath;\n const hasAwait = parentPath && t.isAwaitExpression(parentPath.node);\n\n // case: not awaited cannot correctly find the specifier\n if (!hasAwait) {\n specifiers.push({ type: \"unknown\" });\n return;\n }\n\n const parentNode = parentPath.parentPath?.node;\n\n // case: const varName = (await import('path')).name;\n // equivalent to: import { name } from 'path';\n if (t.isMemberExpression(parentNode)) {\n const property = parentNode.property;\n\n const importedName = getNodeName(property);\n if (!importedName) return;\n\n // case: const varName = (await import('path')).default;\n // equivalent to: import default from 'path';\n if (importedName === \"default\") {\n const capturedMemberExpression = parentNode;\n\n // setDefaultName(\"custom\") → `(await import('path')).custom`\n const setDefaultName = (newName: string) => {\n capturedMemberExpression.property = t.identifier(newName);\n };\n\n specifiers.push({ type: \"default\", name: importedName, setDefaultName });\n return;\n }\n\n specifiers.push({ type: \"named\", kind: \"import\", name: importedName, publicName: importedName });\n\n return;\n }\n\n // case: const { named } = await import('path');\n // equivalent to: import { named } from 'path';\n if (t.isVariableDeclarator(parentNode) && t.isObjectPattern(parentNode.id)) {\n for (const property of parentNode.id.properties) {\n if (!t.isObjectProperty(property)) continue;\n\n const importedName = getNodeName(property.key);\n if (!importedName) continue;\n\n const localName = getNodeName(property.value);\n\n // case: const { default } = await import('path');\n // equivalent to: import default from 'path';\n if (importedName === \"default\") {\n // setDefaultName(\"custom\") → `const { custom: val } = await import('path')`;\n const setDefaultName = (newName: string) => {\n property.key = t.identifier(newName);\n };\n\n specifiers.push({ type: \"default\", name: localName ?? importedName, setDefaultName });\n continue;\n }\n\n specifiers.push({ type: \"named\", kind: \"import\", name: importedName, publicName: localName ?? importedName });\n }\n\n return;\n }\n\n // case: const lib = await import('path');\n // equivalent to: import * as lib from 'path';\n if (t.isVariableDeclarator(parentNode) && t.isIdentifier(parentNode.id)) {\n const usedNames = collectUsedNames(path, parentNode.id.name);\n\n for (const name of usedNames) {\n if (name === \"default\") {\n const capturedId = parentNode.id;\n const capturedPath = path;\n\n // setDefaultName(\"custom\") → keeps import as-is, rewrites `lib.default` → `lib.custom` at all usage sites\n\n const setDefaultName = (newName: string) => {\n const binding = capturedPath.scope.getBinding(capturedId.name);\n if (!binding) return;\n\n for (const referencePath of binding.referencePaths) {\n const pNode = referencePath.parentPath?.node;\n if (t.isMemberExpression(pNode) && t.isIdentifier(pNode.property) && pNode.property.name === \"default\") {\n pNode.property = t.identifier(newName);\n }\n }\n };\n\n specifiers.push({ type: \"default\", name: parentNode.id.name, setDefaultName });\n continue;\n }\n\n specifiers.push({ type: \"named\", kind: \"import\", name, publicName: name });\n }\n\n return;\n }\n\n // case: await import('path');\n // equivalent to: import 'path';\n if (!parentNode || t.isExpressionStatement(parentNode)) {\n specifiers.push({ type: \"side-effect\" });\n }\n}\n\n/**\n * Collects used names from a name space import. E.g., `import * as z from \"zod\"`\\\n * Covers most cases when importing a package using a name space.\n *\n * Covered cases:\n *\n * - Direct member expression: `z.string()`\n * - Destructuring: `const { string, object } = z;`\n * - Following aliases: `const zod = z;`\n *\n * Ignored cases:\n *\n * - Object destructuring with spread syntax: `const { string, ...rest } = z;`\n */\nfunction collectUsedNames(path: NodePath, importName: string): Set<string> {\n const usedNames = new Set<string>();\n\n const binding = path.scope.getBinding(importName);\n if (!binding) {\n return usedNames;\n }\n\n for (const referencePath of binding.referencePaths) {\n const parentPath = referencePath.parentPath;\n if (!parentPath) {\n continue;\n }\n\n const parentNode = parentPath.node;\n\n // Direct member expression: z.string()\n if (t.isMemberExpression(parentNode) && t.isIdentifier(parentNode.property)) {\n usedNames.add(parentNode.property.name); // just add the property\n continue;\n }\n\n // Destructuring: const { string, object } = z;\n if (t.isVariableDeclarator(parentNode) && t.isIdentifier(parentNode.init)) {\n const id = parentNode.id;\n\n // Destructuring: const { string, object } = z;\n if (t.isObjectPattern(id)) {\n for (const property of id.properties) {\n if (t.isRestElement(property) || !t.isIdentifier(property.key)) continue;\n usedNames.add(property.key.name);\n }\n continue;\n }\n\n // Alias: const alias = z;\n if (t.isIdentifier(id)) {\n const aliasUsed = collectUsedNames(parentPath.get(\"id\"), id.name);\n for (const n of aliasUsed) usedNames.add(n);\n }\n }\n }\n\n return usedNames;\n}\n\nfunction getNodeName(node: t.Node): string | null {\n if (t.isIdentifier(node)) {\n return node.name;\n }\n\n if (t.isStringLiteral(node)) {\n return node.value;\n }\n\n if (t.isPrivateName(node)) {\n return node.id.name;\n }\n\n return null;\n}\n","import { createRequire } from \"node:module\";\nimport nodePath from \"node:path\";\n\nimport { join, isPathMatch, replaceExtension } from \"../../utilities/path.ts\";\n\nimport type { Specifier } from \"./collect-specifiers.ts\";\n\n/**\n * Some package names may include `.js` as part of their name (e.g., `highlight.js`).\\\n * If we have a subpackage within such a package, we face a conflict:\\\n * We cannot create a folder named `highlight.js` because a file with the same name (`highlight.js`) already exists.\\\n * To resolve this, we replace `.js` with `_js` in the subpackage path only, avoiding conflicts.\\\n * Example: `highlight.js/languages/javascript.js` -> `highlight_js/languages/javascript.js`\n */\nfunction normalizePackageName(originalSource: string) {\n const parts = originalSource.split(\"/\");\n\n // we need more than one part. e.g., `highlight.js/languages/javascript.js`\n if (parts.length <= 1) return originalSource;\n\n const outParts = [];\n\n for (let index = 0; index < parts.length; index++) {\n const part = parts[index];\n const isLast = index === parts.length - 1;\n\n // skip last part: it's the file name\n if (isLast) {\n outParts.push(part);\n continue;\n }\n\n // replace .js with _js\n outParts.push(part.replace(\".js\", \"_js\"));\n }\n\n return outParts.join(\"/\");\n}\n\nexport function calcPackageOutPath(packageName: string, packagesDirectory: string) {\n const normalizedPackageName = normalizePackageName(packageName);\n const withJsExtension = replaceExtension(normalizedPackageName, \".js\");\n const underPackagesDirectory = join(packagesDirectory, withJsExtension);\n\n return underPackagesDirectory;\n}\n\n/**\n * Output path for an asset shipped by a package, keeping its own extension.\n *\n * Example: `node_modules/highlight.js/styles/default.css` -> `packages/highlight_js/styles/default.css`\n */\nexport function calcPackageAssetOutPath(nodeModulesPath: string, packagesDirectory: string) {\n const marker = \"node_modules/\";\n const markerIndex = nodeModulesPath.lastIndexOf(marker);\n const packagePath = markerIndex === -1 ? nodeModulesPath : nodeModulesPath.slice(markerIndex + marker.length);\n\n return join(packagesDirectory, normalizePackageName(packagePath));\n}\n\nexport function generateStdinString(specifiers: Specifier[], packageName: string) {\n let isDefaultImport = false;\n let newDefaultName: string | undefined;\n let hasSideEffect = false;\n let isNamespace = false;\n const named = new Set<string>();\n\n for (const specifier of specifiers) {\n if (specifier.type === \"default\") {\n isDefaultImport = true;\n newDefaultName = specifier.newDefaultName;\n }\n\n if (specifier.type === \"named\" && specifier.kind === \"import\") {\n named.add(specifier.name);\n }\n\n if (specifier.type === \"named\" && specifier.kind === \"export\") {\n named.delete(specifier.name);\n named.add(specifier.publicName);\n }\n\n if (specifier.type === \"namespace\") {\n isNamespace = true;\n }\n //\n else if (specifier.type === \"side-effect\") {\n hasSideEffect = true;\n }\n }\n\n let contents = \"\";\n\n if (hasSideEffect) {\n contents += `import '${packageName}';`;\n }\n\n if (isNamespace) {\n contents += `\\nexport * from '${packageName}';`;\n }\n\n if (isDefaultImport) {\n contents += `\\nexport { default${newDefaultName ? ` as ${newDefaultName}` : \"\"} } from '${packageName}';`;\n }\n\n // Also include named exports in dev mode (because of commonjs cannot use export *)\n if (named.size > 0 && !isNamespace) {\n contents += `\\nexport { ${Array.from(named).join(\", \")} } from '${packageName}';`;\n }\n\n return contents;\n}\n\nexport function getChunkName(packageName: string, chunks: Record<string, string[]>) {\n for (const [chunkName, packages] of Object.entries(chunks)) {\n if (matchesPackage(packageName, packages)) {\n return chunkName;\n }\n }\n}\n\nexport function matchesPackage(packageName: string, packages: string[]) {\n for (const pattern of packages) {\n // exact match\n if (pattern === packageName) {\n return true;\n }\n\n // wildcard match like \"react-dom/*\"\n if (pattern.endsWith(\"/*\")) {\n const base = pattern.slice(0, -2); // remove \"/*\"\n const isMatch = packageName === base || packageName.startsWith(base + \"/\");\n\n if (isMatch) return true;\n }\n\n // double wild cards like \"react-dom/**\"\n if (pattern.endsWith(\"/**\")) {\n const base = pattern.slice(0, -2); // remove \"**\"\n const isMatch = packageName === base || packageName.startsWith(base + \"/\");\n\n if (isMatch) return true;\n }\n }\n\n return false;\n}\n\n/** Join the package name with its entry point. Example: `join(\"react-dom\", \"./client\") // => \"react-dom/client` */\nfunction packageJoin(name: string, subPackage: string) {\n return nodePath.join(name, subPackage).replace(/\\\\/g, \"/\").replace(/\\/$/, \"\");\n}\n\nfunction getNodeModuleDirectory(packageName: string, root: string): string | null {\n try {\n const require = createRequire(root.endsWith(nodePath.sep) ? root : root + nodePath.sep);\n const entryPoint = require.resolve(packageName);\n\n const parts = entryPoint.split(nodePath.sep);\n const index = parts.lastIndexOf(\"node_modules\");\n\n if (index === -1) {\n console.error(`node_modules not found in resolved path for \"${packageName}\": ${entryPoint}`);\n return null;\n }\n\n return parts.slice(0, index + 1).join(nodePath.sep);\n } catch (error) {\n console.error(`Failed to resolve package directory for \"${packageName}\":`, error);\n return null;\n }\n}\n\nexport function getCustomPackagePath(\n root: string,\n importPath: string,\n isProduction: boolean,\n resolvePackage: Record<string, Record<string, string | { production?: string; development?: string }>>\n): string | undefined {\n const environment = isProduction ? \"production\" : \"development\";\n\n for (const [packageName, exports] of Object.entries(resolvePackage)) {\n for (const [entry, stringOrObject] of Object.entries(exports)) {\n if (packageJoin(packageName, entry) !== importPath) continue;\n\n const relativePath = typeof stringOrObject === \"string\" ? stringOrObject : stringOrObject[environment];\n if (!relativePath) continue;\n\n const nodeModulesDirectory = getNodeModuleDirectory(packageName, root);\n if (!nodeModulesDirectory) {\n console.error(`Skipping \"${packageName}\" — could not determine node_modules directory`);\n continue;\n }\n\n return join(nodeModulesDirectory, packageName, relativePath);\n }\n }\n}\n\nexport function isNodeModulesPath(path: string, root: string) {\n return isPathMatch(path, { include: [\"**/node_modules/**\"], ignore: [], root });\n}\n\n/** Directory of the package a `node_modules` path belongs to, `undefined` for paths outside `node_modules`. */\nexport function packageDirectory(path: string): string | undefined {\n return /^(.*?node_modules\\/(?:@[^/]+\\/)?[^/]+)(?:\\/|$)/.exec(path)?.[1];\n}\n\n/**\n * Returns a stable key for a specifier, ignoring publicName and function refs. Side-effects are keyed by type alone (only one per\n * source).\n */\nfunction specifierKey(s: Specifier): string {\n switch (s.type) {\n case \"default\": {\n return `default::${s.name}`;\n }\n case \"namespace\": {\n return `namespace::${s.name}`;\n }\n case \"named\": {\n return `named::${s.name}`;\n }\n case \"unknown\":\n case \"side-effect\": {\n return `side-effect`;\n }\n }\n}\n\n/**\n * Diffs two specifier arrays and returns only the entries from `collected` that are not already present in `existing`.\n *\n * @param existing - The full current set of specifiers.\n * @param collected - Newly gathered specifiers to screen for novelty.\n * @returns Specifiers in `collected` that are absent from `existing`.\n */\nexport function diffSpecifiers(existing: Specifier[], collected: Specifier[]): Specifier[] {\n const existingKeys = new Set(existing.map(element => specifierKey(element)));\n return collected.filter(s => !existingKeys.has(specifierKey(s)));\n}\n","import { isScriptType } from \"../../helpers/is-script-type.ts\";\nimport { METADATA_TYPES, type PackageMetadata } from \"../../types/metadata.ts\";\nimport { isValidRelativePath, splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { filterScriptMetadata, isHtmlMetadata, isPackageMetadata, isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, extname, isAbsolute, join, relative } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { bundlePackage } from \"./bundle-esbuild.ts\";\nimport { collectSpecifiersFromAst, type Specifier } from \"./collect-specifiers.ts\";\nimport {\n calcPackageAssetOutPath,\n calcPackageOutPath,\n diffSpecifiers,\n generateStdinString,\n getChunkName,\n getCustomPackagePath,\n isNodeModulesPath,\n matchesPackage,\n packageDirectory,\n} from \"./helpers.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface BundlePackagesOptions {\n /** Output directory for bundled `node_modules` packages, relative to the build output directory. */\n packagesDir?: string;\n\n /**\n * Bundles specific packages into a single chunk for optimized loading.\n *\n * Useful for grouping related libraries (e.g., all React dependencies) or bundling CommonJS modules for browser compatibility.\n *\n * @example\n * bundlePackagesPlugin({\n * \"react-bundle\": [\"react\", \"react-dom\", \"react-dom/client\", \"react/jsx-runtime\", \"scheduler\"],\n * });\n *\n * @key Chunk name\n * @value Array of package names to include in the bundle\n */\n chunks?: Record<string, string[]>;\n\n /**\n * Custom package resolver entries to override default resolution logic.\n *\n * @example\n * bundlePackagesPlugin({\n * resolvePackage: {\n * \"react-dom\": {\n * \"./client\": {\n * production: \"./cjs/react-dom.production.js\",\n * development: \"./cjs/react-dom.development.js\",\n * },\n * },\n * },\n * });\n *\n * @default {}\n */\n resolvePackage?: Record<string, Record<string, string | { production?: string; development?: string }>>;\n}\n\nfunction normalizePackageName(packageName: string) {\n return \"default_\" + packageName.replace(/@|-|\\/|\\./g, \"_\");\n}\n\n/**\n * Bundles every \"node_modules\" package imported anywhere in the project into its own file under \"packagesDir\" and rewrites the\n * imports to point at it. Specifiers are collected across the whole codebase first, so esbuild can tree-shake each package down\n * to what is actually used.\n *\n * Notes:\n *\n * - Runs in both modes; minification and tree-shaking are production-only.\n * - Bare imports in scripts and \"<script src>\" tags resolving into \"node_modules\" are both redirected; a script tag is counted as a\n * side-effect import.\n * - A \"<link rel=stylesheet>\" shipped by a package is moved next to the package output, keeping its path inside the package. Other\n * file types stay where they resolve, under \"node_modules\".\n * - Dots in the output path become underscores (\"highlight.js\" becomes \"highlight_js\"), so a package cannot collide with the file\n * bundled from it.\n * - \"chunks\" merges packages into one file and renames their default imports to \"default_<package>\" so they share a module scope,\n * which is what CommonJS packages need to work in the browser.\n * - A package first discovered while bundling another one is bundled right away, then re-bundled once its specifiers are known.\n */\nexport function bundlePackagesPlugin(options: BundlePackagesOptions = {}): Plugin {\n const packagesOutputDirection = options.packagesDir ?? \"./packages\";\n const resolvePackage = options.resolvePackage ?? {};\n const chunks = options.chunks ?? {};\n\n /** Maps package names to a list of collected import specifiers (named, default, side-effect, etc.) from various source files. */\n const specifiersByPackage = new Map<string, Specifier[]>();\n\n /** Maps the absolute path of a package entry point to its original source name */\n const pathPackageMap = new Map<string, string>();\n\n /** Maps a chunk name to the entry contents it was last bundled from, to tell a stale chunk from an up to date one. */\n const chunkContents = new Map<string, string>();\n\n const JS_EXTENSIONS = new Set([\".js\", \".mjs\", \".cjs\", \".jsx\", \".ts\", \".mts\", \".cts\", \".tsx\"]);\n\n const printFormattedError = PrintFormattedError.create({ function: bundlePackagesPlugin });\n\n return {\n name: \"bundle-packages\",\n\n resolveSource(source, filePath) {\n if (!isValidRelativePath(source)) return;\n\n const [link] = splitHtmlLink(source);\n\n // Sources already resolved into another package are kept as is\n const target = join(dirname(filePath), link);\n if (isNodeModulesPath(target, this.root) && packageDirectory(target) !== packageDirectory(filePath)) {\n return { source, dependencyID: undefined };\n }\n\n const resolveResult = this.resolver.resolve(source, filePath);\n if (!resolveResult) {\n return;\n }\n\n // E.g. `fs`, `path`, etc\n if (!isAbsolute(resolveResult.path)) {\n return;\n }\n\n // Only looking for packages\n if (!resolveResult.isPackage) {\n return;\n }\n\n // Only looking for JS files\n if (!JS_EXTENSIONS.has(extname(resolveResult.path))) {\n return;\n }\n\n const isInsideRoot = resolveResult.path.startsWith(this.root);\n if (!isInsideRoot) {\n this.log.warn(`Resolved package \"${resolveResult.path}\" outside of the root directory.`);\n }\n\n pathPackageMap.set(resolveResult.path, source);\n\n const absFileDirectory = join(this.root, dirname(filePath));\n const resolvedSource = relative(absFileDirectory, resolveResult.path) + resolveResult.suffix;\n\n return { source: resolvedSource, dependencyID: undefined };\n },\n\n async postTransform() {\n const root = this.root;\n\n // - Collect specifiers\n // - Rewrite import paths to point to the package output directory\n // - For chunks, rewrite default imports\n for (const inputMetadata of this.metadataList) {\n for (const { metadata } of filterScriptMetadata(inputMetadata)) {\n const sources = collectSpecifiersFromAst(metadata.ast);\n\n for (const sourceReference of sources) {\n const source = sourceReference.source;\n const sourceRootRelative = join(dirname(metadata.filePath), source);\n\n // Only sources pointing to node_modules paths.\n if (!isNodeModulesPath(sourceRootRelative, root)) continue;\n\n const packageName = pathPackageMap.get(join(root, sourceRootRelative));\n if (!packageName) {\n printFormattedError(\n `Could not resolve package name for path \"${sourceRootRelative}\"\\n` +\n `imported from \"${metadata.filePath}\").\\n` +\n `Skipping specifier collection for this import.`\n );\n continue;\n }\n\n // Set the source to where the package will be output.\n const chunkName = getChunkName(packageName, chunks);\n const importName = chunkName ?? packageName;\n\n const packageOutputPath = calcPackageOutPath(importName, packagesOutputDirection);\n const newSource = relative(dirname(metadata.filePath), packageOutputPath);\n sourceReference.source = newSource;\n\n // Merge newly found specifiers with any already collected for this package.\n const existingSpecifiers = specifiersByPackage.get(packageName) ?? [];\n specifiersByPackage.set(packageName, existingSpecifiers);\n\n const specifiers = sourceReference.specifiers;\n\n // Rewrite default specifiers for chunks\n if (chunkName) {\n const normalizedPackageName = normalizePackageName(packageName);\n for (const specifier of specifiers) {\n if (specifier.type === \"default\") {\n specifier.setDefaultName(normalizedPackageName);\n specifier.newDefaultName = normalizedPackageName;\n }\n\n existingSpecifiers.push(specifier);\n }\n\n continue;\n }\n\n // Add without default rewrite\n existingSpecifiers.push(...specifiers);\n }\n }\n\n // Example: <script src=\"../node_modules/lodash/lodash.js\"></script>\n if (isHtmlMetadata(inputMetadata)) {\n const scriptTags = inputMetadata.ast.querySelectorAll(\"script[src]\");\n\n for (const scriptTag of scriptTags) {\n const source = scriptTag.getAttribute(\"src\");\n if (!source) continue;\n\n const scriptType = scriptTag.getAttribute(\"type\");\n if (!isScriptType(scriptType)) {\n continue;\n }\n\n const sourceRootRelative = join(dirname(inputMetadata.filePath), source);\n\n // Only sources pointing to node_modules paths.\n if (!isNodeModulesPath(sourceRootRelative, root)) continue;\n\n const packageName = pathPackageMap.get(join(root, sourceRootRelative));\n if (!packageName) {\n printFormattedError(\n `Could not resolve package name for script src \"${source}\" ` +\n `(in \"${inputMetadata.filePath}\"). ` +\n `The script tag will not be included in the bundled packages.`\n );\n continue;\n }\n\n // Set the source to where the package will be output.\n const packageOutputPath = calcPackageOutPath(packageName, packagesOutputDirection);\n const newSource = relative(dirname(inputMetadata.filePath), packageOutputPath);\n scriptTag.setAttribute(\"src\", newSource);\n\n // Merge newly found specifiers with any already collected for this package.\n const existingSpecifiers = specifiersByPackage.get(packageName) ?? [];\n existingSpecifiers.push({ type: \"side-effect\" });\n specifiersByPackage.set(packageName, existingSpecifiers);\n }\n\n // Example: <link rel=\"stylesheet\" href=\"../node_modules/highlight.js/styles/default.css\" />\n const styleLinks = inputMetadata.ast.querySelectorAll('link[rel=\"stylesheet\"], link[rel=\"preload\"][as=\"style\"]');\n\n for (const styleLink of styleLinks) {\n const source = styleLink.getAttribute(\"href\");\n if (!source) continue;\n\n const sourceRootRelative = join(dirname(inputMetadata.filePath), source);\n\n // Only sources pointing to node_modules paths.\n if (!isNodeModulesPath(sourceRootRelative, root)) continue;\n\n // A package ships it, so it belongs next to the other package output rather than under `node_modules`.\n const assetOutputPath = calcPackageAssetOutPath(sourceRootRelative, packagesOutputDirection);\n const assetPath = join(root, sourceRootRelative);\n const asset = this.metadataList.find(metadata => join(root, metadata.id) === assetPath);\n\n if (asset && asset.filePath !== assetOutputPath) {\n await this.rebase(asset, join(root, assetOutputPath));\n asset.filePath = assetOutputPath;\n }\n\n styleLink.setAttribute(\"href\", relative(dirname(inputMetadata.filePath), assetOutputPath));\n }\n }\n }\n\n /**\n * Tracks packages that need to be re-bundled. During bundling, we might detect that a package imports another package whose\n * specifiers we have already collected. This means we need to recollect the specifiers from the discovered package and\n * re-bundle the current package.\n */\n const pendingReBundles: {\n dependencyName: string;\n dependencyOutputPath: string;\n importerName: string;\n importerOutputPath: string;\n }[] = [];\n\n // Bundle chunks\n for (const [chunkName, packages] of Object.entries(chunks)) {\n if (packages.length === 0) continue;\n\n let contents = \"\";\n for (const [packageName, specifiers] of specifiersByPackage) {\n if (specifiers.length === 0) continue;\n\n const isMatch = matchesPackage(packageName, packages);\n if (!isMatch) continue;\n\n contents += generateStdinString(specifiers, packageName);\n }\n\n if (!contents) continue;\n\n // On demand builds collect specifiers one page at a time, so a chunk bundled for an earlier page is missing\n // whatever the current page adds to it.\n const bundledChunk = this.findMetadata({ type: METADATA_TYPES.Package, id: chunkName });\n if (bundledChunk && chunkContents.get(chunkName) === contents) continue;\n\n const packageOutputPath = calcPackageOutPath(chunkName, packagesOutputDirection);\n\n const packageMetadata: PackageMetadata = isPackageMetadata(bundledChunk)\n ? bundledChunk\n : {\n type: METADATA_TYPES.Package,\n packageName: chunkName,\n code: \"\",\n filePath: packageOutputPath,\n id: chunkName,\n directDependencies: new Set(),\n };\n\n // Re-collected while bundling\n packageMetadata.directDependencies.clear();\n\n const [bundledCode, bundleError] = await bundlePackage({\n contents,\n resolveDir: this.root,\n outfile: packageOutputPath,\n packageName: chunkName,\n minify: this.production,\n production: this.production,\n treeShaking: this.production,\n onPackageResolve: importedPackageName => {\n const packageChunkName = getChunkName(importedPackageName, chunks);\n if (packageChunkName === chunkName) {\n // Custom resolve path\n const customPath = getCustomPackagePath(this.root, importedPackageName, this.production, resolvePackage);\n if (customPath) {\n return { path: customPath, external: false };\n }\n\n // Let esbuild include the package in the bundle if it's in the same chunk\n return;\n }\n\n const packageOrChunkName = packageChunkName ?? importedPackageName;\n const dependencyOutputPath = calcPackageOutPath(packageOrChunkName, packagesOutputDirection);\n\n packageMetadata.directDependencies.add(dependencyOutputPath);\n\n pendingReBundles.push({\n dependencyName: importedPackageName,\n dependencyOutputPath,\n importerName: chunkName,\n importerOutputPath: packageOutputPath,\n });\n\n // A new package discovered as a dependency during bundling.\n // Adding to `specifiersByPackage` will bundle it in the first pass,\n // it will then be re-bundled with the correct specifiers.\n const isNewPackage = !specifiersByPackage.has(importedPackageName);\n if (isNewPackage) {\n specifiersByPackage.set(importedPackageName, [{ type: \"unknown\" }]);\n }\n\n // Rewrite the dependency's import path\n const relativePathFromImporter = relative(dirname(packageOutputPath), dependencyOutputPath);\n\n return { path: relativePathFromImporter, external: true };\n },\n });\n\n if (bundleError) {\n printFormattedError(`Failed to bundle package \"${chunkName}\"`, bundleError);\n continue;\n }\n\n packageMetadata.code = bundledCode;\n chunkContents.set(chunkName, contents);\n\n if (!bundledChunk) {\n this.addMetadata(packageMetadata);\n }\n }\n\n // Bundle every collected package except chunks\n\n for (const [packageName, specifiers] of specifiersByPackage) {\n if (specifiers.length === 0) continue;\n\n // Already bundled\n const packageMetadataExists = this.findMetadata({ type: METADATA_TYPES.Package, id: packageName });\n if (packageMetadataExists) continue;\n\n // Already bundled as a chunk\n const chunk = getChunkName(packageName, chunks);\n if (chunk) continue;\n\n const packageOutputPath = calcPackageOutPath(packageName, packagesOutputDirection);\n\n const packageMetadata: PackageMetadata = {\n type: METADATA_TYPES.Package,\n packageName,\n code: \"\",\n filePath: packageOutputPath,\n id: packageName,\n directDependencies: new Set(),\n };\n\n let isLoadAsIs = !this.production;\n for (const [index, specifier] of Array.from(specifiers).entries()) {\n if (specifier.type !== \"unknown\") continue;\n isLoadAsIs = true;\n specifiers.splice(index, 1);\n }\n\n const contents = isLoadAsIs ? undefined : generateStdinString(specifiers, packageName);\n\n const [bundledCode, bundleError] = await bundlePackage({\n contents,\n entryPoint: isLoadAsIs ? packageName : undefined,\n resolveDir: this.root,\n outfile: packageOutputPath,\n packageName,\n minify: this.production,\n production: this.production,\n treeShaking: this.production,\n onPackageResolve: importedPackageName => {\n const packageChunkName = getChunkName(importedPackageName, chunks);\n const packageOrChunkName = packageChunkName ?? importedPackageName;\n\n const dependencyOutputPath = calcPackageOutPath(packageOrChunkName, packagesOutputDirection);\n\n packageMetadata.directDependencies.add(dependencyOutputPath);\n\n pendingReBundles.push({\n dependencyName: importedPackageName,\n dependencyOutputPath,\n importerName: packageName,\n importerOutputPath: packageOutputPath,\n });\n\n // A new package discovered as a dependency during bundling.\n // Adding to `specifiersByPackage` (live list) will bundle it in the first pass;\n // it will then be re-bundled with the correct specifiers.\n const isNewPackage = !specifiersByPackage.has(importedPackageName);\n if (isNewPackage) {\n specifiersByPackage.set(importedPackageName, [{ type: \"unknown\" }]);\n }\n\n const relativePathFromImporter = relative(dirname(packageOutputPath), dependencyOutputPath);\n\n return { path: relativePathFromImporter, external: true };\n },\n });\n\n if (bundleError) {\n printFormattedError(`Failed to bundle package \"${packageName}\"`, bundleError);\n continue;\n }\n\n packageMetadata.code = bundledCode;\n\n this.addMetadata(packageMetadata);\n }\n\n // In dev mode, we don't need to tree-shake.\n if (!this.production) return;\n\n // Re-bundle pass: handle packages imported by other packages\n\n for (const { dependencyOutputPath, dependencyName, importerName, importerOutputPath } of pendingReBundles) {\n // The bundled package to re-bundle with the new specifiers.\n const packageToBundle = this.metadataList.find(m => m.filePath === dependencyOutputPath);\n if (!isPackageMetadata(packageToBundle)) {\n printFormattedError(\n `Re-bundle failed: could not find bundled asset for \"${dependencyOutputPath}\".`,\n `The package \"${dependencyName}\" is not bundled.`\n );\n continue;\n }\n\n // The bundled package that has the new specifiers.\n const importerBundle = this.metadataList.find(m => m.filePath === importerOutputPath);\n if (!isPackageMetadata(importerBundle)) {\n printFormattedError(\n `Re-bundle failed: could not find bundled asset for \"${importerOutputPath}\".`,\n `The package \"${importerName}\" is not bundled.`\n );\n continue;\n }\n\n // Heavy task, parse the bundled package into a script metadata\n const importerScript = await this.load(importerBundle.filePath, { code: importerBundle.code, type: \"js\" });\n if (!isScriptMetadata(importerScript)) {\n printFormattedError(\n `Re-bundle failed: could not parse asset \"${importerOutputPath}\" as a script.`,\n `The package \"${importerName}\" may be missing specifiers.`\n );\n continue;\n }\n\n const sources = collectSpecifiersFromAst(importerScript.ast);\n\n const collectedSpecifiers: Specifier[] = [];\n\n for (const sourceReference of sources) {\n const source = sourceReference.source;\n const sourceRootRelative = join(dirname(importerScript.filePath), source);\n\n // Focus only on imports that resolve to the dependency's output path.\n if (sourceRootRelative === dependencyOutputPath) {\n const specifiers = sourceReference.specifiers;\n collectedSpecifiers.push(...specifiers);\n }\n }\n\n if (collectedSpecifiers.length === 0) {\n printFormattedError(\n `Re-bundle failed: could not find an import of \"${dependencyOutputPath}\" inside \"${importerOutputPath}\".`,\n `\\nThe dependency \"${dependencyName}\" may be missing specifiers.`\n );\n continue;\n }\n\n // Failed to find correct specifiers for this package.\n const isUnknownSpecifier = collectedSpecifiers.some(specifier => specifier.type === \"unknown\");\n if (isUnknownSpecifier) {\n this.log.warn(\n `Cannot tree-shake the package \"${dependencyName}\" correctly. The package \"${importerName}\" has dynamic imports with unresolved specifiers.`\n );\n continue;\n }\n\n // Merge the newly discovered specifiers with any already collected,\n // filtering out duplicates that are already present.\n const allSpecifiers: Specifier[] = specifiersByPackage.get(dependencyName) ?? [];\n const newSpecifiers = diffSpecifiers(allSpecifiers, collectedSpecifiers);\n\n // If every specifier is already covered, the existing bundle is complete — skip.\n if (newSpecifiers.length === 0) {\n continue;\n }\n\n allSpecifiers.push(...newSpecifiers);\n specifiersByPackage.set(dependencyName, allSpecifiers);\n\n // We are going to re-collect the direct dependencies during rebundling, so we need to clear them first\n packageToBundle.directDependencies.clear();\n\n // Add the new specifiers to the existing bundle\n const contents = generateStdinString(allSpecifiers, dependencyName);\n\n const [reBundledCode, reBundleError] = await bundlePackage({\n contents,\n resolveDir: this.root,\n outfile: dependencyOutputPath,\n packageName: dependencyName,\n production: this.production,\n minify: true,\n treeShaking: true,\n onPackageResolve: importedPackageName => {\n const packageChunkName = getChunkName(importedPackageName, chunks);\n const packageOrChunkName = packageChunkName ?? importedPackageName;\n\n const dependencyOutputPath = calcPackageOutPath(packageOrChunkName, packagesOutputDirection);\n packageToBundle.directDependencies.add(dependencyOutputPath);\n const relativePathFromImporter = relative(dirname(packageToBundle.filePath), dependencyOutputPath);\n\n return { path: relativePathFromImporter, external: true };\n },\n });\n\n if (reBundleError) {\n printFormattedError(`Failed to re-bundle package \"${dependencyName}\"`, reBundleError);\n continue;\n }\n\n // Replace the old bundle with the new one\n packageToBundle.code = reBundledCode;\n }\n },\n };\n}\n","import { mkdirSync } from \"node:fs\";\nimport * as t from \"@babel/types\";\nimport { HTMLElement } from \"@staticbolt/node-html-parser\";\nimport { globSync } from \"glob\";\n\nimport { isValidRelativePath, splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { filterScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { basename, dirname, join, isPathMatch, relative, replaceExtension } from \"../../utilities/path.ts\";\n\nimport type { App, Plugin } from \"@staticbolt/core\";\n\nexport type ImageFormat = \"webp\" | \"avif\" | \"png\" | \"jpeg\";\nexport type ImagePreset = \"default\" | \"photo\" | \"picture\" | \"drawing\" | \"icon\" | \"text\";\n\nexport interface ConvertImageOptions {\n /**\n * Format to convert images to.\n *\n * @default webp\n */\n format?: ImageFormat;\n\n /**\n * Image quality of the output image `(1-100)`.\n *\n * @default 100\n */\n quality?: number;\n\n /**\n * Presets for image compression (work for `WebP` format only).\n *\n * @default default\n */\n preset?: ImagePreset;\n\n /**\n * Glob patterns to include in image processing.\n *\n * @default [\"sources/assets/**\\/*.{jpg,jpeg,png}\"]\n */\n include?: string[];\n\n /**\n * Glob patterns to ignore in image processing.\n *\n * @default [ ]\n */\n exclude?: string[];\n}\n\n/**\n * Converts the images matched by \"include\" to a single target format with sharp, and rewrites every reference to them.\n *\n * References are updated wherever the sources pipeline sees them (HTML attributes, styles, scripts, web manifest); an \"image/*\"\n * type on the tag or manifest entry is rewritten too. In scripts, \"_img.<ext>\" expressions are replaced with the format string,\n * so the same code resolves to the original extension in development and to the converted one in production.\n *\n * Quality and preset can be overridden per file through the filename: \"hero-q:75-p:picture.jpg\".\n *\n * Notes:\n *\n * - Conversion happens after the build and only in production; development keeps serving the originals untouched.\n * - The output mirrors the source path relative to the project root, with only the extension replaced.\n * - Converted sources are published on \"pluginData.convertedImages\" so copy-assets does not copy the originals over them.\n * - \"preset\" is a WebP-only option and is ignored by the other formats.\n */\nexport function convertImagePlugin(options: ConvertImageOptions = {}): Plugin {\n const format = options.format ?? \"webp\";\n const include = options.include ?? [\"sources/assets/**/*.{jpg,jpeg,png}\"];\n const ignore = options.exclude ?? [];\n const preset = options.preset ?? \"default\";\n const quality = options.quality ?? 100;\n\n /** - Replaces an image relative path extension if it is included to be converted */\n function replaceImgExtension(this: App, source: string, filePath: string) {\n // absolute url or not a file path\n if (!isValidRelativePath(source)) return;\n\n const [link, suffix] = splitHtmlLink(source);\n\n const relativeToRoot = join(dirname(filePath), link);\n\n if (!isPathMatch(relativeToRoot, { include, ignore, root: this.root })) return;\n\n return {\n newSource: replaceExtension(link, \".\" + format) + suffix,\n imgPath: join(this.root, relativeToRoot),\n };\n }\n\n const supported = new Set([\"png\", \"jpg\", \"jpeg\", \"webp\", \"avif\"]);\n const convertedImages = new Set<string>();\n\n return {\n name: \"convert-images\",\n\n setup() {\n if (this.production) {\n this.pluginData.convertedImages ??= convertedImages;\n }\n },\n\n async transform(inputMetadata) {\n for (const { metadata } of filterScriptMetadata(inputMetadata)) {\n const log = this.log;\n const isProduction = this.production;\n\n t.traverse(metadata.ast, {\n enter(node, ancestors) {\n if (!t.isMemberExpression(node) || !t.isIdentifier(node.property)) return;\n if (!t.isIdentifier(node.object, { name: \"_img\" })) return;\n\n const property = node.property.name;\n if (!supported.has(property)) return;\n\n const capturedAncestor = ancestors.at(-1);\n if (!capturedAncestor) {\n log.error(\"Internal error. Couldn't find ancestor\");\n return;\n }\n\n const parentNode = capturedAncestor.node;\n\n const newNode = t.stringLiteral(isProduction ? format : property);\n\n if (capturedAncestor.index === undefined) {\n // @ts-expect-error so many wrong types\n parentNode[capturedAncestor.key] = newNode;\n return;\n }\n\n // @ts-expect-error so many wrong types\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n parentNode[capturedAncestor.key][capturedAncestor.index] = newNode;\n },\n });\n }\n\n if (!this.production) return;\n\n const sources = await this.requestSources(inputMetadata);\n for (const sourceReference of sources) {\n const source = sourceReference.source;\n\n const replaceResults = replaceImgExtension.call(this, source, inputMetadata.filePath);\n if (!replaceResults) continue;\n\n sourceReference.source = replaceResults.newSource;\n\n // HTML link with image type\n if (sourceReference.node instanceof HTMLElement) {\n const imgType = sourceReference.node.getAttribute(\"type\");\n if (imgType?.startsWith(\"image/\")) {\n sourceReference.node.setAttribute(\"type\", `image/${format}`);\n }\n }\n\n // Web Manifest entry with image type\n if (sourceReference.node && \"src\" in sourceReference.node && \"type\" in sourceReference.node) {\n sourceReference.node.type = `image/${format}`;\n }\n }\n },\n\n async postBuild() {\n if (!this.production) return;\n\n this.pluginData.convertedImages ??= convertedImages;\n\n const imageFiles = globSync(include, { ignore, nodir: true, cwd: this.root });\n\n const { default: sharp } = await import(\"sharp\");\n\n const promises = imageFiles.map(file => {\n const absImgPath = join(this.root, file);\n convertedImages.add(absImgPath);\n\n const relativeToRoot = relative(this.root, absImgPath);\n const outputFile = join(this.outdir, replaceExtension(relativeToRoot, `.${format}`));\n mkdirSync(dirname(outputFile), { recursive: true });\n\n const parsed = parseOptionFromImgPath(basename(relativeToRoot), quality, preset);\n return sharp(absImgPath).toFormat(format, parsed).toFile(outputFile);\n });\n\n await Promise.all(promises);\n },\n };\n}\n\nfunction parseOptionFromImgPath(imgPath: string, defaultQuality: number, defaultPreset: string) {\n // extract quality from filename matching \"image-q:100.png\"\n const qualityMatch = imgPath.match(/-q:(\\d{1,3})/)?.[1];\n const quality = qualityMatch === undefined ? defaultQuality : Number.parseInt(qualityMatch);\n\n // extract preset from filename matching \"image-p:default.png\"\n const presetMatch = imgPath.match(/-p:(default|photo|picture|drawing|icon|text)/)?.[1];\n const preset = (presetMatch ?? defaultPreset) as ImagePreset;\n\n return { quality, preset };\n}\n","import { copyFileSync, existsSync, mkdirSync } from \"node:fs\";\nimport { globSync } from \"glob\";\n\nimport { dirname, join } from \"../../utilities/path.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface CopyAssetsOptions {\n /**\n * Glob patterns to copy and include.\n *\n * @default [\"sources/assets/**\\/*\"]\n */\n include?: string[];\n\n /**\n * Glob patterns to ignore and exclude when copying asset files.\n *\n * @default [ ]\n */\n exclude?: string[];\n\n /**\n * Files in the public directory are copied to the root of the output directory.\n *\n * @default \"public\"\n */\n publicDirectory?: string;\n}\n\n/**\n * Copies asset files into the output directory at the end of a production build.\n *\n * Two passes: files matching \"include\" keep their path relative to the project root, while everything under \"publicDirectory\" is\n * copied to the output root with that prefix dropped (e.g. \"public/favicon.ico\" becomes \"<outdir>/favicon.ico\").\n *\n * Notes:\n *\n * - Runs after the build and only in production.\n * - Existing output files are never overwritten, and assets other plugins already emitted (converted images, optimized SVGs) are\n * skipped so the originals cannot replace them.\n * - \"exclude\" applies to both passes; the public pass also copies dotfiles.\n */\nexport function copyAssetsPlugin(options: CopyAssetsOptions = {}): Plugin {\n const include = options.include ?? [\"sources/assets/**/*\"];\n const ignore = options.exclude ?? [];\n const publicDirectory = options.publicDirectory ?? \"public\";\n\n return {\n name: \"copy-assets\",\n\n postBuild() {\n if (!this.production) return;\n\n const convertedImages = (this.pluginData.convertedImages as Set<string> | undefined) ?? new Set<string>();\n const optimizedSvgList = (this.pluginData.optimizedSvgList as Set<string> | undefined) ?? new Set<string>();\n\n const assetsFiles = globSync(include, { ignore, nodir: true, cwd: this.root });\n\n for (const file of assetsFiles) {\n const inputFile = join(this.root, file); // abs\n\n // ignore images that are converted\n if (convertedImages.has(inputFile)) continue;\n\n // optimized svg\n if (optimizedSvgList.has(inputFile)) continue;\n\n const outputFile = join(this.outdir, file);\n\n if (existsSync(outputFile)) continue;\n\n mkdirSync(dirname(outputFile), { recursive: true });\n\n copyFileSync(inputFile, outputFile);\n }\n\n const publicFiles = globSync(\"**/*\", { ignore, nodir: true, cwd: join(this.root, publicDirectory), dot: true });\n\n for (const file of publicFiles) {\n const inputFile = join(this.root, publicDirectory, file); // abs\n\n // ignore images that are converted\n if (convertedImages.has(inputFile)) continue;\n\n // optimized svg\n if (optimizedSvgList.has(inputFile)) continue;\n\n const outputFile = join(this.outdir, file);\n\n if (existsSync(outputFile)) continue;\n\n mkdirSync(dirname(outputFile), { recursive: true });\n\n copyFileSync(inputFile, outputFile);\n }\n },\n };\n}\n","import type { EaseFunction, ViewBox } from \"./types.js\";\n\n/** - Converts a path string to two dimensional array `[[M], ...[C]]` */\nexport function getPointsFromPathString(path: string, viewBox: ViewBox) {\n const x = viewBox.x;\n const y = viewBox.y;\n const height = viewBox.height;\n const width = viewBox.width;\n\n // get numbers from the string and convert them from percentage values.\n const match = path.match(/-?[0-9.]+/g);\n if (!match) throw new Error(\"invalid path\");\n\n const pathData = match.map((v, index) => (index % 2 === 0 ? Number(v) * width + x : Number(v) * height + y));\n\n const points: number[][] = [];\n\n if (pathData.length === 0) return points;\n\n points.push([pathData[0], pathData[1]]); // M points\n\n // C points\n for (let index = 2; index < pathData.length; index += 6) {\n points.push([\n pathData[index],\n pathData[index + 1],\n pathData[index + 2],\n pathData[index + 3],\n pathData[index + 4],\n pathData[index + 5],\n ]);\n }\n\n return points;\n}\n\n/** Computes the point (x, y) on the curve for a given time `t` [0 to 1] */\nfunction findPointFromT(\n p0x: number,\n p0y: number,\n c0x: number,\n c0y: number,\n c1x: number,\n c1y: number,\n p1x: number,\n p1y: number,\n t: number\n) {\n const point = { x: 0, y: 0 };\n const mt = 1 - t;\n const mt2 = mt * mt;\n const mt3 = mt2 * mt;\n\n point.x = p0x * mt3 + c0x * 3 * mt2 * t + c1x * 3 * mt * t * t + p1x * t ** 3;\n point.y = p0y * mt3 + c0y * 3 * mt2 * t + c1y * 3 * mt * t * t + p1y * t ** 3;\n\n return point;\n}\n\n/** Computes the Y-coordinate of a point on the curve given its X-coordinate. */\nfunction solvePositionYFromT(\n p0x: number,\n p0y: number,\n c0x: number,\n c0y: number,\n c1x: number,\n c1y: number,\n p1x: number,\n p1y: number,\n t: number\n): number {\n // Desired precision on the computation.\n const epsilon = 1e-6;\n\n // A binary search algorithm is used to determine the Y-coordinate value\n // corresponding to a specified position on the X-coordinate.\n let start = 0;\n let end = 1;\n let target = (start + end) / 2;\n let times = 0;\n\n while (target >= start && target <= 1) {\n const { x, y } = findPointFromT(p0x, p0y, c0x, c0y, c1x, c1y, p1x, p1y, target);\n\n // If the point cannot be found within 50 attempts, a safe loop break will be triggered.\n if (++times > 50) return y;\n\n // Return the located Y-coordinate value.\n if (Math.abs(x - t) <= epsilon) return y;\n\n if (x >= t) end = target;\n else start = target;\n\n target = (start + end) / 2;\n }\n\n return 0;\n}\n\nexport function generateEasingFunctionFromArray(curves: number[][]) {\n return (t: number) => {\n if (t === 0) return curves[0][1];\n if (t === 1) return curves.at(-1)![7];\n\n for (const [p0x, p0y, c0x, c0y, c1x, c1y, p1x, p1y] of curves) {\n if (t <= p1x) {\n return solvePositionYFromT(p0x, p0y, c0x, c0y, c1x, c1y, p1x, p1y, t);\n }\n }\n\n return 0;\n };\n}\n\n/** Converts the values in a two-dimensional array to percentage values (ranging from 0 to 1). */\nfunction convertPointsToRelativeValues(array: number[][], viewBox: ViewBox) {\n const x = viewBox.x;\n const y = viewBox.y;\n const height = viewBox.height;\n const width = viewBox.width;\n\n return array.map(curve => curve.map((v, index) => (index % 2 === 0 ? (v - x) / width : (v - y) / height)));\n}\n\n/**\n * - Convert to relative value ->\n * - Flip the Y points ->\n * - Store only Cubic curves with starting, control, and ending points (without the first M command).\n */\nexport function preparePointsForAnimation(array: number[][], viewBox: ViewBox) {\n const relativePoints = convertPointsToRelativeValues(array, viewBox);\n\n const results: number[][] = [];\n\n let x = 0;\n let y = 0;\n for (const [index, curve] of relativePoints.entries()) {\n const c1x = curve[0];\n const c1y = 1 - curve[1];\n\n if (!index) {\n x = c1x;\n y = c1y;\n continue;\n }\n\n const c2x = curve[2];\n const c2y = 1 - curve[3];\n const px = curve[4];\n const py = 1 - curve[5];\n\n results.push([x, y, c1x, c1y, c2x, c2y, px, py]);\n\n x = px;\n y = py;\n }\n\n return results;\n}\n\n/** Runs an easing function backwards. */\nexport function out(easing: EaseFunction): EaseFunction {\n return t => 1 - easing(1 - t);\n}\n\n/**\n * Makes any easing function symmetrical. The easing function will run forwards for half of the duration, then backwards for the\n * rest of the duration.\n */\nexport function inOut(easing: EaseFunction): EaseFunction {\n return t => {\n if (t < 0.5) return easing(t * 2) / 2;\n return 1 - easing((1 - t) * 2) / 2;\n };\n}\n\nexport function convertEasingFunctionToLinearFN(easingFunction: EaseFunction, samples: number) {\n const values = new Float32Array(samples);\n let count = 0;\n\n for (let index = 0; index < samples; index++) {\n const t = index / (samples - 1);\n values[count++] = easingFunction(t);\n }\n\n const valuesString = Array.from(values, string => +string.toFixed(2)).join(\",\");\n\n return `linear(${valuesString})`;\n}\n","import {\n generateEasingFunctionFromArray,\n getPointsFromPathString,\n inOut,\n out,\n preparePointsForAnimation,\n} from \"./ease-utilities.ts\";\n\nimport type { EaseFunction } from \"./types.d.ts\";\n\nfunction spring(mass = 1, stiffness = 100, damping = 10, velocity = 0, duration = 1000): EaseFunction {\n const clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max);\n return (time: number) => {\n if (time === 0 || time === 1) return time;\n\n mass = clamp(mass, 0.1, 1000);\n stiffness = clamp(stiffness, 0.1, 1000);\n damping = clamp(damping, 0.1, 1000);\n velocity = clamp(velocity, 0.1, 1000);\n\n const w0 = Math.sqrt(stiffness / mass),\n zeta = damping / (2 * Math.sqrt(stiffness * mass)),\n wd = zeta < 1 ? w0 * Math.sqrt(1 - zeta * zeta) : 0,\n a = 1,\n b = zeta < 1 ? (zeta * w0 + -velocity) / wd : -velocity + w0;\n\n let progress = duration ? (duration * time) / 1000 : time;\n\n progress =\n zeta < 1\n ? Math.exp(-progress * zeta * w0) * (a * Math.cos(wd * progress) + b * Math.sin(wd * progress))\n : (a + b * progress) * Math.exp(-progress * w0);\n\n return 1 - progress;\n };\n}\n\nfunction wobble(bounciness = 1): EaseFunction {\n const p = bounciness * Math.PI;\n return (t: number): number => 1 - Math.pow(Math.cos((t * Math.PI) / 2), 3) * Math.cos(t * p);\n}\n\nfunction bounce(t: number): number {\n const n1 = 7.5625;\n const d1 = 2.75;\n if (t < 1 / d1) return n1 * t * t;\n if (t < 2 / d1) return n1 * (t -= 1.5 / d1) * t + 0.75;\n if (t < 2.5 / d1) return n1 * (t -= 2.25 / d1) * t + 0.9375;\n return n1 * (t -= 2.625 / d1) * t + 0.984375;\n}\n\nfunction custom(path: string) {\n const viewBox = { x: 0, y: 0, width: 1, height: 1 };\n const curves = getPointsFromPathString(path, viewBox);\n const relativeCurves = preparePointsForAnimation(curves, viewBox);\n\n return generateEasingFunctionFromArray(relativeCurves);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const predefinedEasing: Record<string, string | ((...arguments_: any[]) => EaseFunction)> = {\n spring,\n custom,\n\n // IN\n \"in-circ\": \"cubic-bezier(0.55, 0, 1, 0.45)\",\n \"in-cubic\": \"cubic-bezier(0.32, 0, 0.67, 0)\",\n \"in-expo\": \"cubic-bezier(0.7, 0, 0.84, 0)\",\n \"in-sine\": \"cubic-bezier(0.12, 0, 0.39, 0)\",\n \"in-quad\": \"cubic-bezier(0.11, 0, 0.5, 0)\",\n \"in-quart\": \"cubic-bezier(0.5, 0, 0.75, 0)\",\n \"in-quint\": \"cubic-bezier(0.64, 0, 0.78, 0)\",\n \"in-back\": (c1 = 1.70158) => {\n return (t: number) => (c1 + 1) * t * t * t - c1 * t * t;\n },\n \"in-bounce\": () => (t: number) => 1 - bounce(1 - t),\n \"in-elastic\": () => (t: number) => {\n const c4 = (2 * Math.PI) / 3;\n return t === 0 ? 0 : t === 1 ? 1 : -Math.pow(2, 10 * t - 10) * Math.sin((t * 10 - 10.75) * c4);\n },\n \"in-poly\": (n: number) => (t: number) => Math.pow(t, n),\n \"in-wobble\": (bounciness: number = 1) => out(wobble(bounciness)),\n\n // OUT\n \"out-circ\": \"cubic-bezier(0, 0.55, 0.45, 1)\",\n \"out-cubic\": \"cubic-bezier(0.33, 1, 0.68, 1)\",\n \"out-expo\": \"cubic-bezier(0.16, 1, 0.3, 1)\",\n \"out-sine\": \"cubic-bezier(0.61, 1, 0.88, 1)\",\n \"out-quad\": \"cubic-bezier(0.5, 1, 0.89, 1)\",\n \"out-quart\": \"cubic-bezier(0.25, 1, 0.5, 1)\",\n \"out-quint\": \"cubic-bezier(0.22, 1, 0.36, 1)\",\n \"out-back\": (c1: number = 1.70158) => {\n return (t: number) => {\n const c3 = c1 + 1;\n return 1 + c3 * Math.pow(t - 1, 3) + c1 * Math.pow(t - 1, 2);\n };\n },\n \"out-bounce\": () => bounce,\n \"out-elastic\": () => (t: number) => {\n const c4 = (2 * Math.PI) / 3;\n return t === 0 ? 0 : t === 1 ? 1 : Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * c4) + 1;\n },\n \"out-poly\": (n: number) => (t: number) => 1 - Math.pow(1 - t, n),\n \"out-wobble\": wobble,\n\n // IN-OUT\n \"in-out-circ\": \"cubic-bezier(0.85, 0, 0.15, 1)\",\n \"in-out-cubic\": \"cubic-bezier(0.65, 0, 0.35, 1)\",\n \"in-out-expo\": \"cubic-bezier(0.87, 0, 0.13, 1)\",\n \"in-out-sine\": \"cubic-bezier(0.37, 0, 0.63, 1)\",\n \"in-out-quad\": \"cubic-bezier(0.45, 0, 0.55, 1)\",\n \"in-out-quart\": \"cubic-bezier(0.76, 0, 0.24, 1)\",\n \"in-out-quint\": \"cubic-bezier(0.83, 0, 0.17, 1)\",\n \"in-out-back\": (c1 = 1.70158) => {\n return (t: number) => {\n const c2 = c1 * 1.525;\n return t < 0.5\n ? (Math.pow(2 * t, 2) * ((c2 + 1) * 2 * t - c2)) / 2\n : (Math.pow(2 * t - 2, 2) * ((c2 + 1) * (t * 2 - 2) + c2) + 2) / 2;\n };\n },\n \"in-out-bounce\": () => (t: number) => (t < 0.5 ? (1 - bounce(1 - 2 * t)) / 2 : (1 + bounce(2 * t - 1)) / 2),\n \"in-out-elastic\": () => (t: number) => {\n const c5 = (2 * Math.PI) / 4.5;\n return t === 0\n ? 0\n : t === 1\n ? 1\n : t < 0.5\n ? -(Math.pow(2, 20 * t - 10) * Math.sin((20 * t - 11.125) * c5)) / 2\n : (Math.pow(2, -20 * t + 10) * Math.sin((20 * t - 11.125) * c5)) / 2 + 1;\n },\n \"in-out-poly\": (n: number) => (t: number) => (t < 0.5 ? Math.pow(2, n - 1) * Math.pow(t, n) : 1 - Math.pow(-2 * t + 2, n) / 2),\n \"in-out-wobble\": (bounciness: number = 1) => inOut(wobble(bounciness)),\n};\n","import * as t from \"@babel/types\";\n\nimport { filterScriptMetadata, filterStyleMetadata, isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { printFmtError } from \"../../utilities/print-formatted-error.ts\";\nimport { convertEasingFunctionToLinearFN } from \"./easing-functions/ease-utilities.ts\";\nimport { predefinedEasing } from \"./easing-functions/ease.ts\";\n\nimport type { EaseFunction } from \"./easing-functions/types.d.ts\";\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface CustomEasePluginOptions {\n /**\n * Transform JS calls like `cssLinear.outCubic()` into their CSS easing string.\n *\n * @example\n * const ease = cssLinear.outCubic();\n * // → \"cubic-bezier(0.215, 0.61, 0.355, 1)\"\n *\n * @default false\n */\n replaceInJS?: boolean;\n\n /**\n * Name of the JS function namespace used for easing calls. The plugin looks for calls like `<name>.<ease>()`.\n *\n * @example\n * const ease = cssLinear.outCubic();\n *\n * @default \"cssLinear\"\n */\n jsFunctionName?: string;\n\n /**\n * Enable replacement of custom easing functions used in CSS.\n *\n * ```css\n * :root {\n * --custom-ease: --ease-out-cubic();\n * }\n * ```\n *\n * @default true\n */\n replaceInCSS?: boolean;\n\n /**\n * Prefix used to detect custom easing functions in CSS. Any function starting with this prefix will be replaced.\n *\n * ```css\n * :root {\n * --custom-ease: --ease-out-cubic();\n * }\n * ```\n *\n * @default \"--ease-\"\n */\n cssFunctionPrefix?: string;\n\n /**\n * Also process custom easing functions inside inline `style` attributes in HTML.\n *\n * ```html\n * <div style=\"--custom-ease: --ease-out-cubic()\"></div>\n * ```\n *\n * @default false\n */\n replaceInHtmlStyleAttribute?: boolean;\n\n /**\n * Additional custom easing definitions. Values can be either:\n *\n * - A CSS easing string\n * - A function returning a JS easing function\n *\n * @example\n * const customEase = {\n * \"in-circ\": \"cubic-bezier(0.55, 0, 1, 0.45)\",\n * \"out-poly\": (n: number) => (t: number) => 1 - Math.pow(1 - t, n),\n * };\n */\n customEase?: Record<string, string | ((...arguments_: unknown[]) => EaseFunction)>;\n\n /**\n * Number of samples used when converting easing functions to CSS `linear()`.\n *\n * Represents a balance between output quality and performance.\n *\n * @default 50\n */\n samples?: number;\n}\n\nexport type { CssLinear } from \"./easing-functions/types.d.ts\";\n\n/**\n * Replaces named easing calls with plain CSS values at build time, so there is nothing to resolve at runtime. Simple curves\n * become a \"cubic-bezier()\" string, computed ones (springs, bounces, elastics) are sampled into a \"linear()\" function.\n *\n * Three places, each with its own switch: CSS declarations (on by default, \"--ease-*()\" calls), JavaScript\n * (\"cssLinear.outCubic()\", opt-in) and inline HTML \"style\" attributes (opt-in).\n *\n * Notes:\n *\n * - Runs in development and production alike.\n * - JS call names are camelCase and matched kebab-cased, so \"cssLinear.outCubic()\" resolves the \"out-cubic\" definition.\n * - Anything that does not resolve is left exactly as written: unknown names, unbalanced parentheses, or arguments that are not\n * plain numbers (in JS they must be numeric literals).\n * - \"customEase\" entries are merged over the predefined set, so reusing a name overrides it.\n * - \"samples\" trades output size for accuracy; it only affects easings that end up as \"linear()\".\n */\nexport function customEasePlugin(options: CustomEasePluginOptions = {}): Plugin {\n options.customEase ??= {};\n const customEasing = { ...predefinedEasing, ...options.customEase };\n\n const shouldReplaceInHtml = options.replaceInHtmlStyleAttribute ?? false;\n\n const shouldReplaceInJS = options.replaceInJS ?? false;\n const jsFunctionName = options.jsFunctionName ?? \"cssLinear\";\n\n const shouldReplaceInCSS = options.replaceInCSS ?? true;\n const cssFunctionPrefix = options.cssFunctionPrefix ?? \"--ease-\";\n\n const samples = options.samples ?? 50;\n\n /** The CSS easing string for one custom easing call, or `undefined` when it cannot be resolved */\n function resolveEasing(name: string, arguments_: number[] | undefined, filePath: string): string | undefined {\n if (!arguments_) return;\n\n const easeFunctionName = name.slice(cssFunctionPrefix.length);\n if (!Object.hasOwn(customEasing, easeFunctionName)) return;\n\n const easeFunctionOrString = customEasing[easeFunctionName];\n\n // CSS Cubic Bezier string\n if (typeof easeFunctionOrString === \"string\") {\n return easeFunctionOrString;\n }\n\n try {\n return convertEasingFunctionToLinearFN(easeFunctionOrString(...arguments_), samples);\n } catch {\n printFmtError(\"Error generating easing function\", { function: customEasePlugin, filePath });\n }\n }\n\n /** Replace every custom easing call in a CSS value, leaving unknown and malformed ones as they are */\n function replaceEaseCalls(value: string, filePath: string): string {\n let output = \"\";\n let cursor = 0;\n\n while (cursor < value.length) {\n const { name, matchStartIndex, matchEndIndex, args } = parseFunctionCall(value.slice(cursor), cssFunctionPrefix);\n if (matchStartIndex < 0) break;\n\n const call = value.slice(cursor + matchStartIndex, cursor + matchEndIndex);\n output += value.slice(cursor, cursor + matchStartIndex) + (resolveEasing(name, args, filePath) ?? call);\n cursor += matchEndIndex;\n }\n\n return output + value.slice(cursor);\n }\n\n return {\n name: \"custom-ease\",\n\n transform(inputMetadata) {\n if (shouldReplaceInHtml && isHtmlMetadata(inputMetadata)) {\n const elements = inputMetadata.ast.querySelectorAll(\"[style]\");\n\n for (const node of elements) {\n const style = node.getAttribute(\"style\");\n if (!style) continue;\n\n const replaced = replaceEaseCalls(style, inputMetadata.id);\n if (replaced !== style) {\n node.setAttribute(\"style\", replaced);\n }\n }\n }\n\n if (shouldReplaceInJS) {\n for (const { metadata } of filterScriptMetadata(inputMetadata)) {\n t.traverse(metadata.ast, {\n enter(node, ancestors) {\n if (!t.isCallExpression(node)) return;\n\n const callee = node.callee;\n\n if (!t.isMemberExpression(callee) || !t.isIdentifier(callee.object) || !t.isIdentifier(callee.property)) {\n return;\n }\n\n if (callee.object.name !== jsFunctionName) {\n return;\n }\n\n const functionName = callee.property.name.replace(/[A-Z]/g, match => \"-\" + match.toLowerCase());\n if (!Object.hasOwn(customEasing, functionName)) return;\n\n const easeFunctionOrString = customEasing[functionName];\n\n const capturedAncestor = ancestors.at(-1);\n if (!capturedAncestor) {\n printFmtError(\"Internal error. Couldn't find ancestor\", { node });\n return;\n }\n\n const parentNode = capturedAncestor.node;\n\n const replaceWith = (newValue: string) => {\n const newNode = t.stringLiteral(newValue);\n\n if (capturedAncestor.index === undefined) {\n // @ts-expect-error so many wrong types\n parentNode[capturedAncestor.key] = newNode;\n return;\n }\n\n // @ts-expect-error so many wrong types\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n parentNode[capturedAncestor.key][capturedAncestor.index] = newNode;\n };\n\n // CSS Cubic Bezier string\n if (typeof easeFunctionOrString === \"string\") {\n replaceWith(easeFunctionOrString);\n return;\n }\n\n const arguments_: number[] = [];\n for (const argument of node.arguments) {\n if (!t.isNumericLiteral(argument)) {\n // TODO: error all args must be numbers\n return;\n }\n\n arguments_.push(argument.value);\n }\n\n const linearFunction = convertEasingFunctionToLinearFN(easeFunctionOrString(...arguments_), samples);\n\n replaceWith(linearFunction);\n },\n });\n }\n }\n\n if (shouldReplaceInCSS) {\n for (const { metadata } of filterStyleMetadata(inputMetadata)) {\n metadata.ast.walkDecls(declaration => {\n const replaced = replaceEaseCalls(declaration.value, inputMetadata.id);\n if (replaced !== declaration.value) {\n declaration.value = replaced;\n }\n });\n }\n }\n },\n };\n}\n\ninterface ParseFunctionCallResult {\n name: string;\n matchStartIndex: number;\n matchEndIndex: number;\n /** `undefined` when the argument list is not a plain list of numbers */\n args: number[] | undefined;\n}\n\nconst NOT_FOUND: ParseFunctionCallResult = { name: \"\", matchStartIndex: -1, matchEndIndex: -1, args: [] };\n\nconst functionCallReCache = new Map<string, RegExp>();\n\n/** Parse a string representing a function call and get its arguments and name */\nfunction parseFunctionCall(code: string, functionNamePrefix: string): ParseFunctionCallResult {\n let re = functionCallReCache.get(functionNamePrefix);\n if (!re) {\n const escapedPrefix = functionNamePrefix.replace(/[$()*+.?[\\\\\\]^{|}]/g, String.raw`\\$&`);\n re = new RegExp(String.raw`(?<![\\w-])(${escapedPrefix}[\\w-]*)\\(`);\n functionCallReCache.set(functionNamePrefix, re);\n }\n\n const match = re.exec(code);\n const name = match?.[1];\n if (!match || !name) {\n return NOT_FOUND;\n }\n\n const openIndex = match.index + match[0].length - 1;\n const closeIndex = findClosingParenthesis(code, openIndex);\n if (closeIndex < 0) {\n return NOT_FOUND;\n }\n\n const result: ParseFunctionCallResult = {\n name,\n matchStartIndex: match.index,\n matchEndIndex: closeIndex + 1,\n args: [],\n };\n\n const argumentsString = code.slice(openIndex + 1, closeIndex).trim();\n if (!argumentsString) {\n return result;\n }\n\n result.args = parseNumericArguments(argumentsString);\n if (!result.args) {\n console.warn(`Failed to parse function call: ${code.slice(match.index, closeIndex + 1)}`);\n }\n\n return result;\n}\n\n/** - Split a CSS argument list into numbers, or `undefined` when any of them is not a number */\nfunction parseNumericArguments(argumentsString: string): number[] | undefined {\n const arguments_: number[] = [];\n\n for (const part of argumentsString.split(\",\")) {\n const argument = Number(part);\n\n if (part.trim() === \"\" || Number.isNaN(argument)) {\n return;\n }\n\n arguments_.push(argument);\n }\n\n return arguments_;\n}\n\n/** Index of the `)` closing the `(` at `openIndex`, or `-1` when it is never closed */\nfunction findClosingParenthesis(code: string, openIndex: number): number {\n let depth = 0;\n\n for (let index = openIndex; index < code.length; index++) {\n const char = code[index];\n\n if (char === \"(\") {\n depth++;\n continue;\n }\n\n if (char === \")\") {\n depth--;\n if (depth === 0) {\n return index;\n }\n }\n }\n\n return -1;\n}\n","import { Log } from \"../../utilities/logger.ts\";\nimport { join } from \"../../utilities/path.ts\";\nimport { readJsonFile } from \"../../utilities/read-json-file.ts\";\n\ninterface RecursiveRecord {\n [key: string]: string | RecursiveRecord;\n}\n\nexport interface GetLocalsResult {\n /** An object the key is the language and the value is a map of keysPath-value */\n localesMap: { [key: string]: Map<string, string> };\n\n /** An object the key is the language and the value is a data of the language */\n localesObj: Record<string, RecursiveRecord>;\n\n getKey(key: string, locale: string): string;\n}\n\ninterface GetLocalsOptions {\n localesPath: string;\n supportedLocales: string[];\n}\n\nexport function getLocals(options: GetLocalsOptions) {\n if (getLocals.cache) {\n return getLocals.cache;\n }\n\n const { supportedLocales, localesPath } = options;\n\n const result: GetLocalsResult = {\n localesMap: {},\n localesObj: {},\n getKey(key: string, locale: string) {\n return this.localesMap[locale]?.get(key) ?? \"\";\n },\n };\n\n for (const locale of supportedLocales) {\n const localePath = join(localesPath, locale + \".json\");\n\n const [localesData, parseError] = readJsonFile<RecursiveRecord>(localePath);\n if (parseError) {\n Log.error(`Failed to parse ${localePath}: ${parseError}`);\n continue;\n }\n\n result.localesObj[locale] = localesData;\n\n const pathValueMap = getAllPathsMap(localesData);\n result.localesMap[locale] = pathValueMap;\n }\n\n getLocals.cache = result;\n\n return result;\n}\n\ngetLocals.cache = null as GetLocalsResult | null;\n\nfunction getAllPathsMap(object: RecursiveRecord, prefix = \"\", result = new Map<string, string>()) {\n for (const key in object) {\n const path = prefix ? `${prefix}.${key}` : key;\n\n if (Object.hasOwn(object, key) && typeof object[key] === \"object\" && !Array.isArray(object[key])) {\n getAllPathsMap(object[key], path, result);\n continue;\n }\n\n result.set(path, (object as Record<string, string>)[key]);\n }\n\n return result;\n}\n","import { isValidRelativePath, splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { extname, isAbsolute, join, normalize, relative } from \"../../utilities/path.ts\";\nimport { getLocals, type GetLocalsResult } from \"./get-locales.ts\";\n\nimport type { I18nPluginOptions } from \"./i18n-plugin.ts\";\nimport type { HtmlMetadata, Plugin } from \"@staticbolt/core\";\n\nexport const propertyRe = /{{\\s+\\b(.*?)\\b(?:=(.*?))?\\s+}}/g;\n\n/**\n * The HTML half of i18nPlugin: once the page is transformed it is cloned per supported locale, and the translation markers are\n * resolved in each copy.\n *\n * Attributes:\n *\n * - \"i18n\": the key whose value becomes the element's text content.\n * - \"i18n-attr-<name>\": the key whose value becomes the \"<name>\" attribute.\n * - \"i18n-placeholder-<name>\": the value for a \"{{ name }}\" placeholder in the translation, or \"@another.key\" to reuse another\n * translation (\"@@\" escapes a literal \"@\").\n *\n * All three are removed from the output, and \"<html lang>\" is set to the locale of the copy.\n *\n * Notes:\n *\n * - The default locale keeps the original paths; every other locale is moved under its own directory (\"ar/index.html\").\n * - Links to pages are deliberately not rebased when a page moves into a locale directory, so they keep pointing inside that\n * locale; asset links are rebased as usual.\n * - The dev server strips a leading locale segment from a request and serves the same page.\n * - A missing key resolves to an empty string, and a placeholder with no value falls back to its default, then to nothing.\n */\nexport function i18nHtmlPlugin(options: Required<I18nPluginOptions>): Plugin {\n const { defaultLocale, i18nAttribute, i18nAttributePrefix, placeholderPrefix, localesDirectory, supportedLocales } = options;\n\n return {\n name: \"i18n-html-plugin\",\n\n resolveRequestPath(requestPath) {\n const [requestPathWithoutQuery] = splitHtmlLink(requestPath);\n\n const extension = extname(requestPathWithoutQuery);\n\n const isHtml = extension === \".html\" || extension === \"\";\n if (!isHtml) return;\n\n const parts = requestPath.replace(/^\\.\\//, \"\").split(\"/\");\n if (!supportedLocales.includes(parts[0])) return;\n\n const strippedRequestPath = join(...parts.slice(1));\n\n return strippedRequestPath;\n },\n\n // When rebasing for i18n (internationalization), skip links that point to HTML or Markdown files.\n // This is because all localized pages (e.g., ar/index.html) are moved to their own language-specific directories.\n // Only static asset links—such as CSS, JS, images, etc.—need to be rebased.\n rebaseSource(source, filePath, newAbsolutePath) {\n if (!isValidRelativePath(source)) return;\n\n // Only html\n if (extname(filePath) !== \".html\") {\n return;\n }\n\n const [link] = splitHtmlLink(source);\n\n // Only links pointing to directories or html files\n const extension = extname(link);\n if (extension && extension !== \".html\") {\n return;\n }\n\n const relativeNewPath = relative(this.root, newAbsolutePath);\n\n const oldPathParts = new Set(filePath.split(\"/\"));\n const newPathParts = relativeNewPath.split(\"/\");\n\n const partsDiff = newPathParts.filter(part => !oldPathParts.has(part));\n\n if (partsDiff.length === 1 && partsDiff[0] !== defaultLocale && supportedLocales.includes(partsDiff[0])) {\n return source;\n }\n },\n\n async postTransform() {\n if (supportedLocales.length === 0) {\n return;\n }\n\n const localesPath = isAbsolute(localesDirectory) ? normalize(localesDirectory) : join(this.root, localesDirectory);\n\n const locales = getLocals({ localesPath, supportedLocales });\n\n const metadataList = Array.from(this.metadataList); // not a live list\n\n for (const inputMetadata of metadataList) {\n if (!isHtmlMetadata(inputMetadata)) continue;\n\n this.removeMetadata(inputMetadata);\n\n for (const locale of supportedLocales) {\n const isDefaultLocale = locale === defaultLocale;\n\n const metadata = this.clone(inputMetadata);\n\n this.addMetadata(metadata);\n\n if (!isDefaultLocale) {\n const newPath = join(locale, metadata.filePath);\n await this.rebase(metadata, newPath);\n }\n\n processI18nInHTML({ metadata, locales, locale, placeholderPrefix, i18nAttribute, i18nAttributePrefix });\n }\n }\n },\n };\n}\n\ninterface ProcessI18nInHTMLOptions {\n metadata: HtmlMetadata;\n locales: GetLocalsResult;\n locale: string;\n\n i18nAttribute: string;\n placeholderPrefix: string;\n i18nAttributePrefix: string;\n}\n\nfunction processI18nInHTML(options: ProcessI18nInHTMLOptions) {\n const { metadata, locales, locale, placeholderPrefix, i18nAttribute, i18nAttributePrefix } = options;\n\n const rootElement = metadata.ast.querySelector(\"html\");\n if (rootElement) {\n rootElement.setAttribute(\"lang\", locale);\n }\n\n const allElements = metadata.ast.querySelectorAll(\"*\");\n for (const node of allElements) {\n if (!node.attrs) continue;\n\n const attributeValue = Object.entries(node.attrs);\n\n const i18nNameValuePair = Object.fromEntries(\n attributeValue\n .filter(([attribute]) => attribute.startsWith(placeholderPrefix))\n .map(([attribute, value]) => [attribute.replace(placeholderPrefix, \"\"), value])\n );\n\n const replacer = (_match: string, attribute: string, defaultValue: string | undefined) => {\n if (Object.hasOwn(i18nNameValuePair, attribute)) {\n const value = i18nNameValuePair[attribute];\n\n if (typeof value === \"string\") {\n if (!value.startsWith(\"@\") || value.startsWith(\"@@\")) {\n return value.replace(/^@@/, \"@\"); // unescape @\n }\n\n const localValue = locales.getKey(value.slice(1), locale);\n if (localValue) return localValue;\n }\n }\n\n if (defaultValue !== undefined) {\n return defaultValue;\n }\n\n return \"\";\n };\n\n // replace text content\n if (Object.hasOwn(node.attributes, i18nAttribute)) {\n const keysPath = node.getAttribute(i18nAttribute);\n\n node.removeAttribute(i18nAttribute);\n\n for (const attribute of Object.keys(i18nNameValuePair)) {\n node.removeAttribute(placeholderPrefix + attribute);\n }\n\n if (!keysPath) continue;\n\n const value = locales.getKey(keysPath, locale);\n // eslint-disable-next-line unicorn/no-unsafe-string-replacement\n node.textContent = value.replace(propertyRe, replacer);\n }\n\n // replace attributes\n const i18nForAttrList = attributeValue.filter(([attribute]) => attribute.startsWith(i18nAttributePrefix));\n\n for (const [attribute, keysPath] of i18nForAttrList) {\n node.removeAttribute(attribute);\n\n for (const attribute_ of Object.keys(i18nNameValuePair)) {\n node.removeAttribute(placeholderPrefix + attribute_);\n }\n\n const attributeToReplace = attribute.replace(i18nAttributePrefix, \"\");\n const value = locales.getKey(keysPath, locale);\n // eslint-disable-next-line unicorn/no-unsafe-string-replacement\n node.setAttribute(attributeToReplace, value.replace(propertyRe, replacer));\n }\n }\n}\n","import { writeFileSync } from \"node:fs\";\n\nimport { formatCode } from \"../../helpers/format-code.ts\";\nimport { Log } from \"../../utilities/logger.ts\";\nimport { isAbsolute, join, normalize, resolve } from \"../../utilities/path.ts\";\nimport { getLocals } from \"./get-locales.ts\";\nimport { propertyRe } from \"./i18n-html-plugin.ts\";\n\nimport type { I18nPluginOptions } from \"./i18n-plugin.ts\";\nimport type { Plugin } from \"@staticbolt/core\";\n\n/**\n * The CLI half of i18nPlugin: adds a \"locales\" command (aliased \"i18n\") that regenerates the editor support files from the\n * translation JSONs and writes them next to them in \"localesDirectory\".\n *\n * - \"i18n.html-data.json\": HTML custom data, so an editor completes keys for \"i18n\", \"i18n-attr-_\" and \"i18n-placeholder-_\".\n * - \"i18n.types.d.ts\": the global i18n types and the declarations of the \"i18n_*\" compile-time helpers.\n *\n * Notes:\n *\n * - Keys are taken from the default locale's file, so anything missing there is missing from the completions and the types.\n * - Nothing regenerates these during a build; run the command again after changing the translations.\n */\nexport function i18nCliPlugin(options: Required<I18nPluginOptions>): Plugin {\n const { defaultLocale, i18nAttribute, i18nAttributePrefix, placeholderPrefix, localesDirectory, supportedLocales } = options;\n\n return {\n name: \"i18n-cli-plugin\",\n\n cli(config) {\n const localesAutocompleteCommand = this.defineSubcommand({\n name: \"locales\",\n aliases: [\"i18n\"],\n meta: {\n description: \"Generate autocomplete for locales.\",\n },\n });\n\n localesAutocompleteCommand.onExecute(async () => {\n const root = resolve(config.root ?? process.cwd());\n\n const localesPath = isAbsolute(localesDirectory) ? normalize(localesDirectory) : join(root, localesDirectory);\n\n const localesData = getLocals({ localesPath, supportedLocales });\n\n // collect all possible keys\n const keys = Array.from(localesData.localesMap[defaultLocale].keys());\n\n const placeholders = new Set<string>();\n for (const locale in localesData.localesObj) {\n const placeholders = collectPlaceholders(localesData.localesObj[locale]);\n for (const placeholder of placeholders) {\n placeholders.add(placeholder);\n }\n }\n\n // html-data.json\n const htmlDataSavePath = join(localesPath, \"i18n.html-data.json\");\n\n const attributeValues = keys.map(key => ({ name: key }));\n const placeholderValues = keys.map(key => ({ name: `@${key}` }));\n\n const htmlDataString = JSON.stringify({\n version: 1.1,\n valueSets: [\n { name: \"i18n-keys\", values: attributeValues },\n { name: \"i18n-placeholder-keys\", values: placeholderValues },\n ],\n globalAttributes: [\n ...Array.from(placeholders, placeholder => ({\n name: placeholderPrefix + placeholder,\n description:\n `Replace the placeholder \\`${placeholder}\\` with a value.\\n\\n` +\n `Example: \\`\"Hi {{ ${placeholder}=DefaultValue }}\"\\` -> \\`<div ${placeholderPrefix + placeholder}=\"someValue\"></div>\\` \\n\\n` +\n `Or use an existing i18n value:\\n\\n\\`<div ${placeholderPrefix + placeholder}=\"@header.title\"></div>\\``,\n valueSet: \"i18n-placeholder-keys\",\n })),\n {\n name: i18nAttributePrefix + \"*\",\n description: `Insert i18n value for attribute. Example: \\`<div ${i18nAttributePrefix}aria-label=\"key\"></div>\\``,\n valueSet: \"i18n-keys\",\n },\n {\n name: i18nAttribute,\n description: `Insert i18n value for text content. Example: \\`<div ${i18nAttribute}=\"key\"></div>\\``,\n valueSet: \"i18n-keys\",\n },\n ],\n });\n\n const [formattedHtmlData, formattedHtmlDataError] = await formatCode(htmlDataString, localesPath, \"json\");\n if (formattedHtmlDataError) {\n Log.error(formattedHtmlDataError.message);\n return;\n }\n\n writeFileSync(htmlDataSavePath, formattedHtmlData);\n Log.success(`Generated html-data at \"${htmlDataSavePath}\"`);\n\n // types.d.ts\n const typesSavePath = join(localesPath, \"i18n.types.d.ts\");\n const typesString = generateTypes(keys, Array.from(placeholders), supportedLocales);\n\n const [formattedTypes, formattedTypesError] = await formatCode(typesString, typesSavePath, \"ts\");\n if (formattedTypesError) {\n Log.error(formattedTypesError.message);\n return;\n }\n\n writeFileSync(typesSavePath, formattedTypes ?? typesString);\n Log.success(`Generated types at \"${typesSavePath}\"`);\n });\n\n this.addCommand(localesAutocompleteCommand);\n },\n };\n}\n\nfunction generateTypes(keys: string[], placeholders: string[], langs: string[]) {\n interface NestedStringDictionary {\n [key: string]: string | NestedStringDictionary;\n }\n\n const result: NestedStringDictionary = {};\n\n for (const key of keys) {\n const parts = key.split(\".\");\n let current = result;\n\n for (let index = 0; index < parts.length; index++) {\n const part = parts[index];\n\n // last\n if (index === parts.length - 1) {\n current[part] = \"string\";\n continue;\n }\n\n // nested\n if (!Object.hasOwn(current, part)) {\n current[part] = {};\n }\n\n current = current[part] as NestedStringDictionary;\n }\n }\n\n const valuesType = JSON.stringify(result, null, 2).replace(/\"string\"/g, \"string\");\n const langsUnionType = langs.map(lang => `\"${lang}\"`).join(\" | \");\n const keysUnionType = keys.map(key => `\"${key}\"`).join(\" | \");\n const placeholderUnionType = placeholders.map(key => `\"${key}\"`).join(\" | \");\n\n const fileString = `declare global {\n type I18nLang = ${langsUnionType};\n type I18nKeysPath = ${keysUnionType};\n type I18nValuesRecord = ${valuesType};\n type I18nPlaceholder = ${placeholderUnionType}\n type I18nPlaceholderRecord = { [key in I18nPlaceholder]?: string };\n\n /** Replace a placeholder with a value. */\n const i18n_fill_template: (value: string, placeholdersObject?: I18nPlaceholderRecord) => string;\n\n /** Get all supported languages as an array. */\n const i18n_locales: () => I18nLang[];\n\n /** Get the default language. */\n const i18n_default_locale: () => I18nLang;\n\n /** Get the translation value for the given key and language. */\n const i18n_key_value: (key: I18nKeysPath, lang: I18nLang, placeholdersObject?: I18nPlaceholderRecord) => string;\n\n /** Get all translation values as a language-value record for the given key. */\n const i18n_key_values: (key: I18nKeysPath) => Record<I18nLang, string>;\n\n /** Get all translation values for the given language as a record. */\n const i18n_lang_values: (lang: I18nLang) => I18nValuesRecord;\n\n /** Get all translation values for all languages. */\n const i18n_all: () => Record<I18nLang, I18nValuesRecord>;\n}\n\nexport {};\n`;\n\n return fileString;\n}\n\ninterface RecursiveRecord {\n [key: string]: string | RecursiveRecord;\n}\n\nfunction collectPlaceholders(data: RecursiveRecord) {\n const result = new Set<string>();\n\n for (const key in data) {\n const value = data[key];\n\n if (typeof value === \"string\") {\n value.replace(propertyRe, (match: string, placeholder: string) => {\n result.add(placeholder);\n return match;\n });\n continue;\n }\n\n if (typeof value === \"object\" && !Array.isArray(value)) {\n for (const placeholder of collectPlaceholders(value)) result.add(placeholder);\n }\n }\n\n return result;\n}\n","import _generator from \"@babel/generator\";\nimport * as t from \"@babel/types\";\n\nimport type { NodePath } from \"@babel/traverse\";\n\nconst generator = typeof _generator === \"function\" ? _generator : _generator.default;\n\nexport type ResolveStaticValue =\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n | { value: Function | undefined; type: \"function\"; path: NodePath }\n | { value: string; type: \"string\"; path: NodePath }\n | { value: boolean; type: \"boolean\"; path: NodePath }\n | { value: number; type: \"number\"; path: NodePath }\n | { value: null; type: \"null\"; path: NodePath }\n | { value: ResolveStaticValue[]; type: \"array\"; path: NodePath }\n | { value: Record<string, unknown>; type: \"object\"; path: NodePath }\n | { value: undefined; type: \"undefined\"; path: NodePath };\n\n/** Get the value of an expression node */\nexport function resolveStaticValue(path: NodePath | null | undefined): ResolveStaticValue | undefined {\n if (!path) return;\n\n const node = path.node;\n\n if (t.isNullLiteral(node)) {\n return { value: null, type: \"null\", path };\n }\n\n if (t.isStringLiteral(node)) {\n return { value: node.value, type: \"string\", path };\n }\n\n if (t.isBooleanLiteral(node)) {\n return { value: node.value, type: \"boolean\", path };\n }\n\n if (t.isNumericLiteral(node)) {\n return { value: node.value, type: \"number\", path };\n }\n\n // BinaryExpression (like foo + bar) or ConditionalExpression (like foo ? bar : baz)\n if (t.isBinaryExpression(node) || t.isConditionalExpression(node)) {\n const evalResult = path.evaluate();\n if (!evalResult.confident) return;\n return { value: evalResult.value as unknown, type: typeof evalResult.value, path } as ResolveStaticValue;\n }\n\n if (t.isTemplateLiteral(node)) {\n let result = \"\";\n\n for (let index = 0; index < node.quasis.length; index++) {\n const staticPart = node.quasis[index].value.cooked ?? node.quasis[index].value.raw;\n result += staticPart;\n\n if (index < node.expressions.length) {\n const exp = node.expressions[index];\n if (!t.isExpression(exp)) continue;\n\n const expValue = resolveStaticValue(path.get(`expressions.${index}`));\n if (!expValue) continue;\n\n if (expValue.type === \"string\" || expValue.type === \"number\" || expValue.type === \"boolean\") {\n result += String(expValue.value);\n }\n }\n }\n\n return { value: result, type: \"string\", path };\n }\n\n if (t.isIdentifier(node)) {\n if (node.name === \"undefined\") return { value: undefined, type: \"undefined\", path };\n\n const binding = path.scope.getBinding(node.name);\n if (!binding || !binding.path.isVariableDeclarator()) return;\n\n const init = binding.path.node.init;\n if (!init) return;\n\n const initPath = binding.path.get(\"init\");\n return resolveStaticValue(initPath);\n }\n\n if (\n t.isArrowFunctionExpression(node) ||\n t.isFunctionExpression(node) ||\n t.isClassMethod(node) ||\n t.isClassPrivateMethod(node)\n ) {\n const parameters = node.params.map(parameter => (t.isIdentifier(parameter) ? parameter.name : \"\")).filter(Boolean);\n const isBlock = t.isBlockStatement(node.body);\n let bodyString = generator(node.body).code;\n\n bodyString = isBlock\n ? bodyString.slice(1, -1).trim() // remove `{` and `}`\n : \"return \" + bodyString; // arrow fn without block\n\n let function_;\n try {\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n function_ = new Function(...parameters, bodyString);\n } catch {\n // do nothing\n }\n\n return { value: function_, type: \"function\", path };\n }\n\n if (t.isObjectExpression(node)) {\n const value: Record<string, unknown> = {};\n\n for (let index = 0; index < node.properties.length; index++) {\n const property = node.properties[index];\n if (!t.isObjectProperty(property)) continue;\n\n const keyName = t.isStringLiteral(property.key)\n ? property.key.value\n : t.isIdentifier(property.key)\n ? property.key.name\n : null;\n if (!keyName) continue;\n\n const propertyValuePath = path.get(`properties.${index}.value`);\n const expValue = resolveStaticValue(propertyValuePath);\n\n if (expValue) value[keyName] = expValue.value;\n }\n\n return { value, type: \"object\", path };\n }\n\n if (t.isArrayExpression(node)) {\n const value = [];\n\n for (let index = 0; index < node.elements.length; index++) {\n const element = node.elements[index];\n if (!element) continue;\n\n const elementPath = path.get(`elements.${index}`);\n const elementValue = resolveStaticValue(elementPath);\n\n if (elementValue) value.push(elementValue);\n }\n\n return { value, type: \"array\", path };\n }\n\n // MemberExpression → object property or array index\n if (t.isMemberExpression(node)) {\n return resolveMemberExpression(path);\n }\n}\n\nfunction resolveMemberExpression(path: NodePath): ReturnType<typeof resolveStaticValue> {\n let current = path.node;\n let currentPath: NodePath | null = path;\n\n const parts = [];\n\n // Collect property names (e.g., [\"key\", \"nested\" , 0])\n while (t.isMemberExpression(current)) {\n const { property, computed } = current;\n\n let keyName;\n // Array index\n if (t.isNumericLiteral(property)) {\n keyName = property.value;\n }\n\n // Property name as identifier. e.g., object.key\n if (!computed && t.isIdentifier(property)) {\n keyName = property.name;\n }\n\n // Class private property name as identifier. e.g., this.#key\n if (!computed && t.isPrivateName(property)) {\n keyName = \"#\" + property.id.name;\n }\n\n // Property name as string. e.g., object[\"key\"]\n if (computed && t.isStringLiteral(property)) {\n keyName = property.value;\n }\n\n // Property name as a computed identifier (variable). e.g., object[computedKey]\n if (computed && t.isIdentifier(property)) {\n const propertyValue = resolveStaticValue(currentPath.get(\"property\"));\n keyName = typeof propertyValue === \"string\" || typeof propertyValue === \"number\" ? propertyValue : undefined;\n }\n\n if (keyName !== undefined) {\n parts.unshift(keyName);\n }\n\n current = current.object;\n currentPath = currentPath.get(\"object\");\n }\n\n // accessing a variable. e.g., object.key\n if (t.isIdentifier(current)) {\n const binding = path.scope.getBinding(current.name);\n if (!binding) return;\n\n if (t.isVariableDeclarator(binding.path.node)) {\n currentPath = binding.path.get(\"init\");\n } else if (t.isClassDeclaration(binding.path.node)) {\n currentPath = binding.path; // class static property\n } else return;\n } else if (t.isThisExpression(current)) {\n // accessing `this.key`.\n const classPath = path.find(p => p.isClassDeclaration() || p.isClassExpression());\n if (!classPath) return;\n currentPath = classPath;\n }\n\n if (!currentPath) return;\n\n // Traverse the object properties\n for (const part of parts) {\n const expression: t.Node | null | undefined = currentPath.node;\n\n // plain object\n if (t.isObjectExpression(expression)) {\n if (typeof part !== \"string\") continue;\n const propertyIndex = expression.properties.findIndex(\n property_ =>\n (t.isObjectProperty(property_) && t.isIdentifier(property_.key, { name: part })) ||\n (t.isObjectProperty(property_) && t.isStringLiteral(property_.key, { value: part }))\n );\n if (propertyIndex === -1) continue;\n\n const property = expression.properties[propertyIndex] as t.ObjectProperty;\n if (!property) continue;\n\n currentPath = currentPath.get(`properties.${propertyIndex}.value`);\n continue;\n }\n\n // array\n if (t.isArrayExpression(expression)) {\n if (typeof part !== \"number\") continue;\n const element = expression.elements[part];\n if (!element) continue;\n\n currentPath = currentPath.get(`elements.${part}`);\n continue;\n }\n\n // class\n if (t.isClassExpression(expression) || t.isClassDeclaration(expression)) {\n if (typeof part !== \"string\") continue;\n\n const valuePath = getClassPropertyValue(currentPath, part);\n if (!valuePath) return;\n\n currentPath = valuePath;\n }\n }\n\n if (!currentPath) return;\n\n return resolveStaticValue(currentPath);\n}\n\nfunction getClassPropertyValue(classPath: NodePath, propertyName: string): NodePath | undefined {\n if (!classPath.isClassDeclaration() && !classPath.isClassExpression()) return;\n\n const classBody = classPath.node.body.body;\n\n for (const [index, node] of classBody.entries()) {\n // ? If a property has both a class field initializer and an assignment in the constructor,\n // ? the initializer value takes precedence if it appears first.\n\n // Case: Constructor assignments (this.prop = ...)\n if (t.isClassMethod(node, { kind: \"constructor\" })) {\n const body = node.body.body;\n for (const [index_, bodyNode] of body.entries()) {\n if (!t.isExpressionStatement(bodyNode) || !t.isAssignmentExpression(bodyNode.expression)) continue;\n\n const { left } = bodyNode.expression;\n if (!t.isMemberExpression(left) || !t.isThisExpression(left.object)) continue;\n\n // check property name\n if (t.isIdentifier(left.property) && left.property.name !== propertyName) continue;\n if (t.isPrivateName(left.property) && left.property.id.name !== propertyName) continue;\n\n return classPath.get(`body.body.${index}.body.body.${index_}.expression.right`);\n }\n }\n\n // Case: Public/Private class field that has a value.\n if (t.isClassProperty(node) || t.isClassPrivateProperty(node)) {\n if (t.isIdentifier(node.key, { name: propertyName }) && node.value) {\n return classPath.get(`body.body.${index}.value`);\n }\n\n if (t.isPrivateName(node.key) && `#${node.key.id.name}` === propertyName && node.value) {\n return classPath.get(`body.body.${index}.value`);\n }\n\n if (t.isStringLiteral(node.key, { value: propertyName }) && node.value) {\n return classPath.get(`body.body.${index}.value`);\n }\n }\n\n // Case: Public/Private get method\n if (\n (t.isClassMethod(node, { kind: \"get\" }) && t.isIdentifier(node.key, { name: propertyName })) ||\n (t.isClassPrivateMethod(node, { kind: \"get\" }) && `#${node.key.id.name}` === propertyName)\n ) {\n for (let index_ = 0; index_ < node.body.body.length; index_++) {\n const bodyNode = node.body.body[index_];\n if (bodyNode.type !== \"ReturnStatement\") continue;\n if (!bodyNode.argument) return;\n\n if (t.isTSAsExpression(bodyNode.argument)) {\n return classPath.get(`body.body.${index.toString()}.body.body.${index_.toString()}.argument.expression`);\n }\n\n return classPath.get(`body.body.${index.toString()}.body.body.${index_.toString()}.argument`);\n }\n }\n }\n}\n","import _traverse from \"@babel/traverse\";\nimport * as t from \"@babel/types\";\n\nimport { resolveStaticValue } from \"../../ast-utilities/babel-utils/resolve-static-value.ts\";\nimport { filterScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { isAbsolute, join, normalize } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { getLocals } from \"./get-locales.ts\";\nimport { propertyRe } from \"./i18n-html-plugin.ts\";\n\nimport type { I18nPluginOptions } from \"./i18n-plugin.ts\";\nimport type { Plugin } from \"@staticbolt/core\";\n\nconst traverse = typeof _traverse === \"function\" ? _traverse : _traverse.default;\n\n/**\n * The script half of i18nPlugin: replaces the \"i18n_*\" helper calls in JavaScript with the values they resolve to, so no\n * translation machinery is left at runtime.\n *\n * - \"i18n_locales()\" and \"i18n_default_locale()\": the supported locales and the default one.\n * - \"i18n_key_value(key, lang, placeholders?)\" and \"i18n_key_values(key)\": one translation, or that key across every locale.\n * - \"i18n_lang_values(lang)\" and \"i18n_all()\": whole translation objects.\n * - \"i18n_fill_template(value, placeholders?)\": fills the \"{{ name=fallback }}\" placeholders of a string.\n *\n * Notes:\n *\n * - Arguments have to be statically resolvable strings or plain objects. Anything dynamic is reported and the call is left in the\n * code, where it will fail at runtime.\n * - Declarations for these helpers come from the \"locales\" CLI command, see i18nCliPlugin.\n * - The active locale is not one of them; read it at runtime from \"document.documentElement.lang\".\n */\nexport function i18nScriptPlugin(options: Required<I18nPluginOptions>): Plugin {\n const { defaultLocale, localesDirectory, supportedLocales } = options;\n\n const printFmtError = PrintFormattedError.create({ function: i18nScriptPlugin });\n\n return {\n name: \"i18n-script-plugin\",\n\n transform(inputMetadata) {\n const localesPath = isAbsolute(localesDirectory) ? normalize(localesDirectory) : join(this.root, localesDirectory);\n\n const locales = getLocals({ localesPath, supportedLocales });\n const langs = Object.keys(locales.localesMap);\n\n for (const { metadata } of filterScriptMetadata(inputMetadata)) {\n traverse(metadata.ast, {\n CallExpression(path) {\n if (!t.isIdentifier(path.node.callee)) return;\n const filePath = metadata.id;\n\n const node = path.node;\n\n if (path.node.callee.name === \"i18n_fill_template\") {\n const firstArgumentValue = resolveStaticValue(path.get(\"arguments.0\"));\n if (!firstArgumentValue || firstArgumentValue.type !== \"string\") {\n printFmtError(\"The first argument of `i18n_fill_template` should be a string\", { node, filePath });\n return;\n }\n\n const secondArgumentValue = resolveStaticValue(path.get(\"arguments.1\"));\n if (secondArgumentValue && secondArgumentValue.type !== \"object\") {\n printFmtError(\"The second argument of `i18n_fill_template` should be a plain object\", {\n node,\n filePath,\n });\n return;\n }\n\n const fillValues = secondArgumentValue?.value ?? {};\n const replacer = (_match: string, variableName: string, defaultValue: string | undefined) => {\n if (Object.hasOwn(fillValues, variableName)) {\n const value_ = fillValues[variableName];\n if (typeof value_ === \"string\") return value_;\n }\n if (defaultValue !== undefined) return defaultValue;\n return \"\";\n };\n\n // eslint-disable-next-line unicorn/no-unsafe-string-replacement\n const value = firstArgumentValue.value.replace(propertyRe, replacer);\n\n path.replaceWith(t.stringLiteral(value));\n return;\n }\n\n if (path.node.callee.name === \"i18n_locales\") {\n path.replaceWith(t.arrayExpression(langs.map(lang => t.stringLiteral(lang))));\n return;\n }\n\n if (path.node.callee.name === \"i18n_default_locale\") {\n path.replaceWith(t.stringLiteral(defaultLocale));\n return;\n }\n\n if (path.node.callee.name === \"i18n_all\") {\n path.replaceWith(buildObjectExpression(locales.localesObj));\n return;\n }\n\n if (path.node.callee.name === \"i18n_lang_values\") {\n const firstArgumentValue = resolveStaticValue(path.get(\"arguments.0\"));\n if (!firstArgumentValue || firstArgumentValue.type !== \"string\") {\n printFmtError(\"The first argument of `i18n_lang_values` should be a string\", { node, filePath });\n return;\n }\n const lang = firstArgumentValue.value;\n\n if (!langs.includes(lang)) {\n printFmtError(`The first argument of \"i18n_lang_values\" should be one of`, langs.join(\", \"), {\n node,\n filePath,\n });\n return;\n }\n\n const object = locales.localesObj[lang];\n if (!object) return;\n\n path.replaceWith(buildObjectExpression(object));\n return;\n }\n\n if (path.node.callee.name === \"i18n_key_value\") {\n const firstArgumentValue = resolveStaticValue(path.get(\"arguments.0\"));\n if (!firstArgumentValue || firstArgumentValue.type !== \"string\") {\n printFmtError(\"The first argument of `i18n_key_value` should be a string\", { node, filePath });\n return;\n }\n const keysPath = firstArgumentValue.value;\n\n const secondeArgumentValue = resolveStaticValue(path.get(\"arguments.1\"));\n if (!secondeArgumentValue || secondeArgumentValue.type !== \"string\") {\n printFmtError(\"The second argument of `i18n_key_value` should be a string\", { node, filePath });\n return;\n }\n const lang = secondeArgumentValue.value;\n\n if (!langs.includes(lang)) {\n printFmtError(`The first argument of \"i18n_lang_values\" should be one of`, langs.join(\", \"), {\n node,\n filePath,\n });\n return;\n }\n\n if (!locales.getKey(keysPath, lang)) {\n printFmtError(\"The first argument of `i18n_key_value` should be a valid key path\", { node, filePath });\n return;\n }\n\n const thirdArgumentValue = resolveStaticValue(path.get(\"arguments.2\"));\n if (thirdArgumentValue && thirdArgumentValue.type !== \"object\") {\n printFmtError(\"The third argument of `i18n_key_value` should be an optional plain object\", {\n node,\n filePath,\n });\n return;\n }\n const fillValues = thirdArgumentValue?.value ?? {};\n\n const replacer = (_match: string, variableName: string, defaultValue: string | undefined) => {\n if (Object.hasOwn(fillValues, variableName)) {\n const value_ = fillValues[variableName];\n if (typeof value_ === \"string\") return value_;\n }\n if (defaultValue !== undefined) return defaultValue;\n return \"\";\n };\n\n // eslint-disable-next-line unicorn/no-unsafe-string-replacement\n const value = locales.getKey(keysPath, lang).replace(propertyRe, replacer);\n\n path.replaceWith(t.stringLiteral(value));\n return;\n }\n\n if (path.node.callee.name === \"i18n_key_values\") {\n const firstArgumentValue = resolveStaticValue(path.get(\"arguments.0\"));\n if (!firstArgumentValue || firstArgumentValue.type !== \"string\") {\n printFmtError(\"The first argument of `i18n_key_values` should be a string\", { node, filePath });\n return;\n }\n const keysPath = firstArgumentValue.value;\n\n const langValueEntries = langs.map(lang => [lang, locales.getKey(keysPath, lang)]);\n\n path.replaceWith(\n t.objectExpression(\n langValueEntries.map(([lang, value]) => t.objectProperty(t.stringLiteral(lang), t.stringLiteral(value)))\n )\n );\n return;\n }\n },\n });\n }\n },\n };\n}\n\ninterface RecursiveRecord {\n [key: string]: string | RecursiveRecord;\n}\n\nfunction buildObjectExpression(object: RecursiveRecord): t.ObjectExpression {\n return t.objectExpression(\n Object.entries(object).map(([key, value]) =>\n t.objectProperty(t.stringLiteral(key), typeof value === \"string\" ? t.stringLiteral(value) : buildObjectExpression(value))\n )\n );\n}\n","import { i18nCliPlugin } from \"./i18n-cli-plugin.ts\";\nimport { i18nHtmlPlugin } from \"./i18n-html-plugin.ts\";\nimport { i18nScriptPlugin } from \"./i18n-script-plugin.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface I18nPluginOptions {\n /**\n * The default locale.\n *\n * @default \"en\"\n */\n defaultLocale?: string;\n\n /**\n * The supported locales.\n *\n * @default [\"en\"]\n */\n supportedLocales?: string[];\n\n /**\n * The path to the locales directory.\n *\n * @default \"./sources/locales\"\n */\n localesDirectory?: string;\n\n /**\n * The name of the i18n attribute.\n *\n * @default \"i18n\"\n */\n i18nAttribute?: string;\n\n /**\n * The prefix to use for i18n attributes.\n *\n * @default \"i18n-attr-\"\n */\n i18nAttributePrefix?: string;\n\n /**\n * The prefix to use for i18n attributes.\n *\n * @default \"i18n-placeholder-\"\n */\n placeholderPrefix?: string;\n}\n\n/**\n * Adds internationalization: every page is emitted once per locale with its translation markers resolved, and scripts get a set\n * of compile-time helpers. Returns the three plugins that do the work (HTML, scripts, CLI) sharing the same resolved options.\n *\n * Translations live in one JSON file per locale inside \"localesDirectory\" (\"en.json\", \"ar.json\", ...). Nested objects turn into\n * dot-notated keys, and values can carry \"{{ name=fallback }}\" placeholders.\n *\n * Notes:\n *\n * - The default locale is emitted at the original paths; the others go under a directory named after the locale.\n * - Locale files are read once and cached for the whole process, so a running dev server does not pick up edits to them.\n */\nexport function i18nPlugin(options: I18nPluginOptions = {}): Plugin[] {\n const requiredOptions: Required<I18nPluginOptions> = {\n defaultLocale: options.defaultLocale ?? \"en\",\n supportedLocales: options.supportedLocales ?? [\"en\"],\n localesDirectory: options.localesDirectory ?? \"./sources/locales\",\n placeholderPrefix: options.placeholderPrefix ?? \"i18n-placeholder-\",\n i18nAttribute: options.i18nAttribute ?? \"i18n\",\n i18nAttributePrefix: options.i18nAttributePrefix ?? \"i18n-attr-\",\n };\n\n return [i18nCliPlugin(requiredOptions), i18nHtmlPlugin(requiredOptions), i18nScriptPlugin(requiredOptions)];\n}\n","import * as t from \"@babel/types\";\n\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\n\nimport type { ImportAsStringOptions } from \"./types.ts\";\nimport type { BabelAst } from \"@staticbolt/core\";\n\ninterface Options {\n ast: BabelAst;\n filePath: string;\n}\n\ninterface ParseImportAsStringResult {\n get source(): string;\n set source(newValue: string);\n replaceWith: (newValue: string) => void;\n options: ImportAsStringOptions;\n}\n\nexport function parseImportAsString({ ast, filePath }: Options): ParseImportAsStringResult[] {\n const result: ParseImportAsStringResult[] = [];\n\n const printFmtError = PrintFormattedError.create({ function: parseImportAsString, filePath });\n\n t.traverse(ast, {\n enter(node, ancestors) {\n if (!t.isCallExpression(node)) return;\n if (!t.isIdentifier(node.callee)) return;\n if (node.callee.name !== \"import_as_string\") return;\n\n const firstArgument = node.arguments[0];\n\n const source = resolveStaticValue(firstArgument);\n if (typeof source !== \"string\") {\n printFmtError(\"The first argument of `import_as_string` should be a string\", { node });\n return;\n }\n\n const optionsObject: Required<ImportAsStringOptions> = {\n templateLiteral: false,\n process: true,\n minify: false,\n format: false,\n };\n\n const secondeArgument = node.arguments[1];\n const secondeArgumentValue = resolveStaticValue(secondeArgument);\n\n if (isPlainObject(secondeArgumentValue)) {\n const entries = Object.entries(secondeArgumentValue) as [keyof ImportAsStringOptions, unknown][];\n\n for (const [key, value] of entries) {\n if (!Object.hasOwn(optionsObject, key)) {\n printFmtError(\"Unknown option of `import_as_string`\", { node });\n continue;\n }\n\n const expectedType = typeof optionsObject[key];\n const actualType = typeof value;\n\n if (actualType !== expectedType) {\n printFmtError(`The '${key}' option should be an optional`, expectedType, { node });\n continue;\n }\n\n optionsObject[key] = value as never;\n }\n }\n\n const capturedAncestor = ancestors.at(-1);\n if (!capturedAncestor) {\n printFmtError(\"Internal error. Couldn't find ancestor\", { node });\n return;\n }\n\n const parentNode = capturedAncestor.node;\n\n const replaceWith = (newValue: string) => {\n const newNode = optionsObject.templateLiteral ? buildTemplateLiteral(newValue) : t.stringLiteral(newValue);\n\n if (capturedAncestor.index === undefined) {\n // @ts-expect-error so many wrong types\n parentNode[capturedAncestor.key] = newNode;\n return;\n }\n\n // @ts-expect-error so many wrong types\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n parentNode[capturedAncestor.key][capturedAncestor.index] = newNode;\n };\n\n result.push({\n get source() {\n return source;\n },\n set source(newValue) {\n node.arguments[0] = t.stringLiteral(newValue);\n },\n replaceWith,\n options: optionsObject,\n });\n },\n });\n\n return result;\n}\n\n/** Builds a template literal holding the value, escaping what would otherwise break out of it. */\nfunction buildTemplateLiteral(value: string): t.TemplateLiteral {\n const escaped = value\n .replace(/\\\\/g, String.raw`\\\\`)\n .replace(/`/g, String.raw`\\``)\n .replace(/\\$\\{/g, String.raw`\\${`);\n\n return t.templateLiteral([t.templateElement({ raw: escaped, cooked: value }, true)], []);\n}\n\nfunction resolveStaticValue(node: t.Node): unknown {\n if (t.isNullLiteral(node)) {\n return null;\n }\n\n if (t.isStringLiteral(node)) {\n return node.value;\n }\n\n if (t.isBooleanLiteral(node)) {\n return node.value;\n }\n\n if (t.isNumericLiteral(node)) {\n return node.value;\n }\n\n if (t.isTemplateLiteral(node)) {\n let result = \"\";\n\n for (let index = 0; index < node.quasis.length; index++) {\n const staticPart = node.quasis[index].value.cooked ?? node.quasis[index].value.raw;\n result += staticPart;\n\n if (index < node.expressions.length) {\n const exp = node.expressions[index];\n if (!t.isExpression(exp)) continue;\n\n const expValue = resolveStaticValue(exp);\n if (!expValue) continue;\n\n if (typeof expValue === \"string\" || typeof expValue === \"number\" || typeof expValue === \"boolean\") {\n result += String(expValue);\n }\n }\n }\n\n return result;\n }\n\n if (t.isObjectExpression(node)) {\n const value: Record<string, unknown> = {};\n\n for (let index = 0; index < node.properties.length; index++) {\n const property = node.properties[index];\n if (!t.isObjectProperty(property)) continue;\n\n const keyName = t.isStringLiteral(property.key)\n ? property.key.value\n : t.isIdentifier(property.key)\n ? property.key.name\n : null;\n if (!keyName) continue;\n\n const expValue = resolveStaticValue(property.value);\n\n if (expValue) {\n value[keyName] = expValue;\n }\n }\n\n return value;\n }\n\n if (t.isArrayExpression(node)) {\n const value = [];\n\n for (let index = 0; index < node.elements.length; index++) {\n const element = node.elements[index];\n if (!element) continue;\n\n const elementValue = resolveStaticValue(element);\n\n if (elementValue) {\n value.push(elementValue);\n }\n }\n\n return value;\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { DependencyTracker } from \"../../helpers/dependency-tracker.ts\";\nimport { filterScriptMetadata, isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { printFmtError } from \"../../utilities/print-formatted-error.ts\";\nimport { safeReadFileSync } from \"../../utilities/read-file.ts\";\nimport { parseImportAsString } from \"./parse-import-as-string.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\n/**\n * Replaces \"import_as_string(path, options?)\" calls in scripts with the contents of that file, inlined as a string literal at\n * build time.\n *\n * By default the file is taken from the build, so what lands in the string is the processed version, and \"minify\" and \"format\"\n * control how it is printed. With \"process: false\" the file is read straight from disk instead, untouched, and with\n * \"templateLiteral: true\" the value is inlined as a template literal rather than a quoted string.\n *\n * Notes:\n *\n * - The path and the options object have to be statically resolvable; anything dynamic is reported and the call is left in the\n * code, where it will fail at runtime.\n * - The path is resolved relative to the file doing the importing.\n * - \"minify\" and \"format\" only apply in production; in development the file is inlined as it is.\n * - An inlined file is dropped from the output unless it is an entry point in its own right.\n * - Editing an inlined file recompiles the scripts that inline it.\n */\nexport function importAsStringPlugin(): Plugin {\n const dependencies = new DependencyTracker();\n\n return {\n name: \"import-as-string\",\n\n sourcesProvider(metadata) {\n if (!isScriptMetadata(metadata)) return;\n\n return parseImportAsString({ ast: metadata.ast, filePath: metadata.filePath });\n },\n\n onFileEvent(event, id) {\n if (event === \"unlink\") {\n dependencies.delete(id);\n }\n },\n\n resolveCompileList(compileSet, event) {\n if (event !== \"change\") return;\n\n for (const id of Array.from(compileSet)) {\n const importers = dependencies.getImporters(id);\n\n for (const importer of importers) {\n compileSet.add(importer);\n }\n }\n },\n\n async transform(inputMetadata) {\n for (const { metadata } of filterScriptMetadata(inputMetadata)) {\n const currentSources = new Set<string>();\n\n const sources = parseImportAsString({ ast: metadata.ast, filePath: metadata.filePath });\n\n for (const { source, replaceWith, options } of sources) {\n const sourceRelative = join(dirname(metadata.filePath), source);\n\n // Inline as normal string\n if (!options.process) {\n const sourceAbs = join(this.root, sourceRelative);\n const [fileContent, fileContentError] = safeReadFileSync(sourceAbs, \"utf8\");\n if (fileContentError) {\n printFmtError(fileContentError, { function: importAsStringPlugin, filePath: metadata.id });\n continue;\n }\n\n currentSources.add(sourceRelative);\n\n replaceWith(fileContent);\n\n continue;\n }\n\n const sourceMetadata = this.findMetadata({ filePath: sourceRelative });\n if (!sourceMetadata) {\n this.log.error(`Failed to find metadata for \"${sourceRelative}\" found in \"${metadata.filePath}\"`);\n continue;\n }\n\n currentSources.add(sourceRelative);\n\n const format = this.production ? options.format : false;\n const minify = this.production ? options.minify : false;\n\n const metadataString = await this.stringify(sourceMetadata, { format, minify });\n if (typeof metadataString !== \"string\") {\n printFmtError(\"Failed to stringify metadata\", { function: importAsStringPlugin, filePath: metadata.id });\n continue;\n }\n\n if (!this.entryPoints.has(sourceMetadata.id)) {\n this.emitExclude.add(sourceMetadata);\n }\n\n replaceWith(metadataString);\n }\n\n dependencies.update(metadata.id, currentSources);\n }\n },\n };\n}\n\nexport type { ImportAsStringOptions, import_as_string } from \"./types.ts\";\n","import { globSync } from \"glob\";\n\nimport { isPathMatch, normalize } from \"../../utilities/path.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface LoadSourcesPluginOptions {\n include: string[];\n exclude?: string[];\n}\n\n/**\n * Registers the files matched by \"include\" as entry points: the roots the build starts from, with everything they reference\n * discovered, transformed and emitted along with them.\n *\n * Notes:\n *\n * - Patterns are matched from the project root at startup, and matching nothing is reported as an error.\n * - Matched files are watched, so creating or deleting one updates the entry point set without a restart.\n * - Any file type staticbolt can load works as an entry point, HTML, markdown, scripts and styles alike.\n */\nexport function loadSourcesPlugin(options: LoadSourcesPluginOptions): Plugin {\n const ignore = options.exclude ?? [];\n\n return {\n name: \"load-sources\",\n\n setup() {\n const entryFiles = globSync(options.include, { ignore, cwd: this.root, nodir: true });\n\n if (entryFiles.length === 0) {\n this.log.error(`No files found matching`, options.include.join(\", \"));\n return;\n }\n\n for (const entryFile of entryFiles) {\n const normalized = normalize(entryFile);\n this.entryPoints.add(normalized);\n this.watcher?.add(normalized);\n }\n },\n\n onFileEvent(event, id) {\n if (event === \"change\") return;\n\n const isIncluded = isPathMatch(id, { include: options.include, ignore, root: this.root });\n if (!isIncluded) return;\n\n if (event === \"unlink\") {\n this.entryPoints.delete(id);\n this.watcher?.unwatch(id);\n return;\n }\n\n this.entryPoints.add(id);\n this.watcher?.add(id);\n },\n };\n}\n","import { mkdirSync, writeFileSync } from \"node:fs\";\n\nimport { dirname, join } from \"../../utilities/path.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface RobotsTextOptions {\n /**\n * Generate `robots.txt`.\n *\n * @default [ ]\n */\n rules?: {\n userAgent: string;\n allow?: string[];\n disallow?: string[];\n }[];\n\n /**\n * The output file path relative to output directory.\n *\n * @default \"robots.txt\"\n */\n outfile?: string;\n\n /** The path to the sitemap file. */\n sitemapUrl?: string;\n}\n\n/**\n * Writes a \"robots.txt\" into the output directory from the rules given in the options.\n *\n * Notes:\n *\n * - Production only, and only when at least one rule is configured; with an empty \"rules\" list nothing is written.\n * - Every rule becomes a \"User-agent\" block followed by its \"Allow\" and \"Disallow\" lines, in the order they are listed.\n * - \"sitemapUrl\" appends a \"Sitemap:\" line as given, so pass the full URL.\n * - The file is written straight to disk after the build and is not part of the build graph.\n */\nexport function robotsTextPlugin(options: RobotsTextOptions = {}): Plugin {\n const rules = options.rules ?? [];\n const outFile = options.outfile ?? \"robots.txt\";\n\n return {\n name: \"robots-text\",\n\n postBuild() {\n if (!this.production || rules.length === 0) return;\n\n const lines = [];\n for (const rule of rules) {\n const userAgent = rule.userAgent ?? \"*\";\n lines.push(`User-agent: ${userAgent}`);\n\n if (rule.allow) for (const path of rule.allow) lines.push(`Allow: ${path}`);\n if (rule.disallow) for (const path of rule.disallow) lines.push(`Disallow: ${path}`);\n\n lines.push(\"\");\n }\n\n if (options.sitemapUrl) {\n lines.push(`Sitemap: ${options.sitemapUrl}`);\n }\n\n const outputFile = join(this.outdir, outFile);\n mkdirSync(dirname(outputFile), { recursive: true });\n writeFileSync(outputFile, lines.join(\"\\n\"), \"utf8\");\n },\n };\n}\n","import c from \"chalk\";\n\nimport { join } from \"../../utilities/path.ts\";\nimport { humanReadableBytes } from \"../../utilities/utilities.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface ServiceWorkerOptions {\n /**\n * Glob patterns for matching files.\n *\n * @default [\"**\\/*.{js,wasm,css,html}\"]\n */\n globPatterns?: string[];\n\n /**\n * Glob patterns for files to ignore.\n *\n * @default [\"**\\/node_modules\\/**\\/*\"]\n */\n globIgnores?: string[];\n\n /**\n * Whether to follow symbolic links when matching glob patterns.\n *\n * @default true\n */\n globFollow?: boolean;\n\n /**\n * Enforces strict mode for glob patterns.\n *\n * @default true\n */\n globStrict?: boolean;\n\n /**\n * Destination file for the generated service worker relative to the output directory.\n *\n * @default \"sw.js\"\n */\n swDest?: string;\n\n /**\n * Determines whether source maps should be generated.\n *\n * @default false\n */\n sourcemap?: boolean;\n\n /**\n * Whether to skip waiting and immediately activate the service worker.\n *\n * @default false\n */\n skipWaiting?: boolean;\n\n /**\n * Whether the service worker should claim all available clients.\n *\n * @default false\n */\n clientsClaim?: boolean;\n\n /**\n * Whether to inline the Workbox runtime.\n *\n * @default false\n */\n inlineWorkboxRuntime?: boolean;\n\n /**\n * Cleans up outdated caches during service worker activation.\n *\n * @default false\n */\n cleanupOutdatedCaches?: boolean;\n\n /**\n * Enables offline Google Analytics support.\n *\n * @default false\n */\n offlineGoogleAnalytics?: boolean;\n\n /** Cache ID used for versioning. */\n cacheId?: string;\n\n /** The default directory index for cached URLs. */\n directoryIndex?: string;\n\n /**\n * Maximum file size (in bytes) to cache.\n *\n * @default 2097152\n */\n maximumFileSizeToCacheInBytes?: number;\n\n /** Modifies URL prefixes for cached assets. */\n modifyURLPrefix?: Record<string, string>;\n}\n\n/**\n * Generates a Workbox service worker from the finished output directory, precaching every file that matches \"globPatterns\".\n *\n * The options are handed to workbox-build's \"generateSW\", with \"swDest\" resolved inside the output directory and the project's\n * browserslist used as the Babel target.\n *\n * Registering it is up to the page:\n *\n * ```ts\n * import { Workbox } from \"workbox-window\";\n *\n * if (\"serviceWorker\" in navigator && _production) {\n * const wb = new Workbox(\"/sw.js\");\n * wb.register();\n * }\n * ```\n *\n * Notes:\n *\n * - Production only, and it runs after the build, so it sees the final files, copied assets included.\n * - The precache manifest is built from the output directory; files larger than \"maximumFileSizeToCacheInBytes\" (2 MB by default)\n * are left out.\n * - The worker is written straight to disk and is not part of the build graph.\n */\nexport function serviceWorkerPlugin(options: ServiceWorkerOptions = {}): Plugin {\n return {\n name: \"service-worker\",\n\n async postBuild() {\n if (!this.production) return;\n\n this.log.info(\"Generating a service worker...\");\n\n const outdir = this.outdir;\n\n options.swDest = join(outdir, options.swDest ?? \"sw.js\");\n\n const { generateSW } = await import(\"workbox-build\");\n\n const { count, size, warnings } = await generateSW({\n globDirectory: outdir,\n babelPresetEnvTargets: this.browserslist,\n ...(options as Required<ServiceWorkerOptions>),\n });\n\n if (warnings.length > 0) {\n this.log.warn(\"Warnings encountered while generating a service worker:\\n >\", warnings.join(c.yellow(\"\\n > \")), \"\\n\");\n }\n\n this.log.info(\n \"Generated a service worker, which will precache\",\n c.yellow(count),\n \"files, totaling\",\n c.yellow(humanReadableBytes(size))\n );\n },\n };\n}\n","import { writeFileSync } from \"node:fs\";\nimport { globSync } from \"glob\";\n\nimport { dirname, join } from \"../../utilities/path.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface SitemapOptions {\n /** The URL of the sitemap. */\n sitemapUrl?: string;\n\n /**\n * The output sitemap file path relative to the output directory.\n *\n * @default \"sitemap.xml\"\n */\n outfile?: string;\n\n /**\n * Glob patterns to match HTML files to include in the sitemap.\n *\n * **NOTE**: This is relative to the output directory.\n *\n * @default [\"**\\/*.html\"]\n */\n include?: string[];\n\n /**\n * Glob patterns to ignore HTML files from the sitemap.\n *\n * **NOTE**: This is relative to the output directory.\n *\n * @default [ ]\n */\n exclude?: string[];\n}\n\n/**\n * Writes a \"sitemap.xml\" listing the HTML pages that ended up in the output directory.\n *\n * Notes:\n *\n * - Production only, and only when \"sitemapUrl\" is set; without it nothing is generated.\n * - The pages are globbed from the output directory after the build, so the list reflects what was really emitted, and \"include\"\n * and \"exclude\" are matched there as well.\n * - Each entry is the URL of the file's directory with a trailing slash: \"blog/post/index.html\" becomes \".../blog/post/\", and a\n * page that is not an \"index.html\" collapses onto the URL of its parent directory.\n * - Only \"<loc>\" is emitted, no \"lastmod\", \"changefreq\" or \"priority\".\n */\nexport function sitemapPlugin(options: SitemapOptions = {}): Plugin {\n const include = options.include ?? [\"**/*.html\"];\n const ignore = options.exclude ?? [];\n const outfile = options.outfile ?? \"sitemap.xml\";\n\n return {\n name: \"sitemap\",\n\n postBuild() {\n if (!this.production || !options.sitemapUrl) return;\n\n this.log.info(\"Generating sitemap...\");\n\n const sitemapPath = join(this.outdir, outfile);\n\n const htmlFiles = globSync(include, { ignore, cwd: this.outdir });\n\n const urls: string[] = [];\n\n for (const file of htmlFiles) {\n const fullRoute = new URL(dirname(file), options.sitemapUrl).href;\n\n let url = \" <url>\\n\";\n url += ` <loc>${fullRoute.endsWith(\"/\") ? fullRoute : fullRoute + \"/\"}</loc>\\n`;\n url += \" </url>\\n\";\n\n urls.push(url);\n }\n\n const sitemapContent =\n '\\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' +\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\\n' +\n ' xmlns:news=\"http://www.google.com/schemas/sitemap-news/0.9\"\\n' +\n ' xmlns:xhtml=\"http://www.w3.org/1999/xhtml\"\\n' +\n ' xmlns:image=\"http://www.google.com/schemas/sitemap-image/1.1\"\\n' +\n ' xmlns:video=\"http://www.google.com/schemas/sitemap-video/1.1\">\\n' +\n urls.join(\"\") +\n \"</urlset>\";\n\n writeFileSync(sitemapPath, sitemapContent.trim(), \"utf8\");\n },\n };\n}\n","import { valueOrError } from \"../../utilities/value-or-error.ts\";\n\nimport type { Config } from \"svgo\";\n\nasync function optimizeSvgUnsafe(svgCode: string, config?: Config) {\n const { optimize } = await import(\"svgo\");\n\n const result = optimize(svgCode, config);\n return result.data;\n}\n\n/** - Takes SVG string and return an optimized SVG string */\nconst optimizeSvg = valueOrError(optimizeSvgUnsafe);\n\nexport { optimizeSvg };\n","import { mkdirSync, writeFileSync } from \"node:fs\";\nimport { globSync } from \"glob\";\n\nimport { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { safeReadFileSync } from \"../../utilities/read-file.ts\";\nimport { optimizeSvg } from \"./svgo-optimize.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\nimport type { Config } from \"svgo\";\n\nexport interface svgoOptions {\n /**\n * Include SVG files to optimize and write to output directory.\n *\n * @default [\"sources/assets/**\\/*.svg\"]\n */\n include?: string[];\n\n /**\n * Ignore and exclude SVG files from optimization.\n *\n * @default [ ]\n */\n exclude?: string[];\n\n /**\n * Whether to optimize SVG tags in HTML.\n *\n * @default true\n */\n optimizeInHtml?: boolean;\n\n /** SVGO configuration. */\n svgoConfig?: Config;\n}\n\n/**\n * Optimizes SVGs with svgo, both the inline \"<svg>\" tags of a page and the files matched by \"include\", which are optimized and\n * written to the output directory.\n *\n * Notes:\n *\n * - Production only.\n * - Results are cached per SVG string, so an icon repeated across many pages goes through svgo once per build.\n * - Files it wrote are published on \"pluginData.optimizedSvgList\" so copy-assets does not put the originals over them.\n * - The default config is svgo's \"preset-default\" with id cleanup, hidden-element removal and unknown-attribute removal turned off,\n * so ids and hooks the rest of the page relies on survive. Passing \"svgoConfig\" replaces that default entirely.\n * - SVGs inlined in CSS are out of reach; use a PostCSS plugin such as cssnano for those.\n */\nexport function svgoPlugin(options: svgoOptions = {}): Plugin {\n const include = options.include ?? [\"sources/assets/**/*.{svg,svga,svgz}\"];\n const ignore = options.exclude ?? [];\n options.optimizeInHtml ??= true;\n\n const svgoConfig = options.svgoConfig ?? {\n multipass: true,\n plugins: [\n {\n name: \"preset-default\",\n params: {\n overrides: {\n cleanupIds: false,\n removeUnknownsAndDefaults: { unknownAttrs: false },\n removeHiddenElems: false,\n },\n },\n },\n ],\n };\n\n const printFmtError = PrintFormattedError.create({ function: svgoPlugin });\n\n // Raw SVG string -> optimized result. The same icons are inlined on many pages (and pages can be\n // re-transformed), so each distinct SVG only goes through svgo once per build.\n const optimizeCache = new Map<string, string>();\n\n return {\n name: \"svgo\",\n\n setup() {\n this.pluginData.optimizedSvgList ??= new Set<string>();\n },\n\n async transform(metadata) {\n if (!this.production) return;\n\n if (options.optimizeInHtml && isHtmlMetadata(metadata)) {\n const filePath = metadata.filePath;\n\n const elements = metadata.ast.querySelectorAll(\"svg\");\n for (const node of elements) {\n const svgString = node.toString();\n\n let svg = optimizeCache.get(svgString);\n\n if (svg === undefined) {\n const [optimized, error] = await optimizeSvg(svgString, svgoConfig);\n if (error) {\n printFmtError(\"Failed to optimize svg using `svgo`\", error, { filePath, node });\n continue;\n }\n\n svg = optimized;\n optimizeCache.set(svgString, svg);\n // Already-optimized output is stable, so re-transformed pages hit the cache immediately.\n optimizeCache.set(svg, svg);\n }\n\n node.replaceWith(svg);\n }\n\n return;\n }\n },\n\n async postBuild() {\n if (!this.production) return;\n\n const svgFiles = globSync(include, { ignore, cwd: this.root });\n if (svgFiles.length === 0) return;\n\n for (const filePath of svgFiles) {\n const svgFileAbs = join(this.root, filePath);\n\n const [svgString, readError] = safeReadFileSync(svgFileAbs, \"utf8\");\n if (readError) {\n printFmtError(\"Failed to read svg file:\", readError, { filePath });\n continue;\n }\n\n const [optimizedSvg, error] = await optimizeSvg(svgString, svgoConfig);\n if (error) {\n printFmtError(\"Failed to optimize svg using `svgo`\", { filePath });\n continue;\n }\n\n const svgOutPath = join(this.outdir, filePath);\n mkdirSync(dirname(svgOutPath), { recursive: true });\n writeFileSync(svgOutPath, optimizedSvg);\n\n const optimizedSvgList = this.pluginData.optimizedSvgList as Set<string>;\n optimizedSvgList.add(svgFileAbs);\n }\n },\n };\n}\n","import postcss from \"postcss\";\n\nimport { valueOrError } from \"../../utilities/value-or-error.ts\";\n\nimport type { PostcssAst } from \"@staticbolt/core\";\n\nasync function processCssUnsafe(\n css: PostcssAst | string,\n plugins?: readonly postcss.AcceptedPlugin[],\n options?: postcss.ProcessOptions\n) {\n return await postcss(plugins).process(css, options ?? {});\n}\n\n/**\n * Parse CSS string and return the root node\n *\n * @mutate cssRoot\n */\nconst processCss = valueOrError(processCssUnsafe);\n\nexport { processCss };\n","import postcssrc from \"postcss-load-config\";\n\nimport { processCss } from \"../../ast-utilities/postcss-utils/process-css.ts\";\nimport { filterStyleMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { join, resolve } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { valueOrError } from \"../../utilities/value-or-error.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\nimport type postcss from \"postcss\";\n\nconst loadPostcssConfig = valueOrError(postcssrc);\n\nexport interface TransformCssOptions {\n /** Postcss plugins. */\n plugins?: readonly postcss.AcceptedPlugin[];\n\n /**\n * Whether to load postcss config file.\n *\n * @default false\n */\n loadConfig?: boolean;\n}\n\n/**\n * Runs PostCSS plugins over every stylesheet in the build, the \"<style>\" tags of a page included.\n *\n * Notes:\n *\n * - The plugins given in the options run first, followed by the ones from the PostCSS config file when \"loadConfig\" is on.\n * - That config is read once at startup, with the build mode and the project's browserslist as its context.\n * - With no plugins at all the pass is skipped.\n * - A plugin error is reported for the stylesheet it happened in and the build carries on.\n */\nexport function transformCssPlugin(options: TransformCssOptions = {}): Plugin {\n const plugins = options.plugins ?? [];\n const isLoadConfig = options.loadConfig ?? false;\n\n let postcssConfig: postcssrc.Result = { file: \"\", options: {}, plugins: [] };\n let allPlugins: postcss.AcceptedPlugin[] = [...plugins];\n\n const printFmtError = PrintFormattedError.create({ function: transformCssPlugin });\n\n return {\n name: \"transform-css\",\n\n async setup() {\n if (!isLoadConfig) return;\n\n const environment = this.production ? \"production\" : \"development\";\n const virtualCssFile = join(this.root, \"virtual.css\");\n\n const pluginsConfigContext = {\n browserslist: this.browserslist,\n cwd: this.root,\n env: environment,\n } as postcssrc.ConfigContext;\n\n const [loadedPlugins, loadPluginsError] = await loadPostcssConfig(pluginsConfigContext, virtualCssFile);\n if (loadPluginsError !== null) {\n printFmtError(loadPluginsError);\n return;\n }\n\n postcssConfig = loadedPlugins;\n allPlugins = [...plugins, ...postcssConfig.plugins];\n },\n\n async transform(inputMetadata) {\n if (allPlugins.length === 0) return;\n\n for (const { metadata, tag } of filterStyleMetadata(inputMetadata)) {\n const cssRoot = metadata.ast;\n\n const [, processError] = await processCss(cssRoot, allPlugins, { from: resolve(this.root, metadata.filePath) });\n if (processError !== null) {\n printFmtError(processError, { node: tag, filePath: metadata.id });\n }\n }\n },\n };\n}\n","import * as babel from \"@babel/core\";\n\nimport { valueOrError } from \"../../utilities/value-or-error.ts\";\n\nimport type { BabelAst } from \"@staticbolt/core\";\n\nconst babelTransform = valueOrError(babel.transformFromAstSync);\n\nexport interface UseBabelTransformOptions {\n ast: BabelAst;\n root: string;\n filePath: string;\n plugins?: babel.PluginItem[];\n presets?: babel.PluginItem[];\n}\n\nexport function useBabelTransform({ ast, root, filePath, plugins, presets }: UseBabelTransformOptions) {\n return babelTransform(ast, undefined, {\n minified: false,\n filename: filePath,\n cwd: root,\n root,\n presets,\n plugins,\n cloneInputAst: false,\n babelrc: false,\n configFile: false,\n ast: false,\n code: false,\n });\n}\n","import * as babel from \"@babel/core\";\nimport babelPresetEnv from \"@babel/preset-env\";\nimport babelTypeScriptPreset from \"@babel/preset-typescript\";\nimport transformDefine from \"babel-plugin-transform-define\";\n\nimport { useBabelTransform } from \"../../ast-utilities/babel-utils/use-transform.ts\";\nimport { filterScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { extname, join, replaceExtension } from \"../../utilities/path.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface TransformJsPluginOptions {\n presets?: babel.PluginItem[];\n plugins?: babel.PluginItem[];\n}\n\n/**\n * Runs Babel over every script in the build, TypeScript and JSX included.\n *\n * Presets are applied in order: TypeScript (all extensions, JSX enabled), preset-env against the project's browserslist, then the\n * project's own Babel config, then whatever the options add.\n *\n * Notes:\n *\n * - \"_production\" is substituted with the build mode, so a check like \"if (_production)\" is resolved at build time.\n * - Module syntax is preserved; \".ts\", \".jsx\" and \".tsx\" files only change their output path to \".js\".\n * - The result is resolved and loaded again, so imports a Babel plugin introduces still become part of the build.\n */\nexport function transformJsPlugin(options: TransformJsPluginOptions = {}): Plugin {\n const presets: babel.PluginItem[] = [];\n\n const plugins: babel.PluginItem[] = [...(options.plugins ?? [])];\n\n return {\n name: \"transform-js\",\n\n setup() {\n const virtualJsFile = join(this.root, \"virtual.js\");\n const babelConfig = babel.loadPartialConfig({ filename: virtualJsFile, cwd: this.root });\n // const babelConfig = babel.loadPartialConfigSync({ filename: virtualJsFile, cwd: this.root });\n\n presets.push(\n [babelTypeScriptPreset, { allExtensions: true, isTSX: true }],\n [babelPresetEnv, { targets: this.browserslist, modules: false }],\n ...(babelConfig?.options.presets ?? []),\n ...(options.presets ?? [])\n );\n\n plugins.push([transformDefine, { _production: this.production }], ...(babelConfig?.options.plugins ?? []));\n },\n\n async transform(inputMetadata) {\n for (const { metadata } of filterScriptMetadata(inputMetadata)) {\n const [, transformError] = useBabelTransform({\n ast: metadata.ast,\n root: this.root,\n filePath: join(this.root, metadata.filePath),\n plugins,\n presets,\n });\n\n if (transformError) {\n this.log.error(transformError.message);\n return;\n }\n\n if ([\".ts\", \".jsx\", \".tsx\"].includes(extname(metadata.filePath))) {\n metadata.filePath = replaceExtension(metadata.filePath, \".js\");\n }\n\n // Plugins may add imports/exports and introduce new dependencies\n\n const metadataList = await this.resolveAndLoad(metadata);\n\n // Remove current one (first one)\n metadataList.shift();\n\n // Merge\n this.addMetadata(metadataList);\n\n // Transform until this point\n await this.transformAndSync(metadataList);\n }\n },\n };\n}\n","import { isValidRelativePath, splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isWebManifestMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join, normalize, relative } from \"../../utilities/path.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface WebManifestOptions {\n /**\n * The file path to the manifest file relative to the root directory.\n *\n * @default \"./sources/assets/manifest.json\"\n */\n manifestPath?: string;\n\n /**\n * The output file path relative to the output directory.\n *\n * @default \"./manifest.json\"\n */\n outfile?: string;\n}\n\n/**\n * Emits the web app manifest at \"outfile\" and repoints the links to it.\n *\n * Notes:\n *\n * - Only the file at \"manifestPath\" counts as the manifest; links to any other JSON are left alone.\n * - It is rebased once the transforms are done, so the paths inside it (icons, screenshots) keep resolving from the new location.\n * - The links are rewritten in production only; while serving, the manifest stays at its source path.\n */\nexport function webManifestPlugin(options: WebManifestOptions = {}): Plugin {\n const manifestPath = normalize(options.manifestPath ?? \"./sources/assets/manifest.json\");\n const outfile = normalize(options.outfile ?? \"./manifest.json\");\n\n return {\n name: \"web-manifest\",\n\n transformSource(source, filePath, _, dependencyID) {\n if (!this.production || dependencyID !== manifestPath || !isValidRelativePath(source)) return;\n\n const [, suffix] = splitHtmlLink(source);\n\n return relative(dirname(filePath), outfile) + suffix;\n },\n\n async postTransform() {\n if (!this.production) return;\n\n for (const metadata of this.metadataList) {\n if (!isWebManifestMetadata(metadata)) continue;\n\n await this.rebase(metadata, join(this.root, outfile));\n }\n },\n };\n}\n","import { availableParallelism } from \"node:os\";\nimport { Worker } from \"node:worker_threads\";\n\n/**\n * Past a handful of workers the jobs fight each other for memory bandwidth more than they gain from another core, and every one\n * of them carries its own copy of whatever the worker loads. Machines with cores to spare get told a number.\n */\nconst DEFAULT_CONCURRENCY = 8;\n\nexport interface WorkerPoolOptions<Job, Result> {\n /** The worker module to spawn. Whatever it does with a job, and whatever it sends back, is between it and the caller. */\n workerUrl: URL;\n\n /** How many workers may run at once. Defaults to one per core, up to eight. */\n concurrency?: number;\n\n /** Called with what the worker sent back for a job. */\n onResult: (job: Job, result: Result) => void;\n\n /** Called for a job no worker was left to run. */\n onFailure: (job: Job, message: string) => void;\n}\n\n/**\n * Runs jobs across a pool of worker threads.\n *\n * Jobs can be added while the rest of the program is still going: a worker is taken on as there is work for it and each pulls\n * from the queue as it frees up, so a job starts the moment it lands rather than waiting for the whole batch. `drain` waits for\n * what is left over and takes the workers down.\n *\n * A job is posted to the worker as it is and the reply is handed back as it is. The pool never looks inside either, so what a job\n * means is entirely the caller's business.\n */\nexport class WorkerPool<Job, Result> {\n readonly #queue: Job[] = [];\n readonly #workers: Promise<void>[] = [];\n readonly #waiting: (() => void)[] = [];\n\n readonly #workerUrl: URL;\n readonly #concurrency: number;\n readonly #onResult: WorkerPoolOptions<Job, Result>[\"onResult\"];\n readonly #onFailure: WorkerPoolOptions<Job, Result>[\"onFailure\"];\n\n #draining = false;\n\n /** Why the workers gave out, when they did. Reported against the jobs that were left over. */\n #failure: string | undefined;\n\n constructor({ workerUrl, concurrency, onResult, onFailure }: WorkerPoolOptions<Job, Result>) {\n this.#workerUrl = workerUrl;\n this.#concurrency = Math.max(1, concurrency ?? Math.min(DEFAULT_CONCURRENCY, availableParallelism() - 1));\n this.#onResult = onResult;\n this.#onFailure = onFailure;\n }\n\n /** Queues a job, taking on another worker if there is still room for one. */\n add(job: Job): void {\n this.#queue.push(job);\n\n if (this.#workers.length < this.#concurrency) {\n this.#workers.push(this.#keepWorking());\n }\n\n this.#wake();\n }\n\n /** Waits for the queue to empty, then takes the workers down. Whatever nothing was left to run is reported. */\n async drain(): Promise<void> {\n if (this.#workers.length === 0) return;\n\n this.#draining = true;\n this.#wake();\n\n await Promise.all(this.#workers);\n\n this.#workers.length = 0;\n this.#draining = false;\n\n for (const job of this.#queue) {\n this.#onFailure(job, this.#failure ?? \"No worker left to run the job\");\n }\n\n this.#queue.length = 0;\n this.#failure = undefined;\n }\n\n /**\n * Holds a worker for as long as there is work for it, and never rejects.\n *\n * Nothing awaits these until `drain`, and a promise left rejected until then takes the process down as an unhandled rejection.\n * A worker that cannot even start says so here, and `drain` reports it against every job it never got to.\n */\n async #keepWorking(): Promise<void> {\n try {\n await this.#work();\n } catch (error) {\n this.#failure ??= error instanceof Error ? error.message : String(error);\n }\n }\n\n /** One worker, taking the next job whenever it comes free and sitting out the gaps until the caller stops feeding it. */\n async #work(): Promise<void> {\n const worker = new Worker(this.#workerUrl);\n\n worker.on(\"error\", () => {});\n\n try {\n while (true) {\n if (this.#queue.length === 0) {\n if (this.#draining) return;\n await this.#waitForWork();\n continue;\n }\n\n const job = this.#queue.shift() as Job;\n\n let result: Result;\n\n try {\n result = await this.#send(worker, job);\n } catch {\n this.#queue.unshift(job);\n this.#wake();\n return;\n }\n\n this.#onResult(job, result);\n }\n } finally {\n await worker.terminate();\n }\n }\n\n /** One round trip. A worker is only ever given its next job once the one before it came back. */\n #send(worker: Worker, job: Job): Promise<Result> {\n return new Promise((resolve, reject) => {\n const onMessage = (result: Result) => {\n detach();\n resolve(result);\n };\n\n const onError = (error: Error) => {\n detach();\n reject(error);\n };\n\n const onExit = (code: number) => {\n detach();\n reject(new Error(`Worker stopped with exit code ${code}`));\n };\n\n function detach() {\n worker.off(\"message\", onMessage);\n worker.off(\"error\", onError);\n worker.off(\"exit\", onExit);\n }\n\n worker.on(\"message\", onMessage);\n worker.on(\"error\", onError);\n worker.on(\"exit\", onExit);\n\n worker.postMessage(job);\n });\n }\n\n /** Parks a worker until there is something to take, or until the pool is closing and it can stop. */\n #waitForWork(): Promise<void> {\n return new Promise(resolve => {\n this.#waiting.push(resolve);\n });\n }\n\n /** Wakes every parked worker at once. The ones that find nothing left to take park themselves again. */\n #wake(): void {\n const parked = [...this.#waiting];\n this.#waiting.length = 0;\n\n for (const resolve of parked) resolve();\n }\n}\n","import { cpSync, mkdirSync, rmSync, writeFileSync } from \"node:fs\";\n\nimport { WorkerPool } from \"../../helpers/worker-pool.ts\";\nimport { isBinaryAssetMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join, isPathMatch, relative } from \"../../utilities/path.ts\";\n\nimport type { DeferredJob, DeferredJobResult } from \"./deferred-worker.ts\";\nimport type { App, DeferredPass, MetadataBase, Plugin } from \"@staticbolt/core\";\n\nexport interface WriteFilesOptions {\n /** Remove the output directory before emitting files. */\n clean?: boolean;\n\n /**\n * Glob patterns to match files to write.\n *\n * @default [\"**\\/*\"]\n */\n include?: string[];\n\n /**\n * Glob patterns to ignore files from writing.\n *\n * @default [ ]\n */\n exclude?: string[];\n\n /**\n * How many worker threads may minify or format output files at once.\n *\n * @default One per core, up to eight\n */\n concurrency?: number;\n\n minify?: {\n /**\n * Whether to minify output.\n *\n * @default false\n */\n enabled?: boolean;\n\n /**\n * Glob patterns to match files to minify.\n *\n * @default [\"**\\/*\"]\n */\n include?: string[];\n\n /**\n * Glob patterns to ignore files from minifying.\n *\n * @default [ ]\n */\n exclude?: string[];\n };\n\n format?: {\n /**\n * Whether to format output.\n *\n * @default false\n */\n enabled?: boolean;\n\n /**\n * Glob patterns to match files to format.\n *\n * @default [\"**\\/*\"]\n */\n include?: string[];\n\n /**\n * Glob patterns to ignore files from formatting.\n *\n * @default [ ]\n */\n exclude?: string[];\n };\n}\n\n/**\n * Emits the build: everything that survived the pipeline is stringified and written under the output directory, with binary\n * assets copied over as they are.\n *\n * Notes:\n *\n * - Production only. The dev server serves from memory and writes nothing.\n * - \"clean\" removes the output directory before the build starts.\n * - \"include\" and \"exclude\" are matched against the source path, and anything a plugin excluded from emitting is skipped.\n * - \"minify\" and \"format\" carry their own patterns; turning both on for the same file logs a warning.\n * - A file whose path would land outside the output directory is reported and skipped.\n * - Formatting and minifying are the slow part of printing a file, so any plugin willing to hand its final pass over gets taken up\n * on it: the file is written as it came out and its pass goes to a pool of worker threads chewing through them while the files\n * behind it are still being written. The pool is drained before this hook returns, so the output directory is settled by the\n * time anything else runs.\n */\nexport function writeFilesPlugin(options: WriteFilesOptions): Plugin {\n const include = options.include ?? [\"**/*\"];\n const ignore = options.exclude ?? [];\n\n /** Runs the passes the plugins handed over, kept around from the first file that needs one until the write is done. */\n let deferredPool: WorkerPool<DeferredJob, DeferredJobResult> | undefined;\n\n options.minify ??= {};\n options.minify.enabled ??= false;\n options.minify.include ??= [\"**/*\"];\n options.minify.exclude ??= [];\n const minify = options.minify as Required<Exclude<WriteFilesOptions[\"minify\"], undefined>>;\n\n options.format ??= {};\n options.format.enabled ??= false;\n options.format.include ??= [\"**/*\"];\n options.format.exclude ??= [];\n const format = options.format as Required<Exclude<WriteFilesOptions[\"format\"], undefined>>;\n\n function shouldMinifyFile(filePath: string, root: string): boolean {\n return minify.enabled && isPathMatch(filePath, { include: minify.include, ignore: minify.exclude, root });\n }\n\n function shouldFormatFile(filePath: string, root: string): boolean {\n return format.enabled && isPathMatch(filePath, { include: format.include, ignore: format.exclude, root });\n }\n\n /** Made on the first file that needs one, so a build with nothing to format or minify never starts a worker. */\n function poolFor(app: App): WorkerPool<DeferredJob, DeferredJobResult> {\n const report = (job: DeferredJob, message: string) => {\n app.log.error(`Failed to process \"${relative(app.outdir, job.path)}\": ${message}`);\n };\n\n deferredPool ??= new WorkerPool<DeferredJob, DeferredJobResult>({\n workerUrl: resolveWorkerUrl(),\n concurrency: options.concurrency,\n onResult: (job, { error }) => {\n if (error) report(job, error);\n },\n onFailure: report,\n });\n\n return deferredPool;\n }\n\n /** Writes one file, handing its final pass to the pool whenever a plugin offers one. */\n async function emit(app: App, metadata: MetadataBase): Promise<void> {\n if (app.emitExclude.has(metadata)) return;\n\n const isIncluded = isPathMatch(metadata.id, { include, ignore, root: app.root });\n if (!isIncluded) return;\n\n if (metadata.filePath.startsWith(\"../\")) {\n app.log.error(`file path \"${metadata.filePath}\" is outside of the output directory \"${app.outdir}\". Skipping...`);\n return;\n }\n\n const shouldMinify = shouldMinifyFile(metadata.id, app.root);\n const shouldFormat = shouldFormatFile(metadata.id, app.root);\n\n if (shouldMinify && shouldFormat) {\n app.log.warn(`\"minify\" and \"format\" are enabled for \"${metadata.id}\" but only one can be used.`);\n }\n\n if (isBinaryAssetMetadata(metadata)) {\n const copyFrom = join(app.root, metadata.id);\n const copyTo = join(app.outdir, metadata.filePath);\n cpSync(copyFrom, copyTo, { recursive: true });\n return;\n }\n\n // stringify\n let deferredPass: DeferredPass | undefined;\n\n const code = await app.stringify(metadata, {\n format: shouldFormat,\n minify: shouldMinify,\n defer: pass => {\n deferredPass = pass;\n },\n });\n\n if (typeof code !== \"string\") {\n app.log.error(`Failed to stringify \"${metadata.id}\"`);\n return;\n }\n\n if (!code) {\n app.log.warn(`Writing empty file \"${metadata.filePath}\"`);\n }\n\n // write\n const outputFile = join(app.outdir, metadata.filePath);\n mkdirSync(dirname(outputFile), { recursive: true });\n writeFileSync(outputFile, code, \"utf8\");\n\n if (deferredPass) {\n poolFor(app).add({ path: outputFile, pass: deferredPass });\n }\n }\n\n return {\n name: \"emit-files\",\n\n setup() {\n if (!this.production) return;\n\n if (options.clean) {\n rmSync(this.outdir, { recursive: true, force: true });\n }\n },\n\n async write() {\n if (!this.production) return;\n\n try {\n for (const metadata of this.metadataList) {\n await emit(this, metadata);\n }\n } finally {\n // Worker threads hold the process open, so the pool has to come down even if a file took the write out with it.\n await deferredPool?.drain();\n }\n },\n };\n}\n\nlet workerUrl: URL | undefined;\n\n/** Resolved through the package's own exports, so it holds up wherever this plugin ended up relative to its worker. */\nfunction resolveWorkerUrl(): URL {\n workerUrl ??= new URL(import.meta.resolve(\"@staticbolt/core/deferred-worker\"));\n return workerUrl;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport vm from \"node:vm\";\nimport * as babel from \"@babel/core\";\nimport transformModulesCommonjs from \"@babel/plugin-transform-modules-commonjs\";\nimport * as t from \"@babel/types\";\n\nimport { dirname, extname, join } from \"../utilities/path.ts\";\nimport { valueOrError } from \"../utilities/value-or-error.ts\";\n\nimport type { JSDOM } from \"jsdom\";\n\ninterface ExecuteJsInVmOptions {\n /** The root directory of the project, where JSON imports are read from */\n root: string;\n\n /** The module to run, as a path relative to the root */\n entryFile: string;\n\n /** The source of a module, the entry file and everything it imports. Nothing means the module does not exist */\n getCode(filePath: string): string | void | Promise<string | void>;\n\n /** Globals for the scripts, applied on top of the built-in ones */\n context?: Record<string, unknown>;\n\n /** Called with every project file the VM loads, including the entry file and JSON imports, but not `node:` built-ins */\n onModuleLoad?(filePath: string): void;\n\n /** When given, `document` and `window` come from a jsdom instance of this html */\n html?: string;\n}\n\ninterface ExecuteJsInVmResult {\n exports: { [k: string]: unknown };\n dom: JSDOM | undefined;\n}\n\n/** Runs an ES module graph inside a `node:vm` context and hands back what the entry module exported. */\nasync function executeJsInVmUnsafe(options: ExecuteJsInVmOptions): Promise<ExecuteJsInVmResult> {\n const { dom, context } = await createSandbox(options.html, options.context);\n\n const runner = new ModuleRunner(context, options);\n const exports = await runner.import(options.entryFile);\n\n return { exports: { ...exports }, dom };\n}\n\n/** A jsdom window when there is html to work on, a bare object with the essentials otherwise. */\nasync function createSandbox(html: string | undefined, globals: Record<string, unknown> = {}) {\n let dom: JSDOM | undefined;\n\n if (html) {\n const { JSDOM, VirtualConsole } = await import(\"jsdom\");\n dom = new JSDOM(html, { virtualConsole: new VirtualConsole(), url: \"http://localhost/\" });\n }\n\n const window = dom ? dom.window : {};\n if (!dom) {\n Object.assign(window, { setTimeout, setInterval, clearInterval, clearTimeout, fetch, URL });\n }\n\n Object.assign(window, { console }, globals);\n\n return { dom, context: vm.createContext(window) };\n}\n\ntype ModuleExports = Record<string, unknown>;\n\n/** What a module body gets to see of the module system. The names are what `toModuleBody` rewrites the syntax to. */\ninterface ModuleScope {\n require(specifier: string): ModuleExports;\n __import(specifier: string): Promise<ModuleExports>;\n __meta: { url: string; resolve(url: string): string };\n exports: ModuleExports;\n}\n\ntype ModuleBody = (scope: ModuleScope) => Promise<void>;\n\nconst BASE_META_URL = \"http://localhost:3000\";\n\n/**\n * Runs modules the way ES modules run: each one once, its static imports before it in source order, top-level `await` included. A\n * module that imports one of its own importers (a cycle) gets its exports as far as they are.\n *\n * Modules are rewritten to CommonJS and run as functions in the context, which keeps them collectable once the run is over.\n */\nclass ModuleRunner {\n /** Resolves to the module's exports once it has run. Registered before the module starts, so it only ever runs once. */\n readonly #runs = new Map<string, Promise<ModuleExports>>();\n\n /** The exports of every module that has started, which is what a cycle gets to see. */\n readonly #exports = new Map<string, ModuleExports>();\n\n readonly #context: vm.Context;\n readonly #options: ExecuteJsInVmOptions;\n\n constructor(context: vm.Context, options: ExecuteJsInVmOptions) {\n this.#context = context;\n this.#options = options;\n }\n\n /**\n * Runs the module unless it already has, and resolves to its exports. `importers` is the chain of static imports that led here,\n * empty for the entry and for dynamic imports.\n */\n import(id: string, importers: ReadonlySet<string> = new Set()): Promise<ModuleExports> {\n let run = this.#runs.get(id);\n\n if (!run) {\n run = this.#run(id, importers);\n this.#runs.set(id, run);\n }\n\n return run;\n }\n\n async #run(id: string, importers: ReadonlySet<string>): Promise<ModuleExports> {\n const exports: ModuleExports = {};\n this.#exports.set(id, exports);\n\n if (id.startsWith(\"node:\")) {\n return Object.assign(exports, (await import(id)) as ModuleExports);\n }\n\n this.#options.onModuleLoad?.(id);\n\n if (extname(id) === \".json\") {\n exports.default = this.#readJson(id);\n return exports;\n }\n\n const source = await this.#options.getCode(id);\n if (!source) {\n throw new Error(`[executeJsInVM] can't find the script '${id}'`);\n }\n\n const { code, imports } = await toModuleBody(source, id);\n\n // A static import that is already on the chain is an importer of this module: a cycle, not waited on\n const chain = new Set(importers).add(id);\n for (const specifier of imports) {\n const importId = this.#resolve(specifier, id);\n if (!chain.has(importId)) {\n await this.import(importId, chain);\n }\n }\n\n const body = this.#compile(code, id);\n\n await body({\n require: specifier => this.#require(specifier, id),\n __import: specifier => this.import(this.#resolve(specifier, id)),\n __meta: createImportMeta(id),\n exports,\n });\n\n return exports;\n }\n\n /** Creates the function in the context, so its globals are the sandbox's. */\n #compile(code: string, id: string): ModuleBody {\n const script = new vm.Script(`\"use strict\"; (async function ({ require, __import, __meta, exports }) {\\n${code}\\n})`, {\n filename: id,\n lineOffset: -1,\n });\n\n return script.runInContext(this.#context) as ModuleBody;\n }\n\n #require(specifier: string, importer: string): ModuleExports {\n const exports = this.#exports.get(this.#resolve(specifier, importer));\n if (!exports) {\n throw new Error(`[executeJsInVM] '${specifier}' has not run before '${importer}'`);\n }\n\n return exports;\n }\n\n #resolve(specifier: string, importer: string): string {\n return specifier.startsWith(\"node:\") ? specifier : join(dirname(importer), specifier);\n }\n\n #readJson(id: string): unknown {\n const jsonPath = join(this.#options.root, id);\n if (!existsSync(jsonPath)) {\n throw new Error(`[executeJsInVM] can't find the file '${id}'`);\n }\n\n return JSON.parse(readFileSync(jsonPath, \"utf8\"));\n }\n}\n\nfunction createImportMeta(id: string): ModuleScope[\"__meta\"] {\n if (extname(id) === \".html\") {\n id = dirname(id) + \"/\";\n }\n\n const url = new URL(id, BASE_META_URL).href;\n\n return {\n url,\n resolve: specifier => new URL(specifier, url).href,\n };\n}\n\ninterface ModuleBodySource {\n code: string;\n imports: string[];\n}\n\n/**\n * The same module runs once per page that uses it, so its rewrite is kept by source. The oldest entries go once there are more\n * than `MODULE_BODY_CACHE_SIZE`, which keeps a long editing session from piling up dead ones.\n */\nconst moduleBodyCache = new Map<string, ModuleBodySource>();\nconst MODULE_BODY_CACHE_SIZE = 256;\n\n/**\n * Rewrites an ES module into the body of a `ModuleBody`: imports and exports become `require` and `exports`, `import.meta`\n * becomes `__meta` and `import()` becomes `__import()`. Also lists what the module imports statically.\n */\nasync function toModuleBody(source: string, id: string): Promise<ModuleBodySource> {\n const cached = moduleBodyCache.get(source);\n if (cached) {\n return cached;\n }\n\n const imports: string[] = [];\n\n const result = await babel.transformAsync(source, {\n filename: id,\n sourceType: \"module\",\n babelrc: false,\n configFile: false,\n compact: false,\n sourceMaps: false,\n plugins: [collectImportsAndRewriteMeta(imports), [transformModulesCommonjs, { importInterop: \"none\", strictMode: false }]],\n });\n\n if (!result?.code) {\n throw new Error(`[executeJsInVM] failed to transform '${id}'`);\n }\n\n const moduleBody = { code: result.code, imports };\n moduleBodyCache.set(source, moduleBody);\n\n if (moduleBodyCache.size > MODULE_BODY_CACHE_SIZE) {\n moduleBodyCache.delete(moduleBodyCache.keys().next().value!);\n }\n\n return moduleBody;\n}\n\n/** Lists the static import sources into `imports`, and turns `import.meta` into `__meta` and `import()` into `__import()`. */\nfunction collectImportsAndRewriteMeta(imports: string[]): babel.PluginObj {\n return {\n visitor: {\n ImportDeclaration(path) {\n imports.push(path.node.source.value);\n },\n\n ExportNamedDeclaration(path) {\n if (path.node.source) {\n imports.push(path.node.source.value);\n }\n },\n\n ExportAllDeclaration(path) {\n imports.push(path.node.source.value);\n },\n\n MetaProperty(path) {\n if (path.node.meta.name === \"import\") {\n path.replaceWith(t.identifier(\"__meta\"));\n }\n },\n\n CallExpression(path) {\n if (t.isImport(path.node.callee)) {\n path.node.callee = t.identifier(\"__import\");\n }\n },\n },\n };\n}\n\nconst executeJsInVM = valueOrError(executeJsInVmUnsafe);\n\nexport { executeJsInVM };\n","import { isTypeScriptScript } from \"../../helpers/lsp-checks.ts\";\n\nimport type { DocumentInfo, ElementInfo, EmbeddedLanguage } from \"@staticbolt/core\";\n\n/** The attribute names the plugin was set up with. */\nexport interface BuildTimeNames {\n /** Marks a script as running at build time. */\n build: string;\n\n /** Gives the script a full DOM instead of the page's tree. */\n fullDom: string;\n\n /** Holds a JSON object of extra globals for the script. */\n context: string;\n}\n\n/** What the sandbox gives every build-time script; these shadow the DOM globals of the same name. */\nconst GLOBALS = `declare const StaticBolt: import(\"@staticbolt/core\").App;\ndeclare const window: typeof globalThis;\ndeclare const __filepath: string;\ndeclare const __id: string;`;\n\n/** The page's tree is the parser's, not the DOM's: its node types take the DOM names, so the code reads as it runs. */\nconst PARSER_TYPES = [\"Document\", \"HTMLElement\", \"Node\", \"TextNode\", \"CommentNode\", \"NodeType\"]\n .map(name => `type ${name} = import(\"@staticbolt/node-html-parser\").${name};`)\n .join(\"\\n\");\n\n/**\n * The bodies of the build-time scripts marked `type=\"application/x-typescript\"`, served as TypeScript that sees the sandbox\n * globals: completion, hover and type errors. Claimed before the core plugin, later in the config, sees the browser in them.\n */\nexport function embeddedLanguages(names: BuildTimeNames): EmbeddedLanguage[] {\n return [\n {\n name: \"build-time\",\n filter: () => true,\n // Each script runs on its own, so each is a module of its own\n findRegions: document =>\n buildTimeScripts(document, names).flatMap(script =>\n script.contentRange ? { ...script.contentRange, isModule: true } : []\n ),\n isColouredByEditor: true,\n prelude: document => prelude(buildTimeScripts(document, names), names),\n },\n ];\n}\n\n/** The build-time scripts of a document that are marked as TypeScript. */\nfunction buildTimeScripts(document: DocumentInfo, names: BuildTimeNames): ElementInfo[] {\n return document.select(\"script\").filter(script => script.has(names.build) && isTypeScriptScript(script));\n}\n\n/**\n * The declarations for a document's build-time scripts: the sandbox globals, and `document` as the parser's tree or, with a full\n * DOM, the DOM's.\n */\nfunction prelude(scripts: ElementInfo[], names: BuildTimeNames): string {\n const hasFullDom = scripts.some(script => script.has(names.fullDom));\n const lines = [GLOBALS];\n\n if (!hasFullDom) {\n lines.push(PARSER_TYPES);\n }\n\n lines.push(\"declare const document: Document;\");\n\n return lines.join(\"\\n\");\n}\n","import { DependencyTracker } from \"../../helpers/dependency-tracker.ts\";\nimport { executeJsInVM } from \"../../helpers/execute-js-in-vm.ts\";\nimport { isScriptType } from \"../../helpers/is-script-type.ts\";\nimport { checkFileExists, checkJsonObject, isEmptyElement, isJavaScript } from \"../../helpers/lsp-checks.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata, isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { embeddedLanguages } from \"./lsp.ts\";\n\nimport type { Plugin, ScriptMetadata } from \"@staticbolt/core\";\n\nexport interface HtmlBuildTimeScriptOptions {\n /**\n * The name of the attribute on the script tag that marks it for execution.\n *\n * @default \"build-time\"\n */\n buildAttribute?: string;\n\n /**\n * The name of the attribute on the script tag that enables full DOM context using `jsdom`, otherwise `node-html-parser` is\n * used.\n *\n * @default \"full-dom\"\n */\n fullDomAttribute?: string;\n\n /**\n * The name of the attribute on the script tag that holds a JSON object, whose entries are exposed as globals to the script\n * during execution.\n *\n * @default \"context\"\n */\n contextAttribute?: string;\n}\n\n/**\n * Executes script tags marked with \"build-time\" during the build and keeps whatever they did to the page. The tag itself never\n * reaches the output.\n *\n * Attributes (names configurable via HtmlBuildTimeScriptOptions):\n *\n * - \"build-time\": execute this tag, inline or through \"src\".\n * - \"full-dom\": run against a jsdom document instead of the lighter node-html-parser AST.\n * - \"context\": a JSON object whose entries become globals for that script.\n *\n * Scripts run in \"node:vm\" with \"document\", \"window\", \"StaticBolt\" (the app), \"__filepath\" and \"__id\" in scope. \"context\" entries\n * are applied last, so they can shadow those names; if the JSON fails to parse the script still runs without them.\n *\n * Notes:\n *\n * - \"full-dom\" needs a fully constructed page (a head and a body), so place this plugin last when using it.\n * - Failures are per tag: the error is logged and the rest of the page carries on.\n * - In development the files each page executed are tracked, so editing one of them recompiles the pages that used it.\n */\nexport function htmlBuildTimeScript(options: HtmlBuildTimeScriptOptions = {}): Plugin {\n const buildAttribute = options.buildAttribute ?? \"build-time\";\n const fullDomAttribute = options.fullDomAttribute ?? \"full-dom\";\n const contextAttribute = options.contextAttribute ?? \"context\";\n const query = `script[${buildAttribute}]`;\n\n const printFmtError = PrintFormattedError.create({ function: htmlBuildTimeScript });\n\n /** Page → the files its build-time scripts executed. Used to recompile the page when one of them changes. */\n const dependencies = new DependencyTracker();\n\n return {\n name: \"html-build-time-script\",\n\n async postTransform() {\n // Only the dev server consumes this, and building it is not free\n const isTracking = !this.production;\n const executedSources = new Map<string, Set<string>>();\n\n for (const metadata of this.metadataList) {\n if (!isHtmlMetadata(metadata)) {\n continue;\n }\n\n // Is the page is fully constructed\n const isReady = metadata.ast.querySelector(\"body\") && metadata.ast.querySelector(\"head\");\n\n const scripts = metadata.ast.querySelectorAll(query);\n if (scripts.length === 0) continue;\n\n const pageSources = isTracking ? (executedSources.get(metadata.id) ?? new Set<string>()) : undefined;\n if (pageSources) {\n executedSources.set(metadata.id, pageSources);\n }\n\n for (const node of scripts) {\n const shouldUseFullDom = node.hasAttribute(fullDomAttribute);\n\n const scriptType = node.getAttribute(\"type\");\n if (!isScriptType(scriptType)) {\n continue;\n }\n\n if (shouldUseFullDom && !isReady) {\n printFmtError(\"Script cannot be executed until the page is fully constructed.\", { node });\n continue;\n }\n\n let scriptMetadata: ScriptMetadata;\n\n // Script with content\n const metadataID = node.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (metadataID) {\n const inlinedMetadata = metadata.scriptsMetadataList.get(metadataID);\n if (!inlinedMetadata) {\n printFmtError(\"Failed to execute script tag. Missing metadata\", { node });\n continue;\n }\n\n scriptMetadata = inlinedMetadata;\n }\n // Script with src attribute\n else {\n const source = node.getAttribute(\"src\");\n if (!source) {\n printFmtError(\"Failed to execute script tag. Missing src attribute\", { node });\n continue;\n }\n\n const [link] = splitHtmlLink(source);\n const sourceRelative = join(dirname(metadata.filePath), link);\n\n const fileMetadata = this.findMetadata({ filePath: sourceRelative });\n if (!isScriptMetadata(fileMetadata)) {\n printFmtError(`Failed to execute script tag. Missing metadata \"${sourceRelative}\"`, { node });\n continue;\n }\n\n scriptMetadata = fileMetadata;\n }\n\n const getCode = async (targetPath: string) => {\n // Entry point\n if (targetPath === scriptMetadata.filePath) {\n return await this.stringify(scriptMetadata);\n }\n\n // External file\n const foundMetadata = this.findMetadata({ filePath: targetPath });\n if (foundMetadata) {\n return await this.stringify(foundMetadata);\n }\n };\n\n const contextAttributeValue = node.getAttribute(contextAttribute);\n\n let extraContext: Record<string, unknown> = {};\n if (contextAttributeValue) {\n try {\n extraContext = JSON.parse(contextAttributeValue) as Record<string, unknown>;\n } catch (error) {\n printFmtError(\"Failed to parse context attribute\\n\", contextAttributeValue, error as Error, { node });\n }\n }\n\n const [executeResult, error] = await executeJsInVM({\n root: this.root,\n entryFile: scriptMetadata.filePath,\n html: shouldUseFullDom ? await this.stringify(metadata) : undefined,\n context: {\n document: shouldUseFullDom ? undefined : metadata.ast,\n window: globalThis,\n StaticBolt: this,\n __filepath: metadata.filePath,\n __id: metadata.id,\n ...extraContext,\n },\n getCode,\n // The VM reports output paths, while the dev server invalidates by source id\n onModuleLoad: pageSources\n ? sourcePath => pageSources.add(this.findMetadata({ filePath: sourcePath })?.id ?? sourcePath)\n : undefined,\n });\n\n if (error) {\n printFmtError(\"Failed to execute script tag\", error, { node });\n continue;\n }\n\n if (shouldUseFullDom && executeResult.dom) {\n const output = executeResult.dom.serialize();\n metadata.ast.root.set_content(output);\n }\n }\n\n // remove script tags after executing\n for (const node of metadata.ast.querySelectorAll(query)) {\n node.remove();\n }\n }\n\n for (const [id, sources] of executedSources) {\n dependencies.update(id, sources);\n }\n },\n\n onFileEvent(event, id) {\n if (event === \"unlink\") {\n dependencies.delete(id);\n }\n },\n\n resolveCompileList(compileSet, event) {\n if (event !== \"change\") return;\n\n for (const id of Array.from(compileSet)) {\n for (const importer of dependencies.getImporters(id)) {\n compileSet.add(importer);\n }\n }\n },\n\n lspEmbeddedLanguages() {\n return embeddedLanguages({ build: buildAttribute, fullDom: fullDomAttribute, context: contextAttribute });\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: \"script\",\n description:\n `Adds the \\`${buildAttribute}\\`, \\`${fullDomAttribute}\\` and \\`${contextAttribute}\\` attributes,` +\n \" which execute the script during the build and keep whatever it did to the page. The tag itself never reaches the output.\",\n attributes: [\n {\n name: buildAttribute,\n description:\n \"This attribute is used to mark the script as build-time script.\" +\n '\\n\\nWith `type=\"application/x-typescript\"` the staticbolt language server serves the script with the sandbox' +\n \" globals (`StaticBolt`, `document`, `window`, `__filepath`, `__id`) in place of the browser's.\",\n valueSet: \"v\",\n },\n {\n name: fullDomAttribute,\n description:\n \"Opt into a full DOM context using `jsdom`. When not present, the lighter `@staticbolt/node-html-parser` is used instead.\",\n valueSet: \"v\",\n },\n {\n name: contextAttribute,\n description: \"Pass global context object as JSON to be available in the script during execution.\",\n },\n ],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const scripts = document.select(\"script\");\n\n for (const element of scripts) {\n const build = element.attribute(buildAttribute);\n if (!build) continue;\n\n if (!isJavaScript(element)) {\n report.warn(build.nameRange, `\"${buildAttribute}\" does nothing on a script that is not JavaScript`);\n continue;\n }\n\n const context = element.attribute(contextAttribute);\n if (context) {\n checkJsonObject(context, report);\n }\n\n const source = element.attribute(\"src\");\n if (!source?.value && isEmptyElement(element, document)) {\n report.error(build.nameRange, `\"${buildAttribute}\" needs a \"src\" or some code in the script to run`);\n continue;\n }\n\n if (source) {\n checkFileExists(source, document, report);\n }\n }\n },\n };\n}\n","import { Log } from \"../../utilities/logger.ts\";\nimport { isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join, isPathMatch, relative } from \"../../utilities/path.ts\";\n\nimport type { App, ScriptMetadata } from \"@staticbolt/core\";\nimport type { Plugin } from \"esbuild\";\n\ntype CheckExternal = (strings: string) => boolean;\n\nexport function loaderPlugin(this: App, outFile: string, isExternalCheck: CheckExternal): Plugin {\n const root = this.root;\n const outFileAbs = join(root, outFile);\n\n // eslint-disable-next-line unicorn/no-this-assignment, @typescript-eslint/no-this-alias\n const app = this;\n\n return {\n name: \"resolve-loader\",\n\n setup(build) {\n // Intercepts relative JS imports so they can be routed through the app metadata system\n // instead of being resolved from disk by esbuild directly.\n build.onResolve({ filter: /\\.(js|mjs|cjs)$/ }, arguments_ => {\n if (!arguments_.path.startsWith(\".\")) return;\n\n const absSource = join(arguments_.resolveDir, arguments_.path);\n const source = relative(root, absSource);\n\n // Modules marked as external are excluded from the bundle. The path is made relative\n // to the output file so the bundled output can reference it correctly at runtime.\n if (isExternalCheck(source)) {\n const relativeToOutFile = relative(dirname(outFile), source);\n return { path: relativeToOutFile, external: true };\n }\n\n // Let esbuild resolve node_modules directly rather than routing them through\n // the loader namespace, since we have no metadata for those files.\n if (isPathMatch(source, { include: [\"**/node_modules/**\"], ignore: [], root })) {\n return { path: absSource };\n }\n\n const scriptMetadata = app.findMetadata({ filePath: source });\n if (!isScriptMetadata(scriptMetadata)) {\n Log.error(`[htmlBundleScriptPlugin:onResolve] Script metadata for the path \"${source}\" not found`);\n return;\n }\n\n // Route through the loader namespace so onLoad can rebase and stringify\n // the script using app metadata rather than reading it from disk.\n return { path: absSource, namespace: \"loader\", pluginData: scriptMetadata };\n });\n\n // Handles every script that was routed into the loader namespace by onResolve.\n // Clones and rebases each one relative to the output file before stringifying.\n build.onLoad({ filter: /\\.(js|mjs|cjs)$/, namespace: \"loader\" }, async arguments_ => {\n const scriptMetadata = arguments_.pluginData as ScriptMetadata | undefined;\n if (!scriptMetadata) {\n Log.error(`[htmlBundleScriptPlugin:onLoad] Script metadata for the path \"${arguments_.path}\" not found.\"`);\n return;\n }\n\n const clone = app.clone(scriptMetadata);\n await app.rebase(clone, outFileAbs);\n const contents = await app.stringify(clone);\n\n return { contents, resolveDir: dirname(outFileAbs), loader: \"js\" };\n });\n },\n };\n}\n","import * as esbuild from \"esbuild\";\n\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { valueOrError, type ValueOrError } from \"../../utilities/value-or-error.ts\";\nimport { loaderPlugin } from \"./esbuild-plugin.ts\";\n\nimport type { App } from \"@staticbolt/core\";\n\nconst bundleFunction = valueOrError(esbuild.build);\n\ninterface Options {\n contents: string;\n entryPoint: string;\n outfile: string;\n iife: boolean;\n isExternalCheck: (strings: string) => boolean;\n}\n\nexport async function bundleScriptWithEsbuild(this: App, options: Options): Promise<ValueOrError<string>> {\n const { contents, entryPoint, outfile, iife, isExternalCheck } = options;\n\n const root = this.root;\n\n const [bundleResult, error] = await bundleFunction({\n stdin: {\n contents,\n sourcefile: join(root, entryPoint),\n resolveDir: join(root, dirname(entryPoint)),\n },\n outfile,\n absWorkingDir: root,\n bundle: true,\n minify: false,\n treeShaking: true,\n write: false,\n platform: \"browser\",\n packages: \"bundle\",\n format: iife ? \"iife\" : \"esm\",\n target: \"es2022\",\n legalComments: \"none\",\n logLevel: \"silent\",\n charset: \"utf8\",\n plugins: [loaderPlugin.call(this, outfile, isExternalCheck)],\n });\n\n if (error) {\n return [null, error];\n }\n\n const outCode = bundleResult?.outputFiles?.[0].text;\n\n if (typeof outCode !== \"string\") {\n return [null, new Error(`Failed to bundle the script tag \"${entryPoint}\"`)];\n }\n\n return [outCode, null];\n}\n","import { isScriptType } from \"../../helpers/is-script-type.ts\";\nimport { checkFileExists, isEmptyElement, isJavaScript } from \"../../helpers/lsp-checks.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { isHtmlMetadata, isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join, isPathMatch, normalize, parsePatterns, relative, replaceExtension } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { bundleScriptWithEsbuild } from \"./esbuild-bundle.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlBundleScriptOptions {\n /**\n * Glob patterns for modules that should be treated as external (excluded from bundling).\n *\n * Applied when the `externalsAttribute` is not set on the script tag.\n *\n * @default [ ]\n */\n externals?: string[];\n\n /**\n * Glob patterns that exempt modules from being treated as external, even if they match `externals`.\n *\n * Applied when the `externalsExcludeAttribute` is not set on the script tag.\n *\n * @default [ ]\n */\n externalsExclude?: string[];\n\n /**\n * The HTML attribute name that enables bundling on a script tag.\n *\n * @default \"bundle\"\n */\n bundleAttribute?: string;\n\n /**\n * The HTML attribute name that specifies the output file path for the bundled script.\n *\n * The attribute value is always resolved relative to the output directory, regardless of where the HTML file lives.\n *\n * @default \"bundle-out\"\n */\n bundleOutAttribute?: string;\n\n /**\n * The HTML attribute name that specifies which modules to treat as external.\n *\n * Accepts a semicolon-separated list of glob patterns.\n *\n * @default \"bundle-externals\"\n */\n externalsAttribute?: string;\n\n /**\n * The HTML attribute name that specifies which modules to exempt from being external.\n *\n * Accepts a semicolon-separated list of glob patterns.\n *\n * @default \"bundle-externals-exclude\"\n */\n externalsExcludeAttribute?: string;\n\n /**\n * The HTML attribute name that switches the bundle output format from ESM to IIFE.\n *\n * The attribute is a boolean flag; its value is ignored.\n *\n * @default \"iife\"\n */\n iifeAttribute?: string;\n}\n\n/**\n * Bundles script tags in HTML files with esbuild. Opt-in per tag.\n *\n * Attributes (names configurable via HtmlBundleScriptOptions):\n *\n * - \"bundle\": bundle this tag.\n * - \"bundle-out\": output path, resolved from the output directory, not from the HTML file.\n * - \"bundle-externals\" / \"bundle-externals-exclude\": semicolon-separated globs, override the plugin defaults for this tag.\n * - \"iife\": emit an IIFE instead of ESM.\n *\n * Without \"bundle-out\", an inline script is bundled in place and a \"src\" script is written to \"{filename}.bundle.js\" next to the\n * original. With it, \"src\" is pointed at the output path and inline content is cleared.\n *\n * Notes:\n *\n * - Bundling only runs in production; in dev the attributes are just stripped. They never reach the output either way.\n * - If the target output path is already bundled, the work is skipped and \"src\" is simply pointed at it.\n * - \"iife\" only changes the esbuild format; the tag's \"type\" is untouched, so remove \"type=module\" yourself if needed.\n */\nexport function htmlBundleScriptPlugin(options: HtmlBundleScriptOptions = {}): Plugin {\n const defaultExternal = options.externals ?? [\"**/node_modules/**\"];\n const defaultExternalExclude = options.externalsExclude ?? [];\n\n const bundleAttribute = options.bundleAttribute ?? \"bundle\";\n const bundleOutAttribute = options.bundleOutAttribute ?? \"bundle-out\";\n const externalsAttribute = options.externalsAttribute ?? \"bundle-externals\";\n const externalsExcludeAttribute = options.externalsExcludeAttribute ?? \"bundle-externals-exclude\";\n const iifeAttribute = options.iifeAttribute ?? \"iife\";\n\n const query = `script[${bundleAttribute}]`;\n\n const printFmtError = PrintFormattedError.create({ function: htmlBundleScriptPlugin });\n\n return {\n name: \"html-bundle-script\",\n\n // Note: the bundle-out attribute is intentionally NOT registered via sourcesProvider.\n // Its value is relative to the output root, while the sources resolve/rebase pipeline\n // assumes file-relative paths and would corrupt it.\n\n async transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const filePath = metadata.filePath;\n\n const scripts = metadata.ast.querySelectorAll(query);\n\n for (const node of scripts) {\n const bundleOutValue = node.getAttribute(bundleOutAttribute);\n // bundle-out is always resolved from the output root, e.g. \"./accordion.js\" lands at \"<outdir>/accordion.js\".\n const bundleOut = bundleOutValue ? normalize(bundleOutValue.replace(/^\\/+/, \"\")) : null;\n const externalsAttributeValue = node.getAttribute(externalsAttribute);\n const externalsExcludeAttributeValue = node.getAttribute(externalsExcludeAttribute);\n const isIife = node.hasAttribute(iifeAttribute);\n\n node.removeAttribute(bundleAttribute);\n node.removeAttribute(bundleOutAttribute);\n node.removeAttribute(externalsAttribute);\n node.removeAttribute(externalsExcludeAttribute);\n node.removeAttribute(iifeAttribute);\n\n const scriptType = node.getAttribute(\"type\");\n if (!isScriptType(scriptType)) continue;\n\n if (!this.production) continue;\n\n // Resolve whether the script is src-based or inline.\n const scriptSource = node.getAttribute(\"src\");\n const scriptMetadataID = node.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n const scriptMetadata = scriptMetadataID ? metadata.scriptsMetadataList.get(scriptMetadataID) : undefined;\n const hasContent = !scriptSource && Boolean(scriptMetadata);\n\n if (!scriptSource && !hasContent) {\n printFmtError('The script tag does not have a \"src\" attribute or code content', { node, filePath });\n continue;\n }\n\n // An inline script with no explicit output path stays inlined after bundling.\n const isInlined = !bundleOut && hasContent;\n\n // Resolve externals from the tag attributes, falling back to plugin-level defaults.\n const externals = parsePatterns(externalsAttributeValue) ?? defaultExternal;\n const externalsIgnore = parsePatterns(externalsExcludeAttributeValue) ?? defaultExternalExclude;\n\n let entryPoint = \"\";\n let outfile = \"\";\n let contents = \"\";\n\n // hasContent and scriptSource are mutually exclusive: hasContent requires !scriptSource.\n if (hasContent) {\n // Default output path is the HTML file itself when staying inline,\n // or the bundleOut path when writing to a separate file.\n outfile = bundleOut ?? filePath;\n\n // The bundled result will replace the tag content in place.\n if (isInlined) {\n entryPoint = metadata.filePath;\n contents = await this.stringify(scriptMetadata!);\n }\n\n // The bundled result is written to a separate file; clear the inline content.\n else {\n node.textContent = \"\";\n\n // Already bundled\n const existingMetadata = this.findMetadata({ filePath: outfile });\n if (existingMetadata) {\n this.log.info(`The entry point \"${entryPoint}\" is already bundled in \"${outfile}\", skipping...`);\n\n // Remove the old inline metadata entry and point the tag to the bundled file.\n if (scriptMetadataID) {\n metadata.scriptsMetadataList.delete(scriptMetadataID);\n }\n\n node.setAttribute(\"src\", relative(dirname(filePath), outfile));\n continue;\n }\n\n // entryPoint is the output file because the content will be rebased to it.\n entryPoint = outfile;\n\n // Rebase imports to be relative to the output file location.\n const clone = this.clone(scriptMetadata!);\n await this.rebase(clone, join(this.root, outfile));\n\n contents = await this.stringify(clone);\n }\n }\n\n // No content, so the script is src-based.\n else if (scriptSource) {\n // Default output path is \"{original-filename}.bundle.js\" next to the original file when no explicit path is given.\n outfile = bundleOut ?? normalize(replaceExtension(join(dirname(filePath), scriptSource), \".bundle.js\"));\n\n // entryPoint is the output file because the content will be rebased to it.\n entryPoint = outfile;\n\n if (this.findMetadata({ filePath: outfile })) {\n this.log.debug(`The entry point \"${entryPoint}\" is already bundled in \"${outfile}\", skipping...`);\n node.setAttribute(\"src\", relative(dirname(filePath), outfile));\n continue;\n }\n\n const sourceScriptMetadata = this.findMetadata({ filePath: join(dirname(filePath), scriptSource) });\n if (!isScriptMetadata(sourceScriptMetadata)) {\n printFmtError(`Script metadata for the path \"${entryPoint}\" not found`, { node, filePath });\n continue;\n }\n\n // Rebase imports to be relative to the output file location.\n const clone = this.clone(sourceScriptMetadata);\n await this.rebase(clone, join(this.root, outfile));\n\n contents = await this.stringify(clone);\n }\n\n // Build the external-check predicate from the resolved patterns.\n const isExternalCheck = (string: string) => {\n return isPathMatch(string, { include: externals, ignore: externalsIgnore, root: this.root });\n };\n\n const [bundleString, bundleError] = await bundleScriptWithEsbuild.call(this, {\n contents,\n entryPoint,\n outfile,\n iife: isIife,\n isExternalCheck,\n });\n\n if (bundleError) {\n printFmtError(`Failed to bundle the entry point \"${entryPoint}\"`, bundleError, { node, filePath });\n continue;\n }\n\n // Load the bundled output back as script metadata so the build system tracks it.\n const newMetadataPath = normalize(isInlined ? filePath : outfile);\n const newScriptMetadata = await this.load(newMetadataPath, { code: bundleString, type: \"js\" });\n if (!isScriptMetadata(newScriptMetadata)) {\n printFmtError(\"Failed to load the bundled script\", { node, filePath });\n continue;\n }\n\n if (isInlined) {\n if (!scriptMetadataID) {\n printFmtError(\"Missing script metadata ID\", { node, filePath });\n continue;\n }\n\n // Replace the old inline metadata entry with the bundled version.\n metadata.scriptsMetadataList.set(scriptMetadataID, newScriptMetadata);\n newScriptMetadata.module = scriptType === \"module\";\n continue;\n }\n\n // Remove the old inline metadata entry and point the tag to the bundled file.\n if (scriptMetadataID) {\n metadata.scriptsMetadataList.delete(scriptMetadataID);\n }\n\n node.setAttribute(\"src\", relative(dirname(filePath), outfile));\n node.textContent = \"\";\n\n this.addMetadata(newScriptMetadata);\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: \"script\",\n description: `Adds the \\`${bundleAttribute}\\` attribute and its options, which bundle the script and its imports with esbuild at build time.`,\n attributes: [\n {\n name: bundleAttribute,\n description: \"Enable script bundling.\",\n valueSet: \"v\",\n },\n {\n name: bundleOutAttribute,\n description:\n \"Specify the output path for bundled scripts relative to the output directory, regardless of the HTML file's location.\" +\n \"\\nIf the script has a `src` attribute, the output path will default to `{filename}.bundle.js` next to the original file.\" +\n \"\\nIf the script has no `src` attribute, the default behavior is to keep the script inline.\",\n },\n {\n name: externalsAttribute,\n description:\n \"Glob patterns list to treat as external during bundling. (semicolon-separated)\" +\n `\\n\\nDefaults to \"${defaultExternal.join(\";\")}\".`,\n },\n {\n name: externalsExcludeAttribute,\n description:\n \"Glob patterns that exempt files from being treated as external, even if they match `externals`. (semicolon-separated)\" +\n `\\n\\nDefaults to \"${defaultExternalExclude.join(\";\")}\".`,\n },\n {\n name: iifeAttribute,\n description:\n \"Emit the bundle as an IIFE instead of ESM.\" +\n \"\\n\\nOnly changes the output format; the tag's `type` attribute is left as it is.\",\n valueSet: \"v\",\n },\n ],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const scripts = document.select(\"script\");\n\n for (const element of scripts) {\n const bundle = element.attribute(bundleAttribute);\n if (!bundle) continue;\n\n if (!isJavaScript(element)) {\n report.warn(bundle.nameRange, `\"${bundleAttribute}\" does nothing on a script that is not JavaScript`);\n continue;\n }\n\n const source = element.attribute(\"src\");\n if (!source?.value && isEmptyElement(element, document)) {\n report.error(bundle.nameRange, `\"${bundleAttribute}\" needs a \"src\" or some code in the script to bundle`);\n continue;\n }\n\n if (source) {\n checkFileExists(source, document, report);\n }\n }\n },\n };\n}\n","/** What an `@import` wraps the imported sheet in. `layer` is `\"\"` for an anonymous `layer`. */\nexport interface ImportConditions {\n layer?: string;\n supports?: string;\n media?: string;\n}\n\nexport interface ImportPrelude extends ImportConditions {\n /** The URL as written, without quotes or `url()` and with escapes resolved. */\n url: string;\n\n /** Offsets of the URL inside the params, so it can be swapped in place. */\n urlStart: number;\n urlEnd: number;\n\n /** The `url(...)` or quoted string token as written. */\n urlToken: string;\n}\n\nconst isSpace = (char: string | undefined) => char === \" \" || char === \"\\t\" || char === \"\\n\" || char === \"\\r\" || char === \"\\f\";\n\nfunction skipSpace(text: string, index: number): number {\n while (index < text.length && isSpace(text[index])) index++;\n return index;\n}\n\nfunction skipSpaceAndComments(text: string, index: number): number {\n for (;;) {\n index = skipSpace(text, index);\n if (!text.startsWith(\"/*\", index)) return index;\n\n const end = text.indexOf(\"*/\", index + 2);\n if (end === -1) return text.length;\n\n index = end + 2;\n }\n}\n\n/** Index just past the closing quote of the string starting at `index`, or `-1` when it never closes. */\nfunction skipString(text: string, index: number): number {\n const quote = text[index];\n\n for (let current = index + 1; current < text.length; current++) {\n const char = text[current];\n if (char === \"\\\\\") {\n current++;\n continue;\n }\n\n if (char === quote) return current + 1;\n if (char === \"\\n\") return -1;\n }\n\n return -1;\n}\n\n/** Index just past the `)` matching the `(` at `index`, or `-1` when it never closes. */\nfunction skipParens(text: string, index: number): number {\n let depth = 0;\n\n for (let current = index; current < text.length; current++) {\n const char = text[current];\n\n if (char === '\"' || char === \"'\") {\n const end = skipString(text, current);\n if (end === -1) return -1;\n\n current = end - 1;\n continue;\n }\n\n if (char === \"(\") depth++;\n else if (char === \")\" && --depth === 0) return current + 1;\n }\n\n return -1;\n}\n\nconst escapeRe = /\\\\(?:([\\da-f]{1,6})\\s?|(.))/gi;\n\nfunction unescapeCss(value: string): string {\n if (!value.includes(\"\\\\\")) return value;\n\n return value.replace(escapeRe, (_, hex: string | undefined, char: string) =>\n hex ? String.fromCodePoint(Number.parseInt(hex, 16)) : char\n );\n}\n\n/**\n * Parses the params of an `@import` rule: the URL followed by its `layer`, `supports()` and media conditions.\n *\n * Returns `undefined` when no URL can be found or a condition is given twice.\n */\nexport function parseImportPrelude(text: string): ImportPrelude | undefined {\n const tokenStart = skipSpaceAndComments(text, 0);\n\n let urlStart: number;\n let urlEnd: number;\n let tokenEnd: number;\n\n const first = text[tokenStart];\n\n if (first === '\"' || first === \"'\") {\n tokenEnd = skipString(text, tokenStart);\n if (tokenEnd === -1) return;\n\n urlStart = tokenStart + 1;\n urlEnd = tokenEnd - 1;\n }\n //\n else if (text.slice(tokenStart, tokenStart + 4).toLowerCase() === \"url(\") {\n const contentStart = skipSpace(text, tokenStart + 4);\n const quote = text[contentStart];\n let close: number;\n\n if (quote === '\"' || quote === \"'\") {\n const stringEnd = skipString(text, contentStart);\n if (stringEnd === -1) return;\n\n close = skipSpace(text, stringEnd);\n if (text[close] !== \")\") return;\n\n urlStart = contentStart + 1;\n urlEnd = stringEnd - 1;\n }\n //\n else {\n close = text.indexOf(\")\", contentStart);\n if (close === -1) return;\n\n urlStart = contentStart;\n urlEnd = close;\n while (urlEnd > urlStart && isSpace(text[urlEnd - 1])) urlEnd--;\n }\n\n tokenEnd = close + 1;\n }\n //\n else {\n return;\n }\n\n const prelude: ImportPrelude = {\n url: unescapeCss(text.slice(urlStart, urlEnd)),\n urlStart,\n urlEnd,\n urlToken: text.slice(tokenStart, tokenEnd),\n };\n\n let position = tokenEnd;\n\n for (;;) {\n position = skipSpaceAndComments(text, position);\n if (position >= text.length) break;\n\n const rest = text.slice(position);\n\n if (/^layer(?=\\(|\\s|$)/i.test(rest)) {\n if (prelude.layer !== undefined) return;\n\n if (rest[5] === \"(\") {\n const end = skipParens(text, position + 5);\n if (end === -1) return;\n\n prelude.layer = text.slice(position + 6, end - 1).trim();\n position = end;\n } else {\n prelude.layer = \"\";\n position += 5;\n }\n\n continue;\n }\n\n if (/^supports\\(/i.test(rest)) {\n if (prelude.supports !== undefined) return;\n\n const end = skipParens(text, position + 8);\n if (end === -1) return;\n\n prelude.supports = text.slice(position + 9, end - 1).trim();\n position = end;\n continue;\n }\n\n prelude.media = rest.trim();\n break;\n }\n\n return prelude;\n}\n\nexport function hasConditions({ layer, supports, media }: ImportConditions): boolean {\n return layer !== undefined || supports !== undefined || media !== undefined;\n}\n\n/** Prints conditions back the way an `@import` prelude takes them: `layer(name) supports(condition) media`. */\nexport function formatImportConditions({ layer, supports, media }: ImportConditions): string {\n const parts: string[] = [];\n\n if (layer !== undefined) parts.push(layer ? `layer(${layer})` : \"layer\");\n if (supports !== undefined) parts.push(`supports(${supports})`);\n if (media !== undefined) parts.push(media);\n\n return parts.join(\" \");\n}\n","import postcss from \"postcss\";\n\nimport { valueOrError } from \"../utilities/value-or-error.ts\";\n\nfunction parseCssUnsafe(css: string, options?: postcss.ProcessOptions) {\n return postcss.parse(css, options ?? {});\n}\n\n/** Parse CSS string and return the root node */\nconst parseCss = valueOrError(parseCssUnsafe);\n\nexport { parseCss };\n","import { parseCss } from \"../../../parsers/css-parser.ts\";\nimport { METADATA_TYPES, type StyleMetadata } from \"../../../types/metadata.ts\";\nimport { join } from \"../../../utilities/path.ts\";\n\nimport type { ValueOrError } from \"../../../utilities/value-or-error.ts\";\nimport type { App } from \"@staticbolt/core\";\n\nexport function styleLoader(this: App, relativePath: string, code: string): ValueOrError<StyleMetadata> {\n const absFilePath = join(this.root, relativePath);\n\n const [cssRoot, parseError] = parseCss(code, { from: absFilePath });\n if (parseError) {\n return [null, parseError];\n }\n\n const cssMetadata: StyleMetadata = {\n type: METADATA_TYPES.CSS,\n ast: cssRoot,\n filePath: relativePath,\n id: relativePath,\n directDependencies: new Set(),\n };\n\n return [cssMetadata, null];\n}\n","import postcss from \"postcss\";\n\nimport {\n formatImportConditions,\n hasConditions,\n parseImportPrelude,\n type ImportConditions,\n type ImportPrelude,\n} from \"../ast-utilities/postcss-utils/import-prelude.ts\";\nimport { styleLoader } from \"../plugins/core-plugins/style-metadata/style-loader.ts\";\nimport { METADATA_TYPES } from \"../types/metadata.ts\";\nimport { splitHtmlLink } from \"../utilities/html-links.ts\";\nimport { isStyleMetadata } from \"../utilities/metadata-utilities.ts\";\nimport { join, relative } from \"../utilities/path.ts\";\n\nimport type { App, StyleMetadata } from \"@staticbolt/core\";\nimport type { AtRule, ChildNode } from \"postcss\";\n\nexport interface StyleBundleDiagnostic {\n level: \"error\" | \"warning\";\n message: string;\n\n /** The rule the message is about, in the file it was written in. */\n node: AtRule;\n\n /** The file the rule was written in, relative to the project root. */\n filePath: string;\n}\n\n/** One stylesheet pulled into the bundle, under the conditions of every `@import` on the way to it. */\ninterface Occurrence {\n metadata: StyleMetadata;\n absolutePath: string;\n\n /** Conditions of the imports leading here, outermost first; levels without conditions are left out. */\n chain: ImportConditions[];\n\n /** Same file under the same conditions is the same occurrence. */\n key: string;\n\n /** The `@import` that pulled the file in; the entry has none. */\n importNode?: AtRule;\n\n /** Top-level nodes of the copy that ends up in the bundle, by their index in the file. Made on first use. */\n nodes?: ChildNode[];\n}\n\n/** A piece of the bundle in output order, as a position in an occurrence rather than a node, so nothing is taken before cloning. */\ntype Entry =\n | { kind: \"charset\"; occurrence: Occurrence; index: number }\n | { kind: \"layer\"; occurrence: Occurrence; index: number }\n | { kind: \"import\"; occurrence: Occurrence; index: number; prelude: ImportPrelude; chain: ImportConditions[] }\n | { kind: \"nodes\"; occurrence: Occurrence; indices: number[] };\n\n/** What becomes of an `@import`. */\ntype ImportPlan =\n | { action: \"inline\"; child: Occurrence }\n | { action: \"keep\"; prelude: ImportPrelude; chain: ImportConditions[] }\n | { action: \"drop\" }\n | { action: \"leave\" };\n\nconst externalUrlRe = /^(?:[a-z][\\d+.a-z-]*:|\\/\\/)/i;\n\n/**\n * Inlines the `@import` tree of a stylesheet in place, the way a browser would have loaded it:\n *\n * - Imported files come from the build when they are part of it, so what other plugins did to them is kept, and from disk\n * otherwise. Their `url()` references are rebased onto the bundle's final location.\n * - `layer()`, `supports()` and media conditions wrap the imported rules; nested imports nest their conditions.\n * - A file imported more than once under the same conditions is kept where it was imported last, which is where a browser's cascade\n * ends up. Cyclic imports are cut.\n * - Imports that cannot be inlined (other origins, `data:`, files that fail to resolve or load) are kept and hoisted to the top\n * with their conditions folded in, after `@charset` and any `@layer` statements that came before them.\n * - Misplaced imports (after other rules) are reported and left alone, like a browser ignores them.\n */\nexport class StyleBundler {\n readonly #app: App;\n\n /** Stylesheets outside the build, loaded from disk once and cloned per use. `undefined` marks a file that failed to load. */\n readonly #loaded = new Map<string, StyleMetadata | undefined>();\n\n constructor(app: App) {\n this.#app = app;\n }\n\n /**\n * Bundles `metadata.ast` in place.\n *\n * @param bundleAbsolutePath Where the bundle ends up, which imported `url()` references are rebased onto.\n */\n async bundle(metadata: StyleMetadata, bundleAbsolutePath: string): Promise<StyleBundleDiagnostic[]> {\n const run = new BundleRun(this.#app, this.#loaded, bundleAbsolutePath);\n return await run.bundle(metadata);\n }\n}\n\nclass BundleRun {\n readonly #app: App;\n readonly #loaded: Map<string, StyleMetadata | undefined>;\n readonly #bundleAbsolutePath: string;\n\n readonly #entries: Entry[] = [];\n readonly #occurrences: Occurrence[] = [];\n readonly #diagnostics: StyleBundleDiagnostic[] = [];\n readonly #reportedNodes = new Set<AtRule>();\n\n #charsetParams: string | undefined;\n #hasKeptImports = false;\n\n constructor(app: App, loaded: Map<string, StyleMetadata | undefined>, bundleAbsolutePath: string) {\n this.#app = app;\n this.#loaded = loaded;\n this.#bundleAbsolutePath = bundleAbsolutePath;\n }\n\n async bundle(metadata: StyleMetadata): Promise<StyleBundleDiagnostic[]> {\n const absolutePath = join(this.#app.root, metadata.filePath);\n const entry: Occurrence = { metadata, absolutePath, chain: [], key: absolutePath, nodes: metadata.ast.nodes.slice() };\n\n await this.#visit(entry, new Set([absolutePath]));\n await this.#assemble(entry);\n\n return this.#diagnostics;\n }\n\n // --- Planning: walk the import tree on the build's own ASTs and lay the bundle out as entries ---\n\n async #visit(occurrence: Occurrence, ancestors: Set<string>) {\n const nodes = occurrence.metadata.ast.nodes;\n const filePath = occurrence.metadata.id;\n\n /** Indices of consecutive nodes that stay as they are, flushed as one entry whenever something else comes between them. */\n let run: number[] = [];\n\n const flushRun = () => {\n if (run.length === 0) return;\n this.#entries.push({ kind: \"nodes\", occurrence, indices: run });\n run = [];\n };\n\n /** Only comments, `@charset`, `@layer` statements and other imports may come before an `@import`. */\n let isInPrefix = true;\n\n for (const [index, node] of nodes.entries()) {\n if (node.type === \"comment\") {\n run.push(index);\n continue;\n }\n\n const atRule = node.type === \"atrule\" ? node : undefined;\n const name = atRule?.name.toLowerCase();\n\n if (atRule && name === \"charset\") {\n if (index === 0) {\n this.#noteCharset(atRule, filePath);\n this.#entries.push({ kind: \"charset\", occurrence, index });\n } else {\n this.#warn(atRule, filePath, \"@charset must precede all other statements\");\n }\n\n continue;\n }\n\n if (atRule && name === \"layer\" && isInPrefix && !atRule.nodes) {\n if (occurrence.chain.length === 0) {\n flushRun();\n this.#entries.push({ kind: \"layer\", occurrence, index });\n } else {\n run.push(index);\n }\n\n continue;\n }\n\n if (!atRule || name !== \"import\") {\n isInPrefix = false;\n run.push(index);\n continue;\n }\n\n const plan = await this.#planImport(atRule, occurrence, ancestors, isInPrefix);\n\n switch (plan.action) {\n case \"leave\": {\n run.push(index);\n break;\n }\n\n case \"drop\": {\n break;\n }\n\n case \"keep\": {\n flushRun();\n this.#entries.push({ kind: \"import\", occurrence, index, prelude: plan.prelude, chain: plan.chain });\n this.#hasKeptImports = true;\n break;\n }\n\n case \"inline\": {\n flushRun();\n this.#occurrences.push(plan.child);\n await this.#visit(plan.child, new Set(ancestors).add(plan.child.absolutePath));\n break;\n }\n }\n }\n\n flushRun();\n }\n\n /**\n * Decides what becomes of an `@import`: inlined, kept as an import (hoisted with its conditions folded in, so the browser\n * fetches it the way it did before), dropped (a cycle) or left where it is as a regular node (not valid where it stands).\n */\n async #planImport(node: AtRule, occurrence: Occurrence, ancestors: Set<string>, isInPrefix: boolean): Promise<ImportPlan> {\n const filePath = occurrence.metadata.id;\n\n const prelude = parseImportPrelude(node.params);\n if (!prelude) {\n this.#warn(node, filePath, `Unable to find the URL in '${node.toString()}'`);\n return { action: \"leave\" };\n }\n\n if (node.nodes) {\n this.#warn(node, filePath, \"It looks like the @import statement was not ended correctly: child nodes are attached to it\");\n return { action: \"leave\" };\n }\n\n if (!isInPrefix) {\n this.#warn(node, filePath, \"@import must precede all other statements (besides @charset and empty @layer)\");\n return { action: \"leave\" };\n }\n\n const chain = hasConditions(prelude) ? [...occurrence.chain, prelude] : occurrence.chain;\n const keep: ImportPlan = { action: \"keep\", prelude, chain };\n\n if (externalUrlRe.test(prelude.url)) {\n return keep;\n }\n\n const absolutePath = this.#resolve(prelude.url, occurrence.absolutePath);\n if (!absolutePath) {\n this.#error(node, filePath, `Failed to resolve \"${prelude.url}\"`);\n return keep;\n }\n\n if (ancestors.has(absolutePath)) {\n return { action: \"drop\" };\n }\n\n const metadata = await this.#load(absolutePath);\n if (!metadata) {\n this.#error(node, filePath, `Failed to load \"${prelude.url}\" as a stylesheet`);\n return keep;\n }\n\n const key = [absolutePath, ...chain.map(level => formatImportConditions(level))].join(\"\\0\");\n\n return { action: \"inline\", child: { metadata, absolutePath, chain, key, importNode: node } };\n }\n\n #resolve(url: string, importerAbsolutePath: string): string | undefined {\n const [link] = splitHtmlLink(url);\n\n // Root-relative, as a browser would resolve it against the site root\n if (link.startsWith(\"/\")) {\n return this.#app.resolver.findFile(join(this.#app.root, link));\n }\n\n const resolved = this.#app.resolver.resolve(link, importerAbsolutePath);\n if (!resolved?.exists) return;\n\n return resolved.path;\n }\n\n async #load(absolutePath: string): Promise<StyleMetadata | undefined> {\n const relativePath = relative(this.#app.root, absolutePath);\n\n const inBuild =\n this.#app.findMetadata<StyleMetadata>({ type: METADATA_TYPES.CSS, filePath: relativePath }) ??\n this.#app.findMetadata<StyleMetadata>({ type: METADATA_TYPES.CSS, id: relativePath });\n\n if (inBuild) return inBuild;\n\n if (!this.#loaded.has(absolutePath)) {\n this.#loaded.set(absolutePath, await this.#loadFromDisk(absolutePath, relativePath));\n }\n\n return this.#loaded.get(absolutePath);\n }\n\n async #loadFromDisk(absolutePath: string, relativePath: string): Promise<StyleMetadata | undefined> {\n const content = await this.#app.read(absolutePath);\n if (content === undefined) return;\n\n // The pipeline has nothing to load from an empty file; here it is simply a sheet with no rules\n if (content.trim() === \"\") {\n return styleLoader.call(this.#app, relativePath, content)[0] ?? undefined;\n }\n\n const metadata = await this.#app.load(relativePath, { code: content });\n if (isStyleMetadata(metadata)) return metadata;\n }\n\n #noteCharset(node: AtRule, filePath: string) {\n if (this.#charsetParams === undefined) {\n this.#charsetParams = node.params;\n return;\n }\n\n if (node.params.toLowerCase() !== this.#charsetParams.toLowerCase()) {\n this.#warn(node, filePath, `Incompatible @charset statements: ${node.params} is dropped for ${this.#charsetParams}`);\n }\n }\n\n #warn(node: AtRule, filePath: string, message: string) {\n this.#report(\"warning\", node, filePath, message);\n }\n\n #error(node: AtRule, filePath: string, message: string) {\n this.#report(\"error\", node, filePath, message);\n }\n\n #report(level: StyleBundleDiagnostic[\"level\"], node: AtRule, filePath: string, message: string) {\n if (this.#reportedNodes.has(node)) return;\n this.#reportedNodes.add(node);\n this.#diagnostics.push({ level, message, node, filePath });\n }\n\n // --- Assembly: clone what is kept, rebase it, and rebuild the entry root from the entries ---\n\n async #assemble(entry: Occurrence) {\n const root = entry.metadata.ast;\n\n const lastByKey = new Map<string, Occurrence>();\n for (const occurrence of this.#occurrences) {\n lastByKey.set(occurrence.key, occurrence);\n }\n\n let charset: AtRule | undefined;\n const prefix: ChildNode[] = [];\n const body: ChildNode[] = [];\n const started = new Set<Occurrence>();\n\n for (const item of this.#entries) {\n const { occurrence } = item;\n\n if (occurrence !== entry && lastByKey.get(occurrence.key) !== occurrence) continue;\n\n const nodes = await this.#nodesOf(occurrence);\n\n switch (item.kind) {\n case \"charset\": {\n charset ??= nodes[item.index] as AtRule;\n break;\n }\n\n case \"layer\": {\n (this.#hasKeptImports ? prefix : body).push(nodes[item.index]);\n break;\n }\n\n case \"import\": {\n const node = nodes[item.index] as AtRule;\n node.params = keptImportPrelude(node.params, item.prelude, item.chain);\n prefix.push(node);\n break;\n }\n\n case \"nodes\": {\n const run = item.indices.map(index => nodes[index]);\n\n // The first piece of a file sits where its `@import` was, so it takes over the whitespace before it\n if (occurrence.importNode && !started.has(occurrence)) {\n const isBundleStart = !charset && prefix.length === 0 && body.length === 0;\n run[0].raws.before = isBundleStart ? \"\" : occurrence.importNode.raws.before || \"\\n\";\n }\n\n started.add(occurrence);\n body.push(...wrapInConditions(run, occurrence.chain));\n break;\n }\n }\n }\n\n if (charset) prefix.unshift(charset);\n\n root.removeAll();\n root.append([...prefix, ...body]);\n }\n\n async #nodesOf(occurrence: Occurrence): Promise<ChildNode[]> {\n if (occurrence.nodes) return occurrence.nodes;\n\n const clone = this.#app.clone(occurrence.metadata);\n await this.#app.rebase(clone, this.#bundleAbsolutePath);\n\n occurrence.nodes = clone.ast.nodes.slice();\n return occurrence.nodes;\n }\n}\n\n/** Nests `nodes` in `@media`, `@supports` and `@layer` rules for every level of the chain, outermost level outermost. */\nfunction wrapInConditions(nodes: ChildNode[], chain: ImportConditions[]): ChildNode[] {\n if (chain.length === 0) return nodes;\n\n const before = nodes[0].raws.before;\n nodes[0].raws.before = \"\\n\";\n\n let wrapped = nodes;\n\n for (let level = chain.length - 1; level >= 0; level--) {\n const { layer, supports, media } = chain[level];\n\n const wrappers: AtRule[] = [];\n if (layer !== undefined) wrappers.push(postcss.atRule({ name: \"layer\", params: layer }));\n if (supports !== undefined) wrappers.push(postcss.atRule({ name: \"supports\", params: `(${supports})` }));\n if (media !== undefined) wrappers.push(postcss.atRule({ name: \"media\", params: media }));\n\n for (const wrapper of wrappers) {\n wrapper.raws = { before: \"\\n\", between: \" \", after: \"\\n\" };\n wrapper.append(wrapped);\n wrapped = [wrapper];\n }\n }\n\n wrapped[0].raws.before = before;\n\n return wrapped;\n}\n\n/**\n * The prelude of an import kept in the bundle, with the conditions of the imports leading to it folded in. A single level fits in\n * one prelude; more than one nests `data:` stylesheets, each importing the next under its own conditions, outermost first.\n */\nfunction keptImportPrelude(text: string, prelude: ImportPrelude, chain: ImportConditions[]): string {\n if (chain.length === 0 || (chain.length === 1 && chain[0] === prelude)) return text;\n\n // Rebasing may have rewritten the URL since the prelude was parsed\n const urlToken = parseImportPrelude(text)?.urlToken ?? prelude.urlToken;\n\n let result = `${urlToken} ${formatImportConditions(chain.at(-1)!)}`;\n\n for (let level = chain.length - 2; level >= 0; level--) {\n // eslint-disable-next-line unicorn/prefer-uint8array-base64 -- `Uint8Array#toBase64` is not available on the Node versions supported\n const stylesheet = Buffer.from(`@import ${result};`).toString(\"base64\");\n result = `'data:text/css;base64,${stylesheet}' ${formatImportConditions(chain[level])}`;\n }\n\n return result;\n}\n","import { StyleBundler } from \"../../helpers/style-bundler.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata, isStyleMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { printFmtError } from \"../../utilities/print-formatted-error.ts\";\n\nimport type { Plugin, StyleMetadata } from \"@staticbolt/core\";\n\nexport interface HtmlBundleStyleOptions {\n /**\n * The HTML attribute name that enables bundling on a link[stylesheet] or style tag.\n *\n * @default \"bundle\"\n */\n bundleAttribute?: string;\n}\n\n/**\n * Inlines the \"@import\" tree of a stylesheet, so the tag ends up self-contained. Opt-in per tag through the \"bundle\" attribute\n * (configurable via HtmlBundleStyleOptions) on a \"<link rel=stylesheet>\" or a \"<style>\" tag.\n *\n * Bundling happens in place: a \"<style>\" tag gets the resolved CSS as its content, and a linked file is rewritten with its\n * imports inlined while \"href\" stays as it is.\n *\n * Notes:\n *\n * - Production only. In development nothing runs and the \"bundle\" attribute is left on the tag.\n * - \"<link rel=preload as=style>\" is always bundled, with or without the attribute, since a preloaded stylesheet has to carry\n * everything it needs.\n * - A linked stylesheet is bundled once even when several pages link to it; they share the same file.\n * - Imports resolve the way every other source does: relative paths, path aliases and packages, through the build's resolver.\n * - Imported files are pulled from the build (so transforms other plugins made are included) and only read from disk when they are\n * not part of it. They stay in the output as separate files, now unreferenced. Their \"url()\" references are rebased onto the\n * bundle's location.\n * - Conditions (\"layer\", \"supports()\", media) wrap the imported rules, a file imported twice under the same conditions is kept\n * where it was imported last, as in a browser, and imports from other origins are hoisted to the top.\n */\nexport function htmlBundleStylePlugin(options: HtmlBundleStyleOptions = {}): Plugin {\n const bundleAttribute = options.bundleAttribute ?? \"bundle\";\n const query = `link[rel=\"stylesheet\"][${bundleAttribute}], link[rel=\"preload\"][as=\"style\"], style[${bundleAttribute}]`;\n\n const alreadyBundledIds = new Set<string>();\n\n let bundler: StyleBundler;\n\n return {\n name: \"html-bundle-style\",\n\n setup() {\n bundler = new StyleBundler(this);\n },\n\n async transform(metadata) {\n if (!this.production) return;\n if (!isHtmlMetadata(metadata)) return;\n\n const elements = metadata.ast.querySelectorAll(query);\n\n for (const node of elements) {\n node.removeAttribute(bundleAttribute);\n\n const isLinkTag = node.tagName.toLowerCase() === \"link\";\n\n const styleMetadata: StyleMetadata | undefined = (() => {\n if (isLinkTag) {\n const href = node.getAttribute(\"href\");\n if (!href) return;\n\n const [link] = splitHtmlLink(href);\n const source = join(dirname(metadata.filePath), link);\n\n const getStyleMetadata = this.findMetadata({ filePath: source });\n if (!isStyleMetadata(getStyleMetadata)) return;\n\n return getStyleMetadata;\n }\n\n // style tag\n const metadataID = node.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!metadataID) return;\n\n return metadata.stylesMetadataList.get(metadataID);\n })();\n\n if (!styleMetadata) {\n printFmtError(`Could not find style metadata.`, { function: htmlBundleStylePlugin, node, filePath: metadata.id });\n continue;\n }\n\n if (isLinkTag) {\n if (alreadyBundledIds.has(styleMetadata.id)) {\n continue;\n }\n\n alreadyBundledIds.add(styleMetadata.id);\n }\n\n const bundleAbsolutePath = join(this.root, isLinkTag ? styleMetadata.filePath : metadata.filePath);\n\n const diagnostics = await bundler.bundle(styleMetadata, bundleAbsolutePath);\n\n for (const { level, message, node: importNode, filePath } of diagnostics) {\n printFmtError(message, { function: htmlBundleStylePlugin, node: importNode, filePath, level });\n }\n }\n },\n\n lspHtmlData() {\n const description = `Adds the \\`${bundleAttribute}\\` attribute, which inlines the stylesheet's \\`@import\\` tree at build time.`;\n const attributes = [{ name: bundleAttribute, description: \"Enable style bundling.\", valueSet: \"v\" }];\n\n return {\n version: 1.1,\n tags: [\n { name: \"link\", description, attributes },\n { name: \"style\", description, attributes },\n ],\n };\n },\n };\n}\n","import { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlEnvOnlyOptions {\n /**\n * The HTML attribute name that marks a tag as development-only.\n *\n * Tags with this attribute are removed at build time and kept (with the attribute stripped) during dev serve.\n *\n * @default \"dev-only\"\n */\n devOnlyAttribute?: string;\n\n /**\n * The HTML attribute name that marks a tag as production-only.\n *\n * Tags with this attribute are removed during dev serve and kept (with the attribute stripped) at build time.\n *\n * @default \"production-only\"\n */\n productionOnlyAttribute?: string;\n}\n\n/**\n * Removes the HTML tags that do not belong in the current environment.\n *\n * Attributes (names configurable via HtmlEnvOnlyOptions):\n *\n * - \"dev-only\": kept while serving, removed from the production build.\n * - \"production-only\": kept in the production build, removed while serving.\n *\n * Notes:\n *\n * - Works on any element, and removal takes the element's whole subtree with it.\n * - Where the tag survives, the marker attribute is stripped from the output.\n */\nexport function htmlEnvOnlyPlugin(options: HtmlEnvOnlyOptions = {}): Plugin {\n const developmentOnlyAttribute = options.devOnlyAttribute ?? \"dev-only\";\n const productionOnlyAttribute = options.productionOnlyAttribute ?? \"production-only\";\n\n return {\n name: \"html-env-only\",\n\n transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n // eslint-disable-next-line unicorn/require-css-escape\n const developmentOnlyElements = metadata.ast.querySelectorAll(`[${developmentOnlyAttribute}]`);\n for (const node of developmentOnlyElements) {\n if (this.production) node.remove();\n else node.removeAttribute(developmentOnlyAttribute);\n }\n\n // eslint-disable-next-line unicorn/require-css-escape\n const productionOnlyElements = metadata.ast.querySelectorAll(`[${productionOnlyAttribute}]`);\n for (const node of productionOnlyElements) {\n if (this.production) node.removeAttribute(productionOnlyAttribute);\n else node.remove();\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n globalAttributes: [\n {\n name: developmentOnlyAttribute,\n description: \"Keep this tag during dev serve only; it is removed at build time.\",\n valueSet: \"v\",\n },\n {\n name: productionOnlyAttribute,\n description: \"Keep this tag at build time only; it is removed during dev serve.\",\n valueSet: \"v\",\n },\n ],\n };\n },\n };\n}\n","import { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlFragmentOptions {\n /**\n * The tag name used for the fragment custom element.\n *\n * @default \"fragment\"\n */\n tagName?: string;\n}\n\n/**\n * Replaces every \"<fragment>\" element (tag name configurable via HtmlFragmentOptions) with its own content, so the wrapper leaves\n * no trace in the output. Handy for grouping markup a layout or an insert has to treat as one node.\n *\n * Notes:\n *\n * - Runs in development and production alike.\n * - The content is re-parsed from the element's inner HTML and trimmed, so surrounding whitespace is dropped.\n * - Fragments nest: the page is rescanned after each replacement, so a fragment inside another one is unwrapped as well.\n */\nexport function htmlFragmentPlugin(options: HtmlFragmentOptions = {}): Plugin {\n const tag = options.tagName ?? \"fragment\";\n\n return {\n name: \"html-fragment\",\n\n transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n // The content is re-parsed on replace, so a nested fragment ends up as a node the previous\n // query never saw. Re-query after every replacement until none is left.\n let node = metadata.ast.querySelector(tag);\n\n while (node?.parentNode) {\n node.replaceWith(node.innerHTML.trim());\n node = metadata.ast.querySelector(tag);\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: tag,\n description: \"At build time, this tag is replaced with its contents.\",\n attributes: [],\n },\n ],\n };\n },\n };\n}\n","import * as t from \"@babel/types\";\n\nimport type { ValueOrError } from \"../../utilities/value-or-error.ts\";\nimport type { BabelAst } from \"@staticbolt/core\";\n\nfunction isTopLevelIIFE(ast: BabelAst): boolean {\n const body = ast.program.body;\n\n if (body.length !== 1) {\n return false;\n }\n\n const statement = body[0];\n if (statement.type !== \"ExpressionStatement\") {\n return false;\n }\n\n const expression = statement.expression;\n if (expression.type !== \"CallExpression\") {\n return false;\n }\n\n const callee = expression.callee;\n\n return callee.type === \"ArrowFunctionExpression\" || callee.type === \"FunctionExpression\";\n}\n\n/**\n * Returns true if an export declaration is an empty re-export (`export {}`). These are typically emitted by TypeScript and carry\n * no runtime meaning.\n */\nfunction isEmptyExport(node: t.Statement): node is t.ExportNamedDeclaration {\n return (\n node.type === \"ExportNamedDeclaration\" && node.specifiers.length === 0 && node.declaration == null && node.source == null\n );\n}\n\nfunction isStaticImport(node: t.Statement): node is t.ImportDeclaration {\n return node.type === \"ImportDeclaration\";\n}\n\nfunction isExport(node: t.Statement): node is t.ExportNamedDeclaration | t.ExportDefaultDeclaration | t.ExportAllDeclaration {\n return (\n node.type === \"ExportNamedDeclaration\" || node.type === \"ExportDefaultDeclaration\" || node.type === \"ExportAllDeclaration\"\n );\n}\n\n/**\n * Wraps all statements of a Babel `File` AST in an IIFE:\n *\n * (function () { <statements> })();\n *\n * Rules:\n *\n * - Static `import` declarations → throws `IIFEWrapError`\n * - Non-empty `export` declarations → throws `IIFEWrapError`\n * - Empty `export {}` statements → silently removed\n * - Dynamic `import()` expressions inside the body → allowed (they're not declarations)\n */\nexport function wrapWithIIFE(ast: BabelAst): ValueOrError<t.File> {\n const body = ast.program.body;\n\n if (isTopLevelIIFE(ast)) {\n return [null, new Error(\"The script is already wrapped in an IIFE\")];\n }\n\n for (const node of body) {\n if (isStaticImport(node)) {\n return [null, new Error(\"Static import declarations are not allowed in IIFE-wrapped scripts\")];\n }\n\n if (isExport(node) && !isEmptyExport(node)) {\n return [null, new Error(`Export declarations are not allowed in IIFE-wrapped scripts`)];\n }\n }\n\n // Strip empty `export {}` statements, keep everything else\n const filteredBody = body.filter(node => !isEmptyExport(node));\n\n // (() => { ...filteredBody })()\n ast.program.body = [t.expressionStatement(t.callExpression(t.arrowFunctionExpression([], t.blockStatement(filteredBody)), []))];\n\n return [ast, null];\n}\n","import { isScriptType } from \"../../helpers/is-script-type.ts\";\nimport { isJavaScript } from \"../../helpers/lsp-checks.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { wrapWithIIFE } from \"./iife.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlIifeScriptOptions {\n /**\n * The attribute name that enables IIFE.\n *\n * @default \"iife\"\n */\n iifeAttribute?: string;\n}\n\n/**\n * Wraps the body of a script tag marked with \"iife\" (attribute configurable via HtmlIifeScriptOptions) in an immediately invoked\n * function expression, so its declarations stay out of the global scope.\n *\n * Notes:\n *\n * - The attribute is stripped in both modes, but the wrapping only happens in production.\n * - Inline scripts only: a tag with a \"src\" attribute is reported as an error and left alone.\n * - Meant for classic scripts. A module already has its own scope, so wrapping one buys nothing.\n */\nexport function htmlIifeScriptPlugin(options: HtmlIifeScriptOptions = {}): Plugin {\n const iifeAttribute = options.iifeAttribute ?? \"iife\";\n const query = `script[${iifeAttribute}]`;\n\n return {\n name: \"html-iife-script\",\n\n transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const scriptTags = metadata.ast.querySelectorAll(query);\n\n for (const scriptTag of scriptTags) {\n scriptTag.removeAttribute(iifeAttribute);\n\n if (!this.production) continue;\n\n const scriptType = scriptTag.getAttribute(\"type\");\n if (!isScriptType(scriptType)) {\n continue;\n }\n\n const printFmtError = PrintFormattedError.create({\n function: htmlIifeScriptPlugin,\n filePath: metadata.id,\n node: scriptTag,\n lang: \"html\",\n });\n\n const sourceAttribute = scriptTag.getAttribute(\"src\");\n if (sourceAttribute) {\n printFmtError(\"IIFE only works with inline scripts.\");\n continue;\n }\n\n if (scriptType === \"module\") {\n printFmtError(\"IIFE should only be used with global scripts. A module already has its own scope.\", {\n level: \"warning\",\n });\n }\n\n const metadataID = scriptTag.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!metadataID) {\n printFmtError(\"Missing metadata ID.\");\n continue;\n }\n\n const scriptMetadata = metadata.scriptsMetadataList.get(metadataID);\n if (!scriptMetadata) {\n printFmtError(\"Missing script metadata.\");\n continue;\n }\n\n // wrap in IIFE (Immediately Invoked Function Expression)\n const [, wrapError] = wrapWithIIFE(scriptMetadata.ast); // mutates ast\n if (wrapError) {\n printFmtError(\"Error wrapping script in IIFE\", wrapError);\n }\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: \"script\",\n description: `Adds the \\`${iifeAttribute}\\` attribute, which wraps an inline script's body in an immediately invoked function expression at build time.`,\n attributes: [\n {\n name: iifeAttribute,\n description:\n \"Enabling this will wrap the script content in an IIFE (Immediately Invoked Function Expression).\" +\n \"\\n\\nWorks only with inline global scripts.\",\n valueSet: \"v\",\n },\n ],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const scripts = document.select(\"script\");\n\n for (const element of scripts) {\n const iife = element.attribute(iifeAttribute);\n if (!iife) continue;\n\n if (!isJavaScript(element)) {\n report.warn(iife.nameRange, `\"${iifeAttribute}\" does nothing on a script that is not JavaScript`);\n continue;\n }\n\n if (element.attribute(\"type\")?.value === \"module\") {\n report.warn(iife.nameRange, `\"${iifeAttribute}\" is for global scripts, a module already has its own scope`);\n }\n }\n },\n };\n}\n","import { isScriptType } from \"../../helpers/is-script-type.ts\";\nimport { checkFileExists, isEmptyElement, isJavaScript } from \"../../helpers/lsp-checks.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { type ScriptMetadata } from \"../../types/metadata.ts\";\nimport { splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata, isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { downloadContent, hashContent, isURL } from \"../../utilities/utilities.ts\";\n\nimport type { ValueOrError } from \"../../utilities/value-or-error.ts\";\nimport type { App, Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlInlineScriptOptions {\n /**\n * The attribute name that enables inlining.\n *\n * @default \"inline\"\n */\n inlineAttribute?: string;\n}\n\n/**\n * Replaces a script tag marked with \"inline\" (attribute configurable via HtmlInlineScriptOptions) with the code it points at, so\n * the page ships one request fewer. The \"src\" attribute is dropped and the code becomes the tag's content.\n *\n * The source can be a local file or a remote URL; a URL is downloaded at build time, cached per page directory and URL, and kept\n * out of the output.\n *\n * Notes:\n *\n * - The attribute is stripped in both modes, but the inlining only happens in production.\n * - The tag must have a \"src\" and no content of its own; anything else is reported as an error and left alone.\n * - A local file has to be part of the build already, otherwise its metadata is not found and nothing is inlined.\n * - The inlined copy is rebased onto the HTML file, so its relative imports keep resolving, and the original file stays in the\n * output unless something removes it.\n * - The tag's \"type\" decides whether the inlined code is treated as a module, not the original file.\n */\nexport function htmlInlineScriptPlugin(options: HtmlInlineScriptOptions = {}): Plugin {\n const inlineAttribute = options.inlineAttribute ?? \"inline\";\n const query = `script[${inlineAttribute}]`;\n\n return {\n name: \"html-inline-script\",\n\n async transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const scriptTags = metadata.ast.querySelectorAll(query);\n\n for (const scriptTag of scriptTags) {\n scriptTag.removeAttribute(inlineAttribute);\n\n if (!this.production) {\n continue;\n }\n\n const scriptType = scriptTag.getAttribute(\"type\");\n if (!isScriptType(scriptType)) {\n continue;\n }\n\n const printFmtError = PrintFormattedError.create({\n function: htmlInlineScriptPlugin,\n filePath: metadata.id,\n node: scriptTag,\n lang: \"html\",\n });\n\n const sourceAttribute = scriptTag.getAttribute(\"src\");\n if (!sourceAttribute) {\n printFmtError(\"Missing src attribute\");\n continue;\n }\n\n const scriptContent = scriptTag.textContent.trim();\n if (scriptContent) {\n printFmtError(\"Script tag is not empty\");\n continue;\n }\n\n const [scriptMetadata, loadError] = await loadScriptMetadata.call(this, sourceAttribute, metadata.filePath);\n if (loadError) {\n printFmtError(\"Error loading script\", loadError);\n continue;\n }\n\n // clone and rebase\n const scriptMetadataClone = this.clone(scriptMetadata);\n await this.rebase(scriptMetadataClone, join(this.root, metadata.filePath));\n\n const isModule = scriptTag.getAttribute(\"type\") === \"module\";\n scriptMetadataClone.module = isModule;\n\n // add script tag ast\n const metadataID = hashContent(await this.stringify(scriptMetadataClone));\n scriptTag.setAttribute(CUSTOM_ATTRIBUTES.MetadataID, metadataID);\n metadata.scriptsMetadataList.set(metadataID, scriptMetadataClone);\n\n scriptTag.removeAttribute(\"src\");\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: \"script\",\n description: `Adds the \\`${inlineAttribute}\\` attribute, which inlines the script the \\`src\\` points at into the page at build time.`,\n attributes: [\n {\n name: inlineAttribute,\n description:\n \"Enable inlining external scripts directly into the HTML at build time. It supports local files, remote URLs.\" +\n \"\\n\\nThe tag must have a `src` and no content of its own. Inlining only happens in production builds.\",\n valueSet: \"v\",\n },\n ],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const scripts = document.select(\"script\");\n\n for (const element of scripts) {\n const inline = element.attribute(inlineAttribute);\n if (!inline) continue;\n\n if (!isJavaScript(element)) {\n report.warn(inline.nameRange, `\"${inlineAttribute}\" does nothing on a script that is not JavaScript`);\n continue;\n }\n\n const source = element.attribute(\"src\");\n if (!source?.value) {\n report.error(inline.nameRange, `\"${inlineAttribute}\" needs a \"src\" pointing at the script to inline`);\n continue;\n }\n\n if (!isEmptyElement(element, document)) {\n report.error(inline.nameRange, `\"${inlineAttribute}\" needs an empty script tag, the content comes from \"src\"`);\n }\n\n checkFileExists(source, document, report);\n }\n },\n };\n}\n\nasync function loadScriptMetadata(this: App, source: string, filePath: string): Promise<ValueOrError<ScriptMetadata>> {\n // Download and load as a script metadata\n if (isURL(source)) {\n const urlHash = await crypto.subtle.digest(\"SHA-1\", new TextEncoder().encode(source));\n const hashHex = Array.from(new Uint8Array(urlHash), b => b.toString(16).padStart(2, \"0\")).join(\"\");\n const downloadedFilePath = join(dirname(filePath), `downloaded/${hashHex}.js`);\n\n // Already downloaded and loaded\n for (const metadata of this.metadataList) {\n if (isScriptMetadata(metadata) && metadata.filePath === downloadedFilePath) {\n return [metadata, null];\n }\n }\n\n const [downloaded, downloadError] = await downloadContent(source);\n if (downloadError) {\n return [null, downloadError];\n }\n\n const scriptMetadata = await this.load(downloadedFilePath, { code: downloaded, type: \"js\" });\n if (!isScriptMetadata(scriptMetadata)) {\n return [null, new Error(\"Downloaded file is not a script\")];\n }\n\n // No need to transform or resolve a downloaded script\n this.addMetadata(scriptMetadata);\n this.emitExclude.add(scriptMetadata);\n\n return [scriptMetadata, null];\n }\n\n const [link] = splitHtmlLink(source);\n const sourcePath = join(dirname(filePath), link);\n\n // Already loaded and found\n const metadata = this.findMetadata({ filePath: sourcePath });\n if (isScriptMetadata(metadata)) {\n return [metadata, null];\n }\n\n return [null, new Error(\"Failed to find script metadata\")];\n}\n","import { checkFileExists } from \"../../helpers/lsp-checks.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { type StyleMetadata } from \"../../types/metadata.ts\";\nimport { splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata, isStyleMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { downloadContent, hashContent, isURL } from \"../../utilities/utilities.ts\";\n\nimport type { ValueOrError } from \"../../utilities/value-or-error.ts\";\nimport type { App, Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlInlineStyleOptions {\n /**\n * The attribute name that enables inlining.\n *\n * @default \"inline\"\n */\n inlineAttribute?: string;\n}\n\n/**\n * Turns a \"<link rel=stylesheet>\" marked with \"inline\" (attribute configurable via HtmlInlineStyleOptions) into a \"<style>\" tag\n * holding the stylesheet itself, so the page ships one request fewer.\n *\n * The \"href\" can point at a local file or a remote URL; a URL is downloaded at build time, cached per page directory and URL, and\n * kept out of the output.\n *\n * Notes:\n *\n * - The attribute is stripped in both modes, but the inlining only happens in production.\n * - The link's remaining attributes are copied onto the \"<style>\" tag; \"href\" and \"rel\" are dropped.\n * - A local file has to be part of the build already, otherwise its metadata is not found and nothing is inlined.\n * - The inlined copy is rebased onto the HTML file, so relative \"url()\" and \"@import\" paths keep resolving, and the original file\n * stays in the output unless something removes it.\n */\nexport function htmlInlineStylePlugin(options: HtmlInlineStyleOptions = {}): Plugin {\n const inlineAttribute = options.inlineAttribute ?? \"inline\";\n const query = `link[rel=\"stylesheet\"][${inlineAttribute}]`;\n\n return {\n name: \"html-inline-style\",\n\n async transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const linkTags = metadata.ast.querySelectorAll(query);\n\n for (const linkTag of linkTags) {\n linkTag.removeAttribute(inlineAttribute);\n\n if (!this.production) {\n continue;\n }\n\n const printFmtError = PrintFormattedError.create({\n function: htmlInlineStylePlugin,\n filePath: metadata.id,\n lang: \"html\",\n });\n\n const sourceAttribute = linkTag.getAttribute(\"href\");\n if (!sourceAttribute) {\n printFmtError(\"Missing href attribute\", { node: linkTag });\n continue;\n }\n\n const [styleMetadata, loadError] = await loadStyleMetadata.call(this, sourceAttribute, metadata.filePath);\n if (loadError) {\n printFmtError(\"Error loading style\", loadError, { node: linkTag });\n continue;\n }\n\n // clone and rebase\n const styleMetadataClone = this.clone(styleMetadata);\n await this.rebase(styleMetadataClone, join(this.root, metadata.filePath));\n\n // add script tag ast\n const metadataID = hashContent(await this.stringify(styleMetadataClone));\n linkTag.setAttribute(CUSTOM_ATTRIBUTES.MetadataID, metadataID);\n metadata.stylesMetadataList.set(metadataID, styleMetadataClone);\n\n linkTag.removeAttribute(\"href\");\n linkTag.removeAttribute(\"rel\");\n\n const attributesString = Object.entries(linkTag.attrs)\n .map(([name, value]) => `${name}=\"${value}\"`)\n .join(\" \");\n\n linkTag.replaceWith(`<style ${attributesString}></style>`);\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: \"link\",\n description: `Adds the \\`${inlineAttribute}\\` attribute, which turns a stylesheet link into a \\`<style>\\` tag holding the stylesheet itself at build time.`,\n attributes: [\n {\n name: inlineAttribute,\n description:\n \"Enable inlining external stylesheets directly into the HTML at build time. It supports both local files and remote URLs.\",\n valueSet: \"v\",\n },\n ],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const links = document.select(\"link\");\n\n for (const element of links) {\n const inline = element.attribute(inlineAttribute);\n if (!inline) continue;\n\n if (element.attribute(\"rel\")?.value !== \"stylesheet\") {\n report.warn(inline.nameRange, `\"${inlineAttribute}\" only works on a link with rel=\"stylesheet\"`);\n continue;\n }\n\n const source = element.attribute(\"href\");\n if (!source?.value) {\n report.error(inline.nameRange, `\"${inlineAttribute}\" needs an \"href\" pointing at the stylesheet to inline`);\n continue;\n }\n\n checkFileExists(source, document, report);\n }\n },\n };\n}\n\nasync function loadStyleMetadata(this: App, source: string, filePath: string): Promise<ValueOrError<StyleMetadata>> {\n // Download and load as a style metadata\n if (isURL(source)) {\n const urlHash = await crypto.subtle.digest(\"SHA-1\", new TextEncoder().encode(source));\n const hashHex = Array.from(new Uint8Array(urlHash), b => b.toString(16).padStart(2, \"0\")).join(\"\");\n const downloadedFilePath = join(dirname(filePath), `downloaded/${hashHex}.css`);\n\n // Already downloaded and loaded\n for (const metadata of this.metadataList) {\n if (isStyleMetadata(metadata) && metadata.filePath === downloadedFilePath) {\n return [metadata, null];\n }\n }\n\n const [downloaded, downloadError] = await downloadContent(source);\n if (downloadError) {\n return [null, downloadError];\n }\n\n const styleMetadata = await this.load(downloadedFilePath, { code: downloaded, type: \"css\" });\n if (!isStyleMetadata(styleMetadata)) {\n return [null, new Error(\"Downloaded file is not CSS\")];\n }\n\n this.addMetadata(styleMetadata);\n this.emitExclude.add(styleMetadata);\n\n return [styleMetadata, null];\n }\n\n // Load locally\n const [link] = splitHtmlLink(source);\n const sourcePath = join(dirname(filePath), link);\n\n const metadata = this.findMetadata({ filePath: sourcePath });\n if (!isStyleMetadata(metadata)) {\n return [null, new Error(\"Failed to find style metadata\")];\n }\n\n return [metadata, null];\n}\n","import { checkFileExists } from \"../../helpers/lsp-checks.ts\";\nimport { type SvgMetadata } from \"../../types/metadata.ts\";\nimport { splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata, isSvgMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { downloadContent, isURL } from \"../../utilities/utilities.ts\";\n\nimport type { ValueOrError } from \"../../utilities/value-or-error.ts\";\nimport type { App, Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlInlineSvgOptions {\n /**\n * The attribute name that enables inlining.\n *\n * @default \"inline\"\n */\n inlineAttribute?: string;\n}\n\n/**\n * Replaces an \"<svg inline src=...>\" placeholder (attribute configurable via HtmlInlineSvgOptions) with the actual SVG element\n * from the file, so it can be styled and scripted like any other markup.\n *\n * The \"src\" can point at a local file or a remote URL; a URL is downloaded at build time, cached per page directory and URL, and\n * kept out of the output.\n *\n * Notes:\n *\n * - Runs in development and production alike.\n * - Every attribute left on the placeholder is copied onto the inlined element and overrides what the file declares, \"viewBox\" and\n * \"fill\" included.\n * - A local file has to be part of the build already, otherwise its metadata is not found and the placeholder is left as it is.\n * - Only the \"<svg>\" element of the file is taken; anything around it in the file is dropped.\n */\nexport function HtmlInlineSvgPlugin(options: HtmlInlineSvgOptions = {}): Plugin {\n const inlineAttribute = options.inlineAttribute ?? \"inline\";\n const query = `svg[${inlineAttribute}]`;\n const sourceAttribute = \"src\";\n\n const printFmtError = PrintFormattedError.create({ function: HtmlInlineSvgPlugin });\n\n const svgMetadataList: SvgMetadata[] = [];\n\n return {\n name: \"html-inline-svg\",\n\n setup() {\n this.pluginData.svgMetadataList ??= svgMetadataList;\n },\n\n async transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const filePath = metadata.filePath;\n const elements = metadata.ast.querySelectorAll(query);\n\n for (const node of elements) {\n const source = node.getAttribute(sourceAttribute);\n if (!source) {\n printFmtError(`The svg element is missing the \"${inlineAttribute}\" attribute`, { node, filePath });\n continue;\n }\n\n const [svgMetadata, loadError] = await loadSvgMetadata.call(this, source, filePath);\n if (loadError) {\n printFmtError(\"Error loading svg metadata\", loadError, { node, filePath });\n continue;\n }\n\n const svgMetadataClone = this.clone(svgMetadata);\n\n const svgElement = svgMetadataClone.ast.querySelector(\"svg\");\n if (!svgElement) {\n printFmtError(`Failed to parse svg element`, { node, filePath });\n continue;\n }\n\n node.removeAttribute(inlineAttribute);\n node.removeAttribute(sourceAttribute);\n\n for (const [attribute, value] of Object.entries(node.attrs)) {\n svgElement.setAttribute(attribute, value);\n }\n\n node.replaceWith(svgElement);\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: \"svg\",\n description: `Adds the \\`${inlineAttribute}\\` attribute, which replaces the placeholder with the SVG element from the file the \\`src\\` points at, at build time.`,\n attributes: [\n {\n name: inlineAttribute,\n description:\n \"Enable inlining external SVGs directly into the HTML at build time. It supports both local files and remote URLs.\",\n valueSet: \"v\",\n },\n ],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const svgs = document.select(\"svg\");\n\n for (const element of svgs) {\n const inline = element.attribute(inlineAttribute);\n if (!inline) continue;\n\n const source = element.attribute(sourceAttribute);\n if (!source?.value) {\n report.error(inline.nameRange, `\"${inlineAttribute}\" needs a \"${sourceAttribute}\" pointing at the SVG to inline`);\n continue;\n }\n\n checkFileExists(source, document, report);\n }\n },\n };\n}\n\nasync function loadSvgMetadata(this: App, source: string, filePath: string): Promise<ValueOrError<SvgMetadata>> {\n // Download and load as a svg metadata\n if (isURL(source)) {\n const urlHash = await crypto.subtle.digest(\"SHA-1\", new TextEncoder().encode(source));\n const hashHex = Array.from(new Uint8Array(urlHash), b => b.toString(16).padStart(2, \"0\")).join(\"\");\n const downloadedFilePath = join(dirname(filePath), `downloaded/${hashHex}.svg`);\n\n // Already downloaded and loaded\n for (const metadata of this.metadataList) {\n if (isSvgMetadata(metadata) && metadata.filePath === downloadedFilePath) {\n return [metadata, null];\n }\n }\n\n const [downloaded, downloadError] = await downloadContent(source);\n if (downloadError) {\n return [null, downloadError];\n }\n\n const svgMetadata = await this.load(downloadedFilePath, { code: downloaded, type: \"svg\" });\n if (!isSvgMetadata(svgMetadata)) {\n return [null, new Error(\"Downloaded file is not SVG\")];\n }\n\n // No need to transform or resolve a downloaded svg\n\n this.addMetadata(svgMetadata);\n this.emitExclude.add(svgMetadata);\n\n return [svgMetadata, null];\n }\n\n // Load locally\n const [link] = splitHtmlLink(source);\n const sourcePath = join(dirname(filePath), link);\n\n const metadata = this.findMetadata({ filePath: sourcePath });\n if (!isSvgMetadata(metadata)) {\n return [null, new Error(\"Failed to find SVG metadata\")];\n }\n\n return [metadata, null];\n}\n","import { DependencyTracker } from \"../../helpers/dependency-tracker.ts\";\nimport { checkFileExists } from \"../../helpers/lsp-checks.ts\";\nimport { splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join, relative } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { safeReadFileSync } from \"../../utilities/read-file.ts\";\nimport { escapeHtml } from \"../../utilities/utilities.ts\";\n\nimport type { MetadataSource, Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlInlineTextOptions {\n /**\n * The tag name for the inline text.\n *\n * @default \"inline-text\"\n */\n tagName?: string;\n\n /**\n * The attribute name on the custom tag that holds the path to the external text file.\n *\n * @default \"src\"\n */\n sourceAttribute?: string;\n\n /**\n * The attribute name of the attribute that disables HTML escaping.\n *\n * @default \"no-escape\"\n */\n noEscapeAttribute?: string;\n}\n\n/**\n * Replaces an \"<inline-text src=...>\" tag with the contents of the file it points at (tag and attribute names configurable via\n * HtmlInlineTextOptions). The text is HTML-escaped unless the tag carries \"no-escape\", which inserts it as markup.\n *\n * Notes:\n *\n * - Runs in development and production alike.\n * - The file is read straight from disk, so it is not a build source and no other plugin transforms it.\n * - Contents are cached per path for the whole build, escaping included: when two tags point at the same file, the first one\n * decides whether both end up escaped.\n * - The cache is dropped when the file changes, and pages that inlined it are recompiled, so the dev server stays in sync.\n */\nexport function htmlInlineTextPlugin(options: HtmlInlineTextOptions = {}): Plugin {\n const tag = options.tagName ?? \"inline-text\";\n const sourceAttribute = options.sourceAttribute ?? \"src\";\n const noEscapeAttribute = options.noEscapeAttribute ?? \"no-escape\";\n\n const cache = new Map<string, string>();\n\n const dependencies = new DependencyTracker();\n\n /** Suffix on the tag's source while it travels through resolution, keeping it apart from real build sources. */\n const MARKER = \"?html-inline-text\";\n\n return {\n name: \"html-inline-text\",\n\n sourcesProvider(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const result: MetadataSource[] = [];\n\n const inlineTags = metadata.ast.querySelectorAll(tag);\n\n for (const inlineTag of inlineTags) {\n const source = inlineTag.getAttribute(sourceAttribute);\n if (!source) continue;\n\n // Marks the source as text to paste, so `resolveSource` can tell it apart from a build source\n const [link] = splitHtmlLink(source);\n inlineTag.setAttribute(sourceAttribute, link + MARKER);\n\n result.push({\n get source() {\n return inlineTag.getAttribute(sourceAttribute) ?? \"\";\n },\n set source(newValue) {\n inlineTag.setAttribute(sourceAttribute, newValue);\n },\n });\n }\n\n return result;\n },\n\n resolveSource(source, filePath) {\n const [, suffix] = splitHtmlLink(source);\n if (suffix !== MARKER) return;\n\n const resolved = this.resolver.resolve(source, filePath);\n if (!resolved?.exists) return;\n\n this.watcher?.add(relative(this.root, resolved.path));\n\n return { source: relative(join(this.root, dirname(filePath)), resolved.path), dependencyID: undefined };\n },\n\n transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const inlineTags = metadata.ast.querySelectorAll(tag);\n const currentSources = new Set<string>();\n\n for (const inlineTag of inlineTags) {\n const printFmtError = PrintFormattedError.create({\n function: htmlInlineTextPlugin,\n filePath: metadata.id,\n lang: \"html\",\n node: inlineTag,\n });\n\n const source = inlineTag.getAttribute(sourceAttribute);\n if (!source) {\n printFmtError(`Missing \"${sourceAttribute}\" attribute`);\n continue;\n }\n\n const [link] = splitHtmlLink(source);\n const sourceRelative = join(dirname(metadata.filePath), link);\n\n let contents: string;\n\n // From cache\n if (cache.has(sourceRelative)) {\n contents = cache.get(sourceRelative)!;\n }\n // Read and cache\n else {\n const [readContents, readError] = safeReadFileSync(sourceRelative, \"utf8\");\n if (readError) {\n printFmtError(readError);\n continue;\n }\n\n const isNoEscape = inlineTag.hasAttribute(noEscapeAttribute);\n contents = isNoEscape ? readContents : escapeHtml(readContents);\n cache.set(sourceRelative, contents);\n }\n\n currentSources.add(sourceRelative);\n\n inlineTag.replaceWith(contents);\n }\n\n dependencies.update(metadata.id, currentSources);\n },\n\n onFileEvent(event, id) {\n if (event === \"unlink\" || event === \"change\") {\n cache.delete(id);\n }\n\n if (event === \"unlink\") {\n dependencies.delete(id);\n }\n },\n\n resolveCompileList(compileSet, event) {\n if (event !== \"change\") return;\n\n for (const id of Array.from(compileSet)) {\n const importers = dependencies.getImporters(id);\n\n for (const importer of importers) {\n compileSet.add(importer);\n }\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: tag,\n description: \"At build time, this tag is replaced with the contents of the external text file.\",\n attributes: [\n {\n name: sourceAttribute,\n description: \"The path to the external text file.\",\n },\n {\n name: noEscapeAttribute,\n description: \"Disable HTML escaping.\",\n valueSet: \"v\",\n },\n ],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const inlineTags = document.select(tag);\n\n for (const element of inlineTags) {\n const source = element.attribute(sourceAttribute);\n\n if (!source?.value) {\n report.error(element, `<${tag}> needs a \"${sourceAttribute}\" pointing at a text file`);\n continue;\n }\n\n checkFileExists(source, document, report);\n }\n },\n };\n}\n","import { isDynamic, isEmptyElement } from \"../../helpers/lsp-checks.ts\";\nimport { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\n/** Where `insertAdjacentHTML` can put content. */\nconst POSITIONS = new Set<string>([\"beforebegin\", \"afterbegin\", \"beforeend\", \"afterend\"]);\n\nexport interface HtmlInsertOptions {\n /**\n * The HTML tag name of the custom insert element.\n *\n * @default \"insert\"\n */\n tagName?: string;\n\n /**\n * The attribute name that points to the target element via a CSS selector.\n *\n * @default \"selector\"\n */\n selectorAttribute?: string;\n\n /**\n * The attribute name that enables the replacement of the target element.\n *\n * @default \"replace\"\n */\n replaceAttribute?: string;\n\n /**\n * The attribute name that determines the position of the inserted element.\n *\n * @default \"where\"\n */\n whereAttribute?: string;\n}\n\n/**\n * Moves the content of an \"<insert>\" tag into any element on the same page, addressed by a CSS selector, then removes the tag\n * itself (names configurable via HtmlInsertOptions).\n *\n * Attributes:\n *\n * - \"selector\": the CSS selector of the target element.\n * - \"where\": where the content lands, one of \"beforebegin\", \"afterbegin\", \"beforeend\" (the default) or \"afterend\".\n * - \"replace\": swap the target element for the content instead of inserting into it.\n *\n * Notes:\n *\n * - Runs in development and production alike, and only searches the page the tag lives on.\n * - A tag whose target is not on the page yet is left untouched, since layouts and pages are assembled in several passes. Any tag\n * still unresolved at the end of the build is reported and stays in the output.\n * - An \"<insert>\" with no content or no selector is reported and left alone.\n */\nexport function htmlInsertPlugin(options: HtmlInsertOptions = {}): Plugin {\n const tag = options.tagName ?? \"insert\";\n const selectorAttribute = options.selectorAttribute ?? \"selector\";\n const replaceAttribute = options.replaceAttribute ?? \"replace\";\n const whereAttribute = options.whereAttribute ?? \"where\";\n\n const printFmtError = PrintFormattedError.create({\n function: htmlInsertPlugin,\n lang: \"html\",\n });\n\n return {\n name: \"html-insert\",\n\n transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const filePath = metadata.filePath;\n const elements = metadata.ast.querySelectorAll(tag);\n\n for (const node of elements) {\n const tag = node.tagName.toLowerCase();\n\n const content = node.innerHTML;\n if (!content) {\n printFmtError(`The tag <${tag}> is empty`, { node, filePath });\n continue;\n }\n\n const selector = node.getAttribute(selectorAttribute);\n if (!selector) {\n printFmtError(`The tag <${tag}> is missing the \"${selectorAttribute}\" attribute`, {\n node,\n filePath,\n });\n continue;\n }\n\n const targetElement = metadata.ast.querySelector(selector);\n if (!targetElement) {\n // ignore for now, this plugin might be called for layout when the page is not fully loaded\n continue;\n }\n\n if (node.hasAttribute(replaceAttribute)) {\n targetElement.replaceWith(content);\n } else {\n const where = (node.getAttribute(whereAttribute) || \"beforeend\") as InsertPosition;\n targetElement.insertAdjacentHTML(where, content);\n }\n\n node.remove();\n }\n },\n\n postTransform() {\n for (const metadata of this.metadataList) {\n if (!isHtmlMetadata(metadata)) continue;\n\n const elements = metadata.ast.querySelectorAll(tag);\n\n for (const node of elements) {\n printFmtError(`Could not find target element.`, { node, filePath: metadata.id });\n }\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: tag,\n description:\n \"At build time, inject HTML content into any target element on the page using a CSS selector at build time.\",\n attributes: [\n {\n name: selectorAttribute,\n description: \"The CSS selector of the target element.\",\n },\n {\n name: replaceAttribute,\n description: \"Replace the target element with the contents of the custom insert element.\",\n valueSet: \"v\",\n },\n {\n name: whereAttribute,\n description: \"The position of the inserted element.\",\n values: [...POSITIONS].map(position => ({ name: position })),\n },\n ],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const inserts = document.select(tag);\n\n for (const element of inserts) {\n const selector = element.attribute(selectorAttribute);\n const where = element.attribute(whereAttribute);\n\n if (isEmptyElement(element, document)) {\n report.error(element, `<${tag}> has nothing to insert`);\n }\n\n if (!selector?.value) {\n report.error(element, `<${tag}> needs a \"${selectorAttribute}\" with the CSS selector of the target element`);\n }\n\n if (where?.value && !isDynamic(where.value) && !POSITIONS.has(where.value)) {\n report.error(where, `\"${whereAttribute}\" must be one of ${[...POSITIONS].join(\", \")}`);\n }\n\n if (where && element.has(replaceAttribute)) {\n report.warn(where.nameRange, `\"${whereAttribute}\" does nothing with \"${replaceAttribute}\"`);\n }\n }\n },\n };\n}\n","import type { EmbeddedRegion } from \"../../types/lsp.ts\";\nimport type { ValueOrError } from \"../../utilities/value-or-error.ts\";\n\n/** `{{ expression }}`, or `\\{{ … }}` to have it left alone. The expression is captured without its surrounding whitespace. */\nconst placeholderRe = /(\\\\)?{{(\\s*)([\\s\\S]*?)\\s*}}/g;\n\n/** Where the expressions of the unescaped placeholders sit in `html`. */\nexport function findPlaceholders(html: string): EmbeddedRegion[] {\n const regions: EmbeddedRegion[] = [];\n\n for (const match of html.matchAll(placeholderRe)) {\n const [, escape, leadingSpace, expression] = match;\n if (escape) continue;\n\n // Past the `{{` and the whitespace after it\n const start = match.index + 2 + leadingSpace.length;\n const extent = { start: match.index, end: match.index + match[0].length };\n\n regions.push({ start, end: start + expression.length, extent });\n }\n\n return regions;\n}\n\n/** `{{ JavaScript expression }}` */\nexport function fillLayoutPlaceholders(html: string, placeholders: Record<string, unknown>): ValueOrError<string> {\n const errors: Error[] = [];\n\n const result = html.replace(placeholderRe, (match: string, escape: string, _leadingSpace: string, content: string) => {\n if (escape === \"\\\\\") {\n return match.slice(1);\n }\n\n const [expression, executeError] = executeExpression(content, placeholders);\n if (executeError) {\n errors.push(executeError);\n return \"\";\n }\n\n return expression;\n });\n\n // join errors\n if (errors.length > 0) {\n const combinedMessage = [\n \"Failed to fill placeholders\",\n ...errors.map((error, index) => ` [${index + 1}] ${error.message}`),\n ].join(\"\\n\");\n\n return [null, new AggregateError(errors, combinedMessage)];\n }\n\n return [result, null];\n}\n\ntype FunctionType = (data: Record<string, unknown>) => unknown;\nconst functionCache = new Map<string, FunctionType>();\n\nfunction executeExpression(expressionString: string, data: Record<string, unknown>): ValueOrError<string> {\n try {\n let function_ = functionCache.get(expressionString);\n if (!function_) {\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n function_ = new Function(\"$data\", `return ${expressionString}`) as FunctionType;\n functionCache.set(expressionString, function_);\n }\n\n const output = function_(data);\n\n if (output === undefined) {\n return [null, new Error(`Expression found in the placeholder {{ ${expressionString} }} returned undefined`)];\n }\n\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n const asString = String(output);\n\n if (asString === \"[object Object]\") {\n return [null, new Error(`Expression found in the placeholder {{ ${expressionString} }} returned an object`)];\n }\n\n return [asString, null];\n } catch (error) {\n return [null, new Error(`Failed to execute expression: ${expressionString}\\n ${(error as Error).message}`)];\n }\n}\n","import { NodeType } from \"@staticbolt/node-html-parser\";\n\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\n\nimport type { HTMLElement } from \"../../types/common.ts\";\nimport type { HtmlMetadata, MarkdownMetadata } from \"../../types/metadata.ts\";\nimport type { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport type { LayoutNames } from \"./options.ts\";\n\n/** The plugin's error printer. */\ntype PrintError = PrintFormattedError[\"print\"];\n\n/** Turns every `add-attr-x` and `remove-attr-x` of a layout into adding or removing `x`, by the value each holds. */\nexport function applyConditionalAttributes(layout: HtmlMetadata, names: LayoutNames): void {\n const addPrefix = `${names.addAttribute}-`;\n const removePrefix = `${names.removeAttribute}-`;\n const elements = layout.ast.querySelectorAll(\"*\");\n\n for (const element of elements) {\n if (!element.attributes) continue;\n\n for (const [name, value] of Object.entries(element.attributes)) {\n if (name.startsWith(addPrefix)) {\n element.removeAttribute(name);\n\n if (isSwitchedOn(value)) {\n element.setAttribute(name.slice(addPrefix.length), \"\");\n }\n\n continue;\n }\n\n if (!name.startsWith(removePrefix)) continue;\n\n element.removeAttribute(name);\n\n if (isSwitchedOn(value)) {\n element.removeAttribute(name.slice(removePrefix.length));\n }\n }\n }\n}\n\n/**\n * Drops from a layout instance the scripts, styles and stylesheet links the page already has from an earlier instance, so a\n * layout used twice emits each once. A tag marked always-include is kept, and the mark removed.\n */\nexport function dropRepeatedAssets(page: HtmlMetadata, layout: HtmlMetadata, alwaysInclude: string): void {\n const scriptsAndStyles = layout.ast.querySelectorAll(\"script,style\");\n\n for (const scriptOrStyle of scriptsAndStyles) {\n const id = scriptOrStyle.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!id) continue;\n\n if (scriptOrStyle.hasAttribute(alwaysInclude)) {\n scriptOrStyle.removeAttribute(alwaysInclude);\n continue;\n }\n\n const list = scriptOrStyle.tagName === \"SCRIPT\" ? \"scriptsMetadataList\" : \"stylesMetadataList\";\n if (!page[list].has(id)) continue;\n\n layout[list].delete(id);\n scriptOrStyle.remove();\n }\n\n const scriptsAndLinks = layout.ast.querySelectorAll('script[src], link[rel=\"stylesheet\"]');\n\n for (const scriptOrLink of scriptsAndLinks) {\n if (scriptOrLink.hasAttribute(alwaysInclude)) {\n scriptOrLink.removeAttribute(alwaysInclude);\n continue;\n }\n\n const isScript = scriptOrLink.tagName === \"SCRIPT\";\n const attribute = isScript ? \"src\" : \"href\";\n const selector = isScript ? \"script[src]\" : 'link[rel=\"stylesheet\"]';\n const layoutSource = join(dirname(layout.filePath), scriptOrLink.attributes[attribute]);\n\n const isOnPage = page.ast.querySelectorAll(selector).some(element => {\n const pageSource = join(dirname(page.filePath), element.attributes[attribute]);\n\n return pageSource === layoutSource;\n });\n\n if (isOnPage) {\n scriptOrLink.remove();\n }\n }\n}\n\n/**\n * Puts the tag's children into the layout's slots, by the `slot` attribute they name or into the unnamed slots, then unwraps\n * every slot. A slot keeps its own content as the fallback: the first fill replaces it, later ones append.\n */\nexport function fillSlots(tag: HTMLElement, layout: HtmlMetadata, layoutPath: string, printError: PrintError): void {\n const filledSlots = new Set<HTMLElement>();\n\n const fillSlot = (slot: HTMLElement, html: string) => {\n if (!filledSlots.has(slot)) {\n filledSlots.add(slot);\n slot.innerHTML = \"\";\n }\n\n slot.insertAdjacentHTML(\"beforeend\", html);\n };\n\n const children = tag.querySelectorAll(\":scope > *\");\n\n for (const element of children) {\n if (element.nodeType !== NodeType.ELEMENT_NODE) continue;\n\n if (!element.hasAttribute(\"slot\")) {\n const defaultSlots = layout.ast.querySelectorAll(\"slot:not([name])\");\n if (defaultSlots.length === 0) {\n printError(\"No default slot in layout file:\", layoutPath, { node: element });\n continue;\n }\n\n for (const defaultSlot of defaultSlots) {\n fillSlot(defaultSlot, element.outerHTML);\n }\n\n continue;\n }\n\n const slotName = element.getAttribute(\"slot\");\n if (!slotName) continue;\n\n // eslint-disable-next-line unicorn/require-css-escape\n const namedSlots = layout.ast.querySelectorAll(`slot[name=\"${slotName}\"]`);\n if (namedSlots.length === 0) {\n printError(`No slots with name \"${slotName}\" in layout file:`, layoutPath, { node: element });\n continue;\n }\n\n element.removeAttribute(\"slot\");\n\n for (const namedSlot of namedSlots) {\n fillSlot(namedSlot, element.outerHTML);\n }\n }\n\n for (const slot of layout.ast.querySelectorAll(\"slot\")) {\n slot.replaceWith(slot.innerHTML.trim());\n }\n}\n\n/**\n * Has a markdown page render inside the layout tag its front matter names: the naming key becomes the source attribute and the\n * other keys the tag's data.\n */\nexport function wrapMarkdownInLayout(metadata: MarkdownMetadata, names: LayoutNames): void {\n const tag = Object.keys(metadata.ast.frontmatter).find(key => names.tags.includes(key));\n if (!tag) return;\n\n let attributes = \"\";\n\n for (const [key, value] of Object.entries(metadata.ast.frontmatter)) {\n attributes += `${key === tag ? names.source : key}=\"${value}\" `;\n }\n\n const openTag = `<${tag} ${attributes}>`;\n const closeTag = `</${tag}>`;\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const render = metadata.ast.render;\n\n metadata.ast.render = async () => {\n const html = await render();\n\n return openTag + html + closeTag;\n };\n}\n\n/** Whether a conditional attribute's value, after the placeholders are filled, switches the attribute on. */\nfunction isSwitchedOn(value: string): boolean {\n const trimmed = value.trim();\n\n return trimmed !== \"\" && trimmed !== \"false\";\n}\n\n/** The tag's attributes other than the source, as the key a rendered instance is cached under. */\nexport function instanceKey(tag: HTMLElement, names: LayoutNames): string {\n let key = \"\";\n\n for (const [attribute, value] of Object.entries(tag.attributes)) {\n if (attribute === names.source) continue;\n\n key += `${attribute}=${value}`;\n }\n\n return key;\n}\n","import { basename } from \"../../utilities/path.ts\";\n\nexport interface HtmlLayoutOptions {\n /**\n * Tag names registered as valid HTML elements. Each name is also the required file suffix — e.g. `\"layout\"` means files must\n * end in `.layout.html`, `\"part\"` means `.part.html`.\n *\n * @default [\"layout\", \"part\"]\n */\n tags?: string[];\n\n /**\n * Attribute name used to point to the layout or part file.\n *\n * @default \"src\"\n */\n layoutSourceAttribute?: string;\n\n /**\n * Attribute name used to point to an external JSON file whose properties are merged into `$data`. Inline attributes take\n * priority over file keys.\n *\n * @default \"dataSource\"\n */\n dataSourceAttribute?: string;\n\n /**\n * Attribute name used to pass an inline JSON string as data. The value is parsed and merged into `$data` alongside any inline\n * attributes and any keys loaded via `dataSource`. Inline attributes take priority over `dataJson` keys; `dataJson` keys take\n * priority over `dataSource` keys.\n *\n * @default \"dataJson\"\n */\n dataJsonAttribute?: string;\n\n /**\n * Attribute name that opts a `<script>`, `<style>`, or `<link rel=\"stylesheet\">` tag out of deduplication. By default,\n * duplicate scripts and styles are removed when a layout or part is used more than once on the same page. Marking a tag with\n * this boolean attribute forces it to be emitted once per instance.\n *\n * @default \"always-include\"\n */\n alwaysIncludeAttribute?: string;\n\n /**\n * Prefix for conditionally adding boolean attributes. Append the target attribute name as a suffix — `add-attr-open`,\n * `add-attr-disabled`, etc. The value is a JS expression evaluated after placeholder resolution; if it is non-empty and not\n * `\"false\"`, the named attribute is added to the element. Multiple `add-attr-*` attributes can appear on the same element.\n *\n * ```html\n * <details add-attr-open=\"{{ $data.open }}\">…</details>\n * ```\n *\n * @default \"add-attr\"\n */\n addAttributeAttribute?: string;\n\n /**\n * Prefix for conditionally removing boolean attributes. Append the target attribute name as a suffix — `remove-attr-disabled`,\n * `remove-attr-hidden`, etc. The value is a JS expression evaluated after placeholder resolution; if it is non-empty and not\n * `\"false\"`, the named attribute is removed from the element. Multiple `remove-attr-*` attributes can appear on the same\n * element.\n *\n * ```html\n * <button disabled remove-attr-disabled=\"{{ $data.enabled }}\">…</button>\n * ```\n *\n * @default \"remove-attr\"\n */\n removeAttributeAttribute?: string;\n}\n\n/** The names the plugin works with, every option filled in. */\nexport interface LayoutNames {\n /** The tags that inline a file, and the suffixes of the files they inline. */\n tags: string[];\n\n /** The attribute holding the path of the file to inline. */\n source: string;\n\n /** The attribute holding the path of a JSON file with data. */\n dataSource: string;\n\n /** The attribute holding inline JSON data. */\n dataJson: string;\n\n /** The attribute that keeps a script or style for every instance of a layout. */\n alwaysInclude: string;\n\n /** The prefix of the attributes that add a boolean attribute. */\n addAttribute: string;\n\n /** The prefix of the attributes that remove a boolean attribute. */\n removeAttribute: string;\n}\n\n/** The options with their defaults filled in. */\nexport function resolveLayoutNames(options: HtmlLayoutOptions): LayoutNames {\n return {\n tags: options.tags ?? [\"layout\", \"part\"],\n source: options.layoutSourceAttribute ?? \"src\",\n dataSource: options.dataSourceAttribute ?? \"dataSource\",\n dataJson: options.dataJsonAttribute ?? \"dataJson\",\n alwaysInclude: options.alwaysIncludeAttribute ?? \"always-include\",\n addAttribute: options.addAttributeAttribute ?? \"add-attr\",\n removeAttribute: options.removeAttributeAttribute ?? \"remove-attr\",\n };\n}\n\n/** Whether a path is a file the tags inline: one named after a tag, `main.layout.html` say. */\nexport function isLayoutFile(file: string, names: LayoutNames): boolean {\n const fileName = basename(file);\n return names.tags.some(tag => fileName.endsWith(`.${tag}.html`));\n}\n\n/** Whether an attribute adds or removes a boolean attribute. */\nexport function isConditionalAttribute(name: string, names: LayoutNames): boolean {\n return name.startsWith(`${names.addAttribute}-`) || name.startsWith(`${names.removeAttribute}-`);\n}\n","import { checkFileExists, checkJsonObject, isDynamic } from \"../../helpers/lsp-checks.ts\";\nimport { findPlaceholders } from \"./fill-placeholders.ts\";\nimport { isConditionalAttribute, isLayoutFile } from \"./options.ts\";\n\nimport type { LayoutNames } from \"./options.ts\";\nimport type {\n AttributeInfo,\n DocumentInfo,\n ElementInfo,\n EmbeddedLanguage,\n HTMLDataV1,\n IAttributeData,\n ITagData,\n Plugin,\n ProblemReporter,\n} from \"@staticbolt/core\";\n\n/** The tags and attributes the plugin adds to HTML, for completion and hover. */\nexport function htmlData(names: LayoutNames): HTMLDataV1 {\n const layoutAttributes: IAttributeData[] = [\n { name: names.source, description: \"The path to the layout to use.\" },\n { name: names.dataSource, description: \"The path for a JSON file containing data for the layout.\" },\n { name: names.dataJson, description: \"The layout data in JSON format.\" },\n ];\n\n const alwaysInclude: IAttributeData = {\n name: names.alwaysInclude,\n description:\n \"When using a layout more than once on the same page. Always include this script/style/link[rel='stylesheet'] even if it is already present.\",\n valueSet: \"v\",\n };\n\n const alwaysIncludeDescription =\n `Adds the \\`${names.alwaysInclude}\\` attribute, which gives this tag one copy per layout instance` +\n \" instead of the single copy a layout used more than once on the same page emits.\";\n\n const tags: ITagData[] = [\n { name: \"script\", description: alwaysIncludeDescription, attributes: [alwaysInclude] },\n { name: \"link\", description: alwaysIncludeDescription, attributes: [alwaysInclude] },\n { name: \"style\", description: alwaysIncludeDescription, attributes: [alwaysInclude] },\n ];\n\n for (const tag of names.tags) {\n tags.push({ name: tag, description: `This tag allows inlining a \\`${tag}\\` file.`, attributes: layoutAttributes });\n }\n\n return {\n version: 1.1,\n tags,\n globalAttributes: [\n {\n name: names.addAttribute,\n description:\n \"Inside a layout file only.\" +\n \" Prefix for conditionally adding boolean attributes.\" +\n \" Append the target attribute name as a suffix — `add-attr-open`, `add-attr-disabled`, etc.\" +\n \" The value is a JS expression evaluated after placeholder resolution;\" +\n ' if it is non-empty and not `\"false\"`, the named attribute is added to the element.' +\n \" Multiple `add-attr-*` attributes can appear on the same element.\",\n },\n {\n name: names.removeAttribute,\n description:\n \"Inside a layout file only.\" +\n \" Prefix for conditionally removing boolean attributes.\" +\n \" Append the target attribute name as a suffix — `remove-attr-open`, `remove-attr-disabled`, etc.\" +\n \" The value is a JS expression evaluated after placeholder resolution;\" +\n ' if it is non-empty and not `\"false\"`, the named attribute is removed from the element.' +\n \" Multiple `remove-attr-*` attributes can appear on the same element.\",\n },\n ],\n };\n}\n\n/** The placeholders of layout files, as JavaScript that sees `$data`. */\nexport function embeddedLanguages(names: LayoutNames): EmbeddedLanguage[] {\n return [\n {\n name: \"placeholders\",\n filter: file => isLayoutFile(file, names),\n findRegions: document => findPlaceholders(document.text),\n prelude: \"declare const $data: Record<string, any>;\",\n },\n ];\n}\n\n/** Checks the layout tags of a document, and that the conditional attributes sit in a layout file. */\nexport function validate(names: LayoutNames): NonNullable<Plugin[\"lspValidate\"]> {\n return (document, report) => {\n const layoutTags = document.select(...names.tags);\n\n for (const element of layoutTags) {\n checkLayoutTag(element, document, report, names);\n }\n\n if (isLayoutFile(document.file, names)) {\n return;\n }\n\n // A markdown file may be rendered inside a layout, where the conditional attributes do work\n if (document.file.endsWith(\".md\")) {\n return;\n }\n\n // Conditional attributes only mean something where placeholders are filled\n for (const element of document.elements) {\n for (const attribute of element.attributes) {\n if (!isConditionalAttribute(attribute.name, names)) continue;\n\n report.warn(attribute.nameRange, `\"${attribute.name}\" only works inside a layout file`);\n }\n }\n };\n}\n\n/** A layout tag points at a file named after it, and its data attributes point at a JSON file and hold a JSON object. */\nfunction checkLayoutTag(element: ElementInfo, document: DocumentInfo, report: ProblemReporter, names: LayoutNames): void {\n const source = element.attribute(names.source);\n const dataSource = element.attribute(names.dataSource);\n const dataJson = element.attribute(names.dataJson);\n\n if (!source?.value) {\n report.error(element, `<${element.name}> needs a \"${names.source}\" pointing at a .${element.name}.html file`);\n }\n\n if (source) {\n checkFileExists(source, document, report);\n checkFileSuffix(source, report);\n }\n\n if (dataSource) {\n checkFileExists(dataSource, document, report);\n }\n\n if (dataJson) {\n checkJsonObject(dataJson, report);\n }\n}\n\n/** A tag inlines files named after it, so `<part>` takes a `.part.html` file. */\nfunction checkFileSuffix(source: AttributeInfo, report: ProblemReporter): void {\n if (!source.value) return;\n if (isDynamic(source.value)) return;\n\n const suffix = `.${source.element.name}.html`;\n if (source.value.endsWith(suffix)) return;\n\n report.warn(source, `<${source.element.name}> takes a file ending in \"${suffix}\"`);\n}\n","import { METADATA_TYPES, type HtmlMetadata, type MetadataBase, type TextAssetMetadata } from \"../../types/metadata.ts\";\nimport { isHtmlMetadata, isMarkdownMetadata, isTextAssetMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { basename, dirname, join } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { readJsonFile } from \"../../utilities/read-json-file.ts\";\nimport { mergeMaps } from \"../../utilities/utilities.ts\";\nimport { fillLayoutPlaceholders } from \"./fill-placeholders.ts\";\nimport { applyConditionalAttributes, dropRepeatedAssets, fillSlots, instanceKey, wrapMarkdownInLayout } from \"./inline-layout.ts\";\nimport { embeddedLanguages, htmlData, validate } from \"./lsp.ts\";\nimport { isLayoutFile, resolveLayoutNames } from \"./options.ts\";\n\nimport type { HtmlLayoutOptions } from \"./options.ts\";\nimport type { MetadataSource, Plugin } from \"@staticbolt/core\";\n\nexport type { HtmlLayoutOptions } from \"./options.ts\";\n\ninterface HtmlLayoutMetadata extends HtmlMetadata {\n hash: string;\n}\n\n/**\n * Composes pages out of reusable \"<layout>\" and \"<part>\" files (tag names configurable via HtmlLayoutOptions). The tag is\n * replaced by the file it points at, the tag's children are distributed into the file's \"<slot>\" elements, and the scripts and\n * styles the file declares are merged into the page.\n *\n * Attributes on the tag:\n *\n * - \"src\": the file to inline. Its name must end with \".<tag>.html\", so \"<part>\" loads \"*.part.html\".\n * - \"dataSource\" and \"dataJson\": data for the file's placeholders, as a path to a JSON file and as an inline JSON string.\n * - Anything else on the tag is data as well.\n *\n * Inside the file, \"{{ expression }}\" is evaluated as JavaScript with the data exposed as \"$data\" (a leading backslash escapes a\n * placeholder, and an expression returning undefined or an object is an error), while \"add-attr-<name>\" and \"remove-attr-<name>\"\n * toggle a boolean attribute when their value is non-empty and not \"false\".\n *\n * Notes:\n *\n * - Data precedence, lowest first: the \"dataSource\" file, then \"dataJson\", then the tag's own attributes.\n * - Layouts nest, and a page is rescanned after each expansion, so a layout can pull in further layouts and parts.\n * - Markdown pages take their layout from front matter: a \"layout\" or \"part\" key names the file, the other keys are data.\n * - Using the same layout twice on one page emits its scripts, styles and stylesheet links once; \"always-include\" opts a tag out of\n * that and gives it one copy per instance.\n * - Layout files never reach the output on their own, and editing one recompiles every page and layout that pulls it in.\n * - In production an instance is rendered once per file and attribute set, then cloned for the identical ones.\n */\nexport function htmlLayoutPlugin(options: HtmlLayoutOptions = {}): Plugin {\n const names = resolveLayoutNames(options);\n const layoutTags = names.tags;\n const sourceAttribute = names.source;\n const dataSourceAttribute = names.dataSource;\n const dataJsonAttribute = names.dataJson;\n const alwaysIncludeAttribute = names.alwaysInclude;\n const query = layoutTags.join(\",\");\n\n const printFmtError = PrintFormattedError.create({ function: htmlLayoutPlugin });\n\n const htmlLayoutMetadataCache: HtmlLayoutMetadata[] = [];\n\n /**\n * @key dataSource path\n * @value contents\n */\n const dataSourceCache = new Map<string, Record<string, unknown>>();\n\n function isLayoutPath(path: string): boolean {\n return isLayoutFile(path, names);\n }\n\n return {\n name: \"html-layout\",\n\n load(content, relativePath, { type }) {\n if (type && !layoutTags.includes(type)) return;\n\n if (!isLayoutPath(relativePath)) return;\n\n const textAssetMetadata: TextAssetMetadata = {\n type: METADATA_TYPES.TextAsset,\n filePath: relativePath,\n id: relativePath,\n code: content,\n directDependencies: new Set(),\n };\n\n this.emitExclude.add(textAssetMetadata);\n\n return textAssetMetadata;\n },\n\n sourcesProvider(metadata) {\n const sources: MetadataSource[] = [];\n\n if (isHtmlMetadata(metadata)) {\n const elements = metadata.ast.querySelectorAll(query);\n\n for (const node of elements) {\n const source = node.getAttribute(sourceAttribute);\n if (source) {\n sources.push({\n get source() {\n return source;\n },\n set source(newValue) {\n node.setAttribute(sourceAttribute, newValue);\n },\n });\n }\n\n const dataSource = node.getAttribute(dataSourceAttribute);\n if (dataSource) {\n sources.push({\n get source() {\n return dataSource;\n },\n set source(newValue) {\n node.setAttribute(dataSourceAttribute, newValue);\n },\n });\n }\n }\n }\n\n if (isMarkdownMetadata(metadata)) {\n for (const [key, source] of Object.entries(metadata.ast.frontmatter)) {\n if (!source) continue;\n\n if (layoutTags.includes(key) || key === dataSourceAttribute) {\n sources.push({\n get source() {\n return source;\n },\n set source(newValue) {\n metadata.ast.frontmatter[key] = newValue;\n },\n });\n }\n }\n }\n\n return sources;\n },\n\n resolveCompileList(compileSet, event, id) {\n if (event !== \"change\") return;\n\n // Update the dataSource cache and add relaying layouts to the compile list\n if (dataSourceCache.has(id)) {\n const [newJson, metadataError] = readJsonFile<Record<string, unknown>>(join(this.root, id));\n if (metadataError) {\n printFmtError(metadataError, { filePath: id });\n return;\n }\n\n dataSourceCache.set(id, newJson);\n\n for (const metadata of this.metadataList) {\n if (isTextAssetMetadata(metadata) && isLayoutPath(metadata.id) && metadata.directDependencies.has(id)) {\n compileSet.add(metadata.id);\n }\n }\n }\n\n for (const id of Array.from(compileSet)) {\n if (!isLayoutPath(id)) continue;\n\n const queue = [id];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n\n for (const metadata of this.metadataList) {\n if (!(metadata.directDependencies.has(current) && !compileSet.has(metadata.id))) {\n continue;\n }\n\n compileSet.add(metadata.id);\n\n // only keep climbing if it's also a layout\n if (isLayoutPath(metadata.id)) {\n queue.push(metadata.id);\n }\n }\n }\n }\n },\n\n async transform(metadata) {\n if (isHtmlMetadata(metadata)) {\n let node = metadata.ast.querySelector(query);\n\n const skip = () => {\n if (!node) return;\n node.replaceWith(node.innerHTML);\n node = metadata.ast.querySelector(query);\n };\n\n while (node) {\n const tag = node.tagName.toLowerCase();\n\n const source = node.getAttribute(sourceAttribute);\n if (!source) {\n printFmtError(`The tag <${tag}> is missing the attribute \"${sourceAttribute}\"`, {\n node,\n filePath: metadata.id,\n });\n skip();\n continue;\n }\n\n const layoutRelativePath = join(dirname(metadata.filePath), source);\n\n const layoutAssetMetadata = this.findMetadata<TextAssetMetadata>({ id: layoutRelativePath });\n if (!isTextAssetMetadata(layoutAssetMetadata)) {\n printFmtError(`Failed to load layout metadata`, { node, filePath: metadata.id });\n skip();\n continue;\n }\n\n if (!basename(layoutRelativePath).endsWith(`.${tag}.html`)) {\n printFmtError(`Usage of the tag <${tag}> is incorrect. The layout file name does not end with \"${tag}.html\"`, {\n node,\n filePath: metadata.id,\n level: \"warning\",\n });\n }\n\n // --- Read data source ---\n const fillData: Record<string, unknown> = {};\n\n const dataSourcePath = node.getAttribute(dataSourceAttribute);\n if (dataSourcePath) {\n const dataSourceRelativePath = join(dirname(metadata.filePath), dataSourcePath);\n layoutAssetMetadata.directDependencies.add(dataSourceRelativePath);\n\n // From cache\n if (dataSourceCache.has(dataSourceRelativePath)) {\n Object.assign(fillData, dataSourceCache.get(dataSourceRelativePath));\n }\n // From file\n else {\n const [dataSource, fillError] = readJsonFile<Record<string, unknown>>(join(this.root, dataSourceRelativePath));\n if (fillError) {\n printFmtError(fillError, { node, filePath: metadata.id });\n skip();\n continue;\n }\n\n dataSourceCache.set(dataSourceRelativePath, dataSource);\n Object.assign(fillData, dataSource);\n }\n }\n\n const dataJson = node.getAttribute(dataJsonAttribute);\n if (dataJson) {\n try {\n Object.assign(fillData, JSON.parse(dataJson));\n } catch (error) {\n printFmtError(`Failed to parse JSON data`, error as Error, { node, filePath: metadata.id });\n skip();\n continue;\n }\n }\n\n Object.assign(fillData, node.attributes);\n\n const [layoutCode, fillError] = fillLayoutPlaceholders(layoutAssetMetadata.code, fillData);\n if (fillError) {\n printFmtError(fillError, { node, filePath: metadata.id });\n skip();\n continue;\n }\n\n let layoutHtmlMetadata: HtmlLayoutMetadata | undefined;\n\n const hash = instanceKey(node, names);\n\n // Check cache only in production\n if (this.production) {\n const cachedMetadata = htmlLayoutMetadataCache.find(\n metadata => metadata.id === layoutRelativePath && metadata.hash === hash\n );\n\n if (cachedMetadata) {\n layoutHtmlMetadata = this.clone(cachedMetadata);\n }\n }\n\n // Create new\n if (!layoutHtmlMetadata) {\n // Code string to metadata.\n const layoutMetadata = await this.load(layoutRelativePath, { code: layoutCode, type: \"html\" });\n if (!isHtmlLayoutMetadata(layoutMetadata)) {\n printFmtError(`Failed to parse <${tag}> code`, { node, filePath: metadata.id });\n skip();\n continue;\n }\n\n const metadataList = await this.resolveAndLoad(layoutMetadata);\n\n // Merge except for the layout metadata (first one)\n this.addMetadata(metadataList.slice(1));\n\n // Only transform discovered metadata list until this point in time\n await this.transformAndSync(metadataList);\n\n applyConditionalAttributes(layoutMetadata, names);\n\n // Cache only in production\n if (this.production) {\n layoutMetadata.hash = hash;\n htmlLayoutMetadataCache.push(layoutMetadata);\n layoutHtmlMetadata = this.clone(layoutMetadata);\n }\n // In development use the original metadata\n else {\n layoutHtmlMetadata = layoutMetadata;\n }\n }\n\n if (!isHtmlLayoutMetadata(layoutHtmlMetadata)) {\n printFmtError(`Failed to parse <${tag}> code`, { node, filePath: metadata.id });\n skip();\n continue;\n }\n\n dropRepeatedAssets(metadata, layoutHtmlMetadata, alwaysIncludeAttribute);\n\n // The page inlining the layout should have same direct dependencies\n for (const dependency of layoutHtmlMetadata.directDependencies) {\n metadata.directDependencies.add(dependency);\n }\n\n await this.rebase(layoutHtmlMetadata, join(this.root, metadata.filePath));\n\n fillSlots(node, layoutHtmlMetadata, layoutRelativePath, printFmtError);\n\n // Copy script and style from layout metadata to where the layout tag is inlined.\n mergeMaps(metadata.scriptsMetadataList, layoutHtmlMetadata.scriptsMetadataList);\n mergeMaps(metadata.stylesMetadataList, layoutHtmlMetadata.stylesMetadataList);\n\n node.replaceWith(layoutHtmlMetadata.ast.root);\n node = metadata.ast.querySelector(query);\n }\n\n return;\n }\n\n if (isMarkdownMetadata(metadata)) {\n wrapMarkdownInLayout(metadata, names);\n }\n },\n\n lspHtmlData() {\n return htmlData(names);\n },\n\n lspEmbeddedLanguages() {\n return embeddedLanguages(names);\n },\n\n lspValidate: validate(names),\n };\n}\n\nfunction isHtmlLayoutMetadata(metadata: MetadataBase | undefined): metadata is HtmlLayoutMetadata {\n return isHtmlMetadata(metadata);\n}\n","import { DependencyTracker } from \"../../helpers/dependency-tracker.ts\";\nimport { checkFileExists, isEmptyElement } from \"../../helpers/lsp-checks.ts\";\nimport { splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata, isMarkdownMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\n\nimport type { MetadataSource, Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlMarkdownOptions {\n /**\n * The attribute that when present on a tag will render the content as markdown.\n *\n * @default \"markdown\"\n */\n markdownAttribute?: string;\n\n /**\n * The tag name of the element that can reference a markdown file.\n *\n * @default \"markdown\"\n */\n tag?: string;\n\n /**\n * The attribute that when present on a tag will render the content as markdown.\n *\n * @default \"src\"\n */\n sourceAttribute?: string;\n}\n\n/**\n * Renders markdown inside HTML pages, from a file or from the element's own text (names configurable via HtmlMarkdownOptions).\n *\n * - An element carrying the \"markdown\" attribute has its text rendered and replaced by the resulting HTML, and loses the attribute.\n * - A \"<markdown src=...>\" tag is replaced by the rendered contents of the file it points at.\n *\n * Notes:\n *\n * - Runs in development and production alike.\n * - The rendered HTML goes through the normal pipeline (resolve, load, transform), so its own tags are processed like the rest of\n * the page and a referenced file's links are rebased onto the page that renders it.\n * - Editing a referenced markdown file recompiles the pages that render it.\n */\nexport function htmlMarkdownPlugin(options: HtmlMarkdownOptions = {}): Plugin {\n const mdAttribute = options.markdownAttribute ?? \"markdown\";\n const markdownTag = options.tag ?? \"markdown\";\n const sourceAttribute = options.sourceAttribute ?? \"src\";\n\n const dependencies = new DependencyTracker();\n\n const printFmtError = PrintFormattedError.create({ function: htmlMarkdownPlugin });\n\n return {\n name: \"html-markdown\",\n\n sourcesProvider(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const result: MetadataSource[] = [];\n\n const markdowns = metadata.ast.querySelectorAll(markdownTag);\n for (const node of markdowns) {\n const source = node.getAttribute(sourceAttribute);\n if (!source) continue;\n\n result.push({\n get source() {\n return source;\n },\n set source(newValue) {\n node.setAttribute(sourceAttribute, newValue);\n },\n });\n }\n\n return result;\n },\n\n async transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n // Normal HTML tag with `markdown` attribute\n // eslint-disable-next-line unicorn/require-css-escape\n const elements = metadata.ast.querySelectorAll(`[${mdAttribute}]`);\n for (const node of elements) {\n node.removeAttribute(mdAttribute);\n\n const code = node.rawText;\n if (!code) {\n printFmtError(`The element \"${node.tagName}\" with the markdown attribute \"${mdAttribute}\" is empty`, {\n node,\n filePath: metadata.id,\n });\n continue;\n }\n\n const markdownMetadata = await this.load(metadata.filePath, { code, type: \"md\" });\n if (!isMarkdownMetadata(markdownMetadata)) {\n printFmtError(\"Invalid markdown file:\", metadata.filePath, { node, filePath: metadata.id });\n continue;\n }\n\n const asHtmlString = await markdownMetadata.ast.render();\n\n const htmlMetadata = await this.load(metadata.filePath, { code: asHtmlString, type: \"html\" });\n if (!isHtmlMetadata(htmlMetadata)) {\n printFmtError(\"Invalid HTML file:\", metadata.filePath, { node, filePath: metadata.id });\n continue;\n }\n\n const metadataList = await this.resolveAndLoad(htmlMetadata);\n this.addMetadata(metadataList.slice(1));\n await this.transformAndSync(metadataList);\n\n node.set_content(htmlMetadata.ast.children);\n }\n\n const currentSources = new Set<string>();\n\n // Custom `markdown` tag that can reference a markdown file\n const markdowns = metadata.ast.querySelectorAll(markdownTag);\n for (const node of markdowns) {\n const source = node.getAttribute(sourceAttribute);\n if (!source) {\n printFmtError(`The tag <${markdownTag}> is missing the attribute \"${sourceAttribute}\"`, {\n node,\n filePath: metadata.id,\n });\n continue;\n }\n\n const [link] = splitHtmlLink(source);\n\n const sourceRelative = join(dirname(metadata.filePath), link);\n\n const markdownMetadata = await this.load(sourceRelative, { type: \"md\" });\n if (!isMarkdownMetadata(markdownMetadata)) {\n printFmtError(\"Invalid markdown file:\", sourceRelative, { node, filePath: metadata.id });\n continue;\n }\n\n currentSources.add(sourceRelative);\n\n const asHtmlString = await markdownMetadata.ast.render();\n\n const htmlMetadata = await this.load(sourceRelative, { code: asHtmlString, type: \"html\" });\n if (!isHtmlMetadata(htmlMetadata)) {\n printFmtError(\"Invalid HTML file:\", sourceRelative, { node, filePath: metadata.id });\n continue;\n }\n\n const metadataList = await this.resolveAndLoad(htmlMetadata);\n this.addMetadata(metadataList.slice(1));\n await this.transformAndSync(metadataList);\n await this.rebase(htmlMetadata, join(this.root, metadata.filePath));\n\n node.replaceWith(...htmlMetadata.ast.children);\n }\n\n dependencies.update(metadata.id, currentSources);\n },\n\n onFileEvent(event, id) {\n if (event === \"unlink\") {\n dependencies.delete(id);\n }\n },\n\n resolveCompileList(compileSet, event) {\n if (event !== \"change\") return;\n\n for (const id of Array.from(compileSet)) {\n const importers = dependencies.getImporters(id);\n\n for (const importer of importers) {\n compileSet.add(importer);\n }\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n globalAttributes: [{ name: mdAttribute, description: \"Render the contents of this element as markdown.\", valueSet: \"v\" }],\n tags: [\n {\n name: markdownTag,\n description: \"This tag lets you render Markdown files inside HTML.\",\n attributes: [{ name: sourceAttribute, description: \"The path to the external markdown file.\" }],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const markdowns = document.select(markdownTag);\n\n for (const element of markdowns) {\n const source = element.attribute(sourceAttribute);\n\n if (!source?.value) {\n report.error(element, `<${markdownTag}> needs a \"${sourceAttribute}\" pointing at a markdown file`);\n continue;\n }\n\n checkFileExists(source, document, report);\n }\n\n for (const element of document.elements) {\n const markdown = element.attribute(mdAttribute);\n if (!markdown) continue;\n if (!isEmptyElement(element, document)) continue;\n\n report.warn(markdown.nameRange, `There is no markdown in this <${element.name}> to render`);\n }\n },\n };\n}\n","import { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\nimport type { HTMLElement, Node } from \"@staticbolt/node-html-parser\";\n\ninterface StyleEntry {\n node: Node;\n metadataID: string;\n attrKey: string;\n}\n\n/**\n * Merges consecutive \"<style>\" tags in the \"<head>\" into a single tag, cutting the number of style blocks a page ships.\n *\n * Notes:\n *\n * - Production only, and only inside \"<head>\"; styles anywhere else are left alone.\n * - A run is only merged when the tags carry identical attributes, and a \"<link rel=stylesheet>\" between them breaks the run, so\n * the cascade order never changes.\n * - The merged rules are appended to the first tag of the run and the others are removed.\n */\nexport function htmlMergeStylesPlugin(): Plugin {\n function getAttributeKey(element: HTMLElement): string {\n const attributes = { ...element.attributes };\n delete attributes[CUSTOM_ATTRIBUTES.MetadataID];\n\n return Object.entries(attributes)\n .toSorted(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => `${k}=${v}`)\n .join(\"|\");\n }\n\n return {\n name: \"html-merge-styles\",\n\n postTransform() {\n if (!this.production) return;\n\n for (const metadata of this.metadataList) {\n if (!isHtmlMetadata(metadata)) continue;\n\n // Only merge styles in the head tag\n const head = metadata.ast.querySelector(\"head\");\n if (!head) continue;\n\n const headElements = head.querySelectorAll(\"style, link[rel=stylesheet]\");\n\n let currentGroup: StyleEntry[] = [];\n\n const flushGroup = () => {\n if (currentGroup.length >= 2) {\n const [first, ...rest] = currentGroup;\n const firstAst = metadata.stylesMetadataList.get(first.metadataID)!.ast;\n\n for (const { node, metadataID } of rest) {\n const styleMetadata = metadata.stylesMetadataList.get(metadataID);\n if (!styleMetadata) continue;\n\n // Merge AST nodes into the first root\n styleMetadata.ast.each(node => {\n node.parent = undefined;\n firstAst.append(node);\n });\n\n metadata.stylesMetadataList.delete(metadataID);\n node.remove();\n }\n }\n\n currentGroup = [];\n };\n\n for (const element of headElements) {\n // A stylesheet link breaks the consecutive chain — flush and reset\n if (element.tagName.toLowerCase() === \"link\") {\n flushGroup();\n continue;\n }\n\n const metadataID = element.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!metadataID) continue;\n\n const styleMetadata = metadata.stylesMetadataList.get(metadataID);\n if (!styleMetadata) continue;\n\n const attributeKey = getAttributeKey(element);\n\n // If the group is empty or attr signature matches, continue the group\n // Otherwise flush the current group and start a new one\n if (currentGroup.length > 0 && currentGroup[0].attrKey !== attributeKey) {\n flushGroup();\n }\n\n currentGroup.push({ node: element, metadataID, attrKey: attributeKey });\n }\n\n // Flush any remaining group at end of head\n flushGroup();\n }\n },\n };\n}\n","import { isValidRelativePath, splitHtmlLink } from \"../../../utilities/html-links.ts\";\nimport { isPackageMetadata, isTextAssetMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { basename, dirname, extname, join, relative, replaceExtension } from \"../../../utilities/path.ts\";\nimport { safeReadFileSync } from \"../../../utilities/read-file.ts\";\nimport { cloneObject } from \"../../../utilities/utilities.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\n/**\n * The baseline of the pipeline: reads files from disk, resolves and rebases links, and clones or prints the metadata kinds no\n * other plugin claims (text assets and bundled packages).\n *\n * Notes:\n *\n * - A resolved link keeps the style it was written in: an extensionless or directory-style link to a page stays that way, while a\n * script path resolving to \".ts\", \".tsx\" or \".jsx\" is rewritten to \".js\", which is what actually ships.\n * - Query strings and hashes survive both resolving and rebasing, and a link that ends up pointing at its own page becomes \"./\".\n */\nexport function coreBasePlugin(): Plugin {\n const JS_EXTENSIONS = new Set([\".js\", \".mjs\", \".cjs\", \".jsx\", \".ts\", \".mts\", \".cts\", \".tsx\"]);\n\n return {\n name: \"core-base\",\n\n read(absolutePath) {\n const [fileContent, readFileError] = safeReadFileSync(absolutePath, \"utf8\");\n if (readFileError) {\n return;\n }\n\n return fileContent;\n },\n\n onFileEvent(event, filePath) {\n if (event === \"unlink\") {\n this.resolver.files.delete(filePath);\n }\n },\n\n clone(metadata) {\n if (isTextAssetMetadata(metadata) || isPackageMetadata(metadata)) {\n return cloneObject(metadata);\n }\n },\n\n stringify(metadata) {\n if (isTextAssetMetadata(metadata) || isPackageMetadata(metadata)) {\n return metadata.code;\n }\n },\n\n resolveSource(source, filePath, metadata) {\n if (!isValidRelativePath(source)) return;\n\n const resolveResult = this.resolver.resolve(source, filePath);\n if (!resolveResult) {\n this.log.error(`Failed to resolve \"${source}\" found in \"${filePath}\" of type \"${metadata.type}\"`);\n return;\n }\n\n let resolved = resolveResult.path;\n\n // The browser can only load JS files\n if (JS_EXTENSIONS.has(extname(resolved))) {\n resolved = replaceExtension(resolved, \".js\");\n }\n\n resolved = relative(join(this.root, dirname(filePath)), resolved);\n\n if (!resolveResult.isFileAlias) {\n resolved = matchSourceStyle(source, resolved);\n }\n\n // case: \"./\" with suffix \"/\" -> \".//\" which is not a valid link\n if (resolved.endsWith(\"/\") && resolveResult.suffix.startsWith(\"/\")) {\n resolved = resolved.slice(0, -1);\n }\n\n resolved += resolveResult.suffix;\n\n const dependencyID = resolveResult.exists ? relative(this.root, resolveResult.path) : undefined;\n\n return { source: resolved, dependencyID };\n },\n\n rebaseSource(source, filePath, newAbsolutePath) {\n if (!isValidRelativePath(source)) return;\n\n const [link, suffix] = splitHtmlLink(source);\n\n // Already a self-reference (pointing to own directory)\n if ([\"index.html\", \"index.md\"].includes(basename(filePath)) && [\"./\", \".\", \"\"].includes(link)) {\n return source;\n }\n\n const oldAbsolutePath = join(this.root, filePath);\n const sourceAbsolute = join(dirname(oldAbsolutePath), link).replace(/\\/$/, \"\");\n\n let rebased = relative(dirname(newAbsolutePath), sourceAbsolute);\n\n // Going to be a self-reference after rebasing\n if (basename(newAbsolutePath) === \"index.html\" && isSelfReference(sourceAbsolute, newAbsolutePath)) {\n rebased = \"./\";\n }\n\n // Preserve \"/\" in this edge case\n if (link === \"./\" && !rebased.endsWith(\"/\")) {\n rebased += \"/\";\n }\n\n // Avoid double-slash\n if (rebased.endsWith(\"/\") && suffix.startsWith(\"/\")) {\n rebased = rebased.slice(0, -1);\n }\n\n rebased += suffix;\n\n return rebased;\n },\n\n onMetadataRebase(metadata, _, newAbsolutePath) {\n metadata.filePath = relative(this.root, newAbsolutePath);\n },\n };\n}\n\n/**\n * Adjusts a resolved path to match the style of the original link.\n *\n * Preserves whether the original link used an explicit extension, no extension, or an index-based directory style. Only applies\n * to `.html` and `.md` resolved paths.\n *\n * @example\n * matchSourceStyle(\"./auth/login/\", \"./auth/login.html\"); // \"./auth/login\"\n * matchSourceStyle(\"./auth/login/\", \"./auth/login/index.html\"); // \"./auth/login\"\n * matchSourceStyle(\"./auth/login\", \"./auth/login.html\"); // \"./auth/login\"\n * matchSourceStyle(\"./auth/login.html\", \"./auth/login.html\"); // \"./auth/login.html\"\n */\nfunction matchSourceStyle(originalSource: string, resolvedPath: string): string {\n const [originalLink] = splitHtmlLink(originalSource);\n\n const resolvedExtension = extname(resolvedPath);\n\n // Only target links to `.html` or `.md`\n if (resolvedExtension !== \".html\" && resolvedExtension !== \".md\") {\n return resolvedPath;\n }\n\n // Preserve explicit extensions\n const originalExtension = extname(originalLink);\n if (originalExtension === \".html\" || originalExtension === \".md\") {\n return resolvedPath;\n }\n\n const resolvedNoExtension = replaceExtension(resolvedPath, \"\");\n const resolvedFilename = basename(resolvedPath, resolvedExtension);\n\n // Match using index.html or index.md\n if (resolvedFilename === \"index\") {\n return dirname(resolvedPath);\n }\n\n // Match no extension\n return resolvedNoExtension;\n}\n\nexport function isSelfReference(sourceAbsolute: string, filePathAbsolute: string): boolean {\n const sourceExtension = extname(sourceAbsolute);\n\n // Only look for sources points to directories, .html, or .md\n if (![\".html\", \".md\", \"\"].includes(sourceExtension)) {\n return false;\n }\n\n // Exact match\n if (sourceAbsolute === filePathAbsolute) {\n return true;\n }\n\n // Try with .html\n const htmlExtensionCandidate = replaceExtension(sourceAbsolute, \".html\");\n if (htmlExtensionCandidate === filePathAbsolute) {\n return true;\n }\n\n // Try with .md\n const mdExtensionCandidate = replaceExtension(sourceAbsolute, \".md\");\n if (mdExtensionCandidate === filePathAbsolute) {\n return true;\n }\n\n // Try index.html\n const indexHtmlCandidate = join(sourceAbsolute, \"index.html\");\n if (indexHtmlCandidate === filePathAbsolute) {\n return true;\n }\n\n // Try index.md\n const indexMdCandidate = join(sourceAbsolute, \"index.md\");\n return indexMdCandidate === filePathAbsolute;\n}\n","import { dirname, extname, isSubpath, join, normalize, parse, replaceExtension } from \"../../utilities/path.ts\";\n\n/**\n * - Help to calculate the new html path when compiling html files in the pages directory\n * - For example: `./pages/home.html` => `./home/index.html`\n *\n * @returns - The new html path or the original path if it is not in the Pages directory\n */\nexport function calculatePagePath(originalPath: string, pagesDirectory: string): string {\n if (extname(originalPath) === \".md\") {\n originalPath = replaceExtension(originalPath, \".html\");\n }\n\n const isInPagesDirectory = isSubpath(pagesDirectory, dirname(originalPath));\n if (!isInPagesDirectory) {\n return normalize(originalPath);\n }\n\n const fileName = parse(originalPath).name; // without extension\n const extension = extname(originalPath);\n\n let newPath = cutLeadingSubpath(originalPath, pagesDirectory);\n\n // Only add \"index\" for files with an extension otherwise its a directory\n if (extension && fileName !== \"index\") {\n newPath = join(dirname(newPath), fileName, \"index\" + extension);\n }\n\n return newPath;\n}\n\n/**\n * - Cut the leading subpath from a path\n *\n * @example\n * cutLeadingSubpath('/a/b/c', '/a') => 'b/c'\n *\n * @param pathToCut - The path to cut\n * @param leadingSubpath - The leading subpath\n * @returns - The path without the leading subpath\n */\nfunction cutLeadingSubpath(pathToCut: string, leadingSubpath: string): string {\n const pathParts = normalize(pathToCut).split(\"/\");\n const subpathParts = normalize(leadingSubpath).split(\"/\");\n const withCut = pathParts\n .map((part, index) => (index >= subpathParts.length ? part : part === subpathParts[index] ? \"\" : part))\n .filter(Boolean);\n\n return normalize(withCut.join(\"/\"));\n}\n","import type { ValueOrError } from \"../../utilities/value-or-error.ts\";\nimport type { RouteData } from \"./dynamic-routes.ts\";\n\n/** (any){{any}} */\nconst placeholderRe = /(\\\\)?{{\\s*([\\s\\S]*?)\\s*}}/g;\n\n/** `{{ JavaScript expression }}` */\nexport function fillPlaceholders(html: string, routeData: RouteData): ValueOrError<string> {\n const errors: Error[] = [];\n\n const result = html.replace(placeholderRe, (match: string, escape: string, content: string) => {\n if (escape === \"\\\\\") {\n return match.slice(1);\n }\n\n const [expression, executeError] = executeExpression(content, routeData);\n if (executeError) {\n errors.push(executeError);\n return \"\";\n }\n\n return expression;\n });\n\n // join errors\n if (errors.length > 0) {\n const combinedMessage = [\n \"Failed to fill placeholders\",\n ...errors.map((error, index) => ` [${index + 1}] ${error.message}`),\n ].join(\"\\n\");\n\n return [null, new AggregateError(errors, combinedMessage)];\n }\n\n return [result, null];\n}\n\ntype FunctionType = (parameters: RouteData[\"params\"], properties: Required<RouteData>[\"props\"]) => unknown;\nconst functionCache = new Map<string, FunctionType>();\n\nfunction executeExpression(expressionString: string, data: RouteData): ValueOrError<string> {\n try {\n let function_ = functionCache.get(expressionString);\n if (!function_) {\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n function_ = new Function(\"$params\", \"$props\", `return ${expressionString}`) as FunctionType;\n functionCache.set(expressionString, function_);\n }\n\n const output = function_(data.params, data.props ?? {});\n\n if (output === undefined) {\n return [null, new Error(`Expression found in the placeholder {{ ${expressionString} }} returned undefined`)];\n }\n\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n const asString = String(output);\n\n if (asString === \"[object Object]\") {\n return [null, new Error(`Expression found in the placeholder {{ ${expressionString} }} returned an object`)];\n }\n\n return [asString, null];\n } catch (error) {\n return [null, new Error(`Failed to execute expression: ${expressionString}\\n ${(error as Error).message}`)];\n }\n}\n","import * as z from \"zod/v4\";\n\nimport { executeJsInVM } from \"../../helpers/execute-js-in-vm.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { Log } from \"../../utilities/logger.ts\";\nimport { isHtmlMetadata, isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { join, relative } from \"../../utilities/path.ts\";\nimport { printFmtError } from \"../../utilities/print-formatted-error.ts\";\nimport { fillPlaceholders } from \"./fill-placeholders.ts\";\n\nimport type { ValueOrError } from \"../../utilities/value-or-error.ts\";\nimport type { App, HtmlMetadata, ScriptMetadata } from \"@staticbolt/core\";\n\nconst getStaticPathsSchema = z.array(\n z.object({\n params: z.record(z.string(), z.string()),\n props: z.record(z.string(), z.string()).optional(),\n })\n);\n\ntype GetStaticPathsResults = z.infer<typeof getStaticPathsSchema>;\n\nexport type RouteData = GetStaticPathsResults[number];\n\nexport async function handleDynamicRoutes(this: App, htmlMetadata: HtmlMetadata) {\n // Collect executable scripts that need to be executed to extract routes data\n const executableScripts = collectExecutableScripts.call(this, htmlMetadata);\n\n const routesData: RouteData[] = [];\n\n for (const scriptMetadata of executableScripts) {\n await this.resolve(scriptMetadata);\n\n await this.transform(scriptMetadata);\n\n // TODO: Load dependencies\n\n // Execute and collect routes data\n const [parameters, collectError] = await collectParameters.call(this, htmlMetadata, scriptMetadata);\n if (collectError) {\n printFmtError(collectError, { filePath: htmlMetadata.id });\n continue;\n }\n\n routesData.push(...parameters);\n }\n\n const generatedRoutes: HtmlMetadata[] = [];\n\n const templateString = await this.stringify(htmlMetadata);\n\n for (const routeData of routesData) {\n // Fill and populate\n const [pageString, fillError] = fillPlaceholders(templateString, routeData);\n if (fillError) {\n printFmtError(fillError, { filePath: htmlMetadata.id });\n continue;\n }\n\n // String to HTML metadata\n const generatedMetadata = await this.load(htmlMetadata.filePath, { code: pageString, type: \"html\" });\n if (!isHtmlMetadata(generatedMetadata)) {\n Log.error(\"Expected HTML metadata\");\n continue;\n }\n\n const metadataList = await this.resolveAndLoad(generatedMetadata);\n\n // Remove generated metadata (first one)\n metadataList.shift();\n\n // Add discovered metadata\n this.addMetadata(metadataList);\n\n const newFilePath = fillDynamicPath(htmlMetadata.filePath, routeData.params);\n await this.rebase(generatedMetadata, join(this.root, newFilePath));\n\n // Remove existing\n const existingIndex = generatedRoutes.findIndex(existing => existing.filePath === generatedMetadata.filePath);\n if (existingIndex !== -1) {\n generatedRoutes.splice(existingIndex, 1);\n }\n\n generatedRoutes.push(generatedMetadata);\n }\n\n return { routesData, generatedRoutes };\n}\n\nfunction collectExecutableScripts(this: App, htmlMetadata: HtmlMetadata): ScriptMetadata[] {\n const attribute = \"params\";\n const query = `script[${attribute}]`;\n\n const result: ScriptMetadata[] = [];\n\n const scripts = htmlMetadata.ast.querySelectorAll(query);\n\n for (const node of scripts) {\n // Script with content\n const metadataID = node.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (metadataID) {\n const inlinedMetadata = htmlMetadata.scriptsMetadataList.get(metadataID);\n if (!inlinedMetadata) {\n printFmtError(\"Failed to execute script tag. Missing metadata\", { node, filePath: htmlMetadata.id });\n continue;\n }\n\n result.push(inlinedMetadata);\n continue;\n }\n\n // Script with src attribute\n const source = node.getAttribute(\"src\");\n if (!source) {\n printFmtError('Failed to execute script tag. Missing \"src\" attribute', { node, filePath: htmlMetadata.id });\n continue;\n }\n\n const resolved = this.resolver.resolve(source, htmlMetadata.id);\n if (!resolved || !resolved.exists) {\n printFmtError(\"Failed to execute script tag. Missing file\", { node, filePath: htmlMetadata.id });\n continue;\n }\n\n const relativeToRoot = relative(this.root, resolved.path);\n\n const fileMetadata = this.findMetadata({ filePath: relativeToRoot });\n if (!isScriptMetadata(fileMetadata)) {\n printFmtError(\"Failed to execute script tag. Missing metadata\", { node, filePath: htmlMetadata.id });\n continue;\n }\n\n result.push(fileMetadata);\n }\n\n // remove script tags after executing\n for (const node of htmlMetadata.ast.querySelectorAll(query)) {\n node.remove();\n }\n\n return result;\n}\n\n/** Fills a dynamic route path with the given params. Supports [param] and [...param] (catch-all) segments. */\nfunction fillDynamicPath(path: string, parameters: Record<string, string>): string {\n const segments = path.split(\"/\");\n const result: string[] = [];\n\n for (const segment of segments) {\n const catchAllMatch = segment.match(/^\\[\\.\\.\\.(.*)\\]$/);\n if (catchAllMatch) {\n result.push(parameters[catchAllMatch[1]] ?? \"\");\n continue;\n }\n\n const dynamicMatch = segment.match(/\\[([^\\]]+)\\]/);\n if (dynamicMatch) {\n const key = dynamicMatch[1];\n const value = parameters[key] ?? dynamicMatch[0];\n\n if (value.includes(\"/\")) {\n throw new Error(`Dynamic param \"${key}\" contains slashes. Use \"[...${key}]\" for catch-all routes.`);\n }\n\n result.push(segment.replace(/\\[([^\\]]+)\\]/, () => value));\n continue;\n }\n\n result.push(segment);\n }\n\n return result.filter(Boolean).join(\"/\");\n}\n\nasync function collectParameters(\n this: App,\n parentHtmlMetadata: HtmlMetadata,\n scriptMetadata: ScriptMetadata\n): Promise<ValueOrError<GetStaticPathsResults>> {\n const getCode = async (targetPath: string) => {\n // Entry point\n if (targetPath === scriptMetadata.filePath) {\n return await this.stringify(scriptMetadata);\n }\n\n // External file\n const foundMetadata = this.findMetadata({ filePath: targetPath });\n if (foundMetadata) {\n return await this.stringify(foundMetadata);\n }\n };\n\n const context = { window: globalThis, document: parentHtmlMetadata.ast };\n\n const [executeResult, error] = await executeJsInVM({\n root: this.root,\n entryFile: scriptMetadata.filePath,\n getCode,\n context,\n });\n\n if (error) {\n return [null, error];\n }\n\n if (!(\"getStaticPaths\" in executeResult.exports)) {\n return [null, new Error(\"Must export a function named `getStaticPaths`\")];\n }\n\n const getStaticPaths = executeResult.exports.getStaticPaths;\n if (typeof getStaticPaths !== \"function\") {\n return [null, new Error(\"Must export a function named `getStaticPaths`\")];\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n const parameters = (await getStaticPaths()) as unknown;\n\n const parseResult = getStaticPathsSchema.safeParse(parameters);\n if (!parseResult.success) {\n return [null, parseResult.error];\n }\n\n return [parseResult.data, null];\n}\n\nconst DYNAMIC_SEGMENT_RE = /\\[(\\.{3})?[a-zA-Z_][a-zA-Z0-9_]*\\]/;\n\n/** Checks if the file path is a dynamic route. E.g. `/users/[id].html`, `/users/[...slug]/profile.html` */\nexport function isDynamicRoute(path: string): boolean {\n return path.split(\"/\").some(segment => DYNAMIC_SEGMENT_RE.test(segment));\n}\n","import { globSync } from \"glob\";\n\nimport { isValidRelativePath, splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata, isMarkdownMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { basename, dirname, extname, isSubpath, join, normalize, relative } from \"../../utilities/path.ts\";\nimport { isSelfReference } from \"../core-plugins/base-plugin/base-plugin.ts\";\nimport { calculatePagePath } from \"./calculate-page-path.ts\";\nimport { handleDynamicRoutes, isDynamicRoute } from \"./dynamic-routes.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlPagesOptions {\n /**\n * Pages directory relative to the root.\n *\n * @default [\"pages\"]\n */\n pagesDir?: string;\n\n /**\n * Where to output the HTML pages relative to the output directory.\n *\n * @default \"./\"\n */\n outputDir?: string;\n}\n\n/**\n * Turns the files under the pages directory into routes: every \".html\" and \".md\" file in \"pagesDir\" is emitted at its clean URL\n * path, and the links pointing into the directory are rewritten to match.\n *\n * - \"pages/home.html\" becomes \"home/index.html\", so it is served at \"/home/\", while a file already named \"index\" keeps its place.\n * - Markdown pages are rendered to HTML first, and the markdown itself is kept out of the output.\n * - Square brackets mark a dynamic route: \"pages/users/[id].html\" is expanded into one page per entry returned by the\n * \"getStaticPaths\" export of its \"<script params>\" tag, with \"{{ $params.x }}\" and \"{{ $props.x }}\" filled in.\n *\n * Notes:\n *\n * - Rebasing goes both ways: a page's own links survive the move out of \"pagesDir\", and links from anywhere else pointing into it\n * are rewritten to the final URL.\n * - \"outputDir\" puts the whole route tree under a subdirectory of the output.\n * - The dev server resolves a request through the same computed paths, with or without the trailing \"index.html\", dynamic routes\n * included.\n */\nexport function htmlPagesPlugin(options: HtmlPagesOptions = {}): Plugin {\n const pagesDirectory = normalize(options.pagesDir ?? \"./pages\");\n const outputDirectory = normalize(options.outputDir ?? \"./\");\n\n const pagesFiles = new Set<string>();\n const dynamicPathGeneratedMap = new Map<string, Set<string>>();\n\n return {\n name: \"html-pages\",\n\n async setup() {\n if (this.production) return;\n\n this.watcher?.add(pagesDirectory);\n\n const pages = globSync(`${pagesDirectory}/**/*.{html,md}`, { cwd: this.root, nodir: true });\n\n for (let pageFile of pages) {\n pageFile = normalize(pageFile);\n\n pagesFiles.add(pageFile);\n\n if (extname(pageFile) !== \".html\" || !isDynamicRoute(pageFile)) continue;\n\n // Load dynamic routes to be able to resolve requests from dev server\n const metadata = await this.load(pageFile);\n if (metadata) {\n this.addMetadata(metadata);\n }\n }\n },\n\n async preTransform() {\n for (const htmlMetadata of Array.from(this.metadataList)) {\n if (!isHtmlMetadata(htmlMetadata)) continue;\n\n const isDynamic = isPageDirectorySubpath(htmlMetadata.filePath, pagesDirectory) && isDynamicRoute(htmlMetadata.filePath);\n if (!isDynamic) continue;\n\n // Remove any metadata with the same ID\n this.removeMetadata(this.filterMetadata({ id: htmlMetadata.id }));\n\n const { generatedRoutes } = await handleDynamicRoutes.call(this, htmlMetadata);\n\n for (const generated of generatedRoutes) {\n this.addMetadata(generated);\n\n const generatedSet = dynamicPathGeneratedMap.get(generated.id) ?? new Set();\n generatedSet.add(generated.filePath);\n dynamicPathGeneratedMap.set(generated.id, generatedSet);\n }\n }\n },\n\n resolveRequestPath(requestPath) {\n const [requestPathWithoutQuery] = splitHtmlLink(requestPath);\n\n for (const [id, generatedSet] of dynamicPathGeneratedMap) {\n for (const generated of generatedSet) {\n const pageOutputPath = calculatePagePath(generated, pagesDirectory);\n\n // exact match\n if (requestPathWithoutQuery === pageOutputPath) {\n return id;\n }\n\n // without index.html\n if (basename(pageOutputPath) === \"index.html\" && requestPathWithoutQuery === dirname(pageOutputPath)) {\n return id;\n }\n }\n }\n\n for (const pageFile of pagesFiles) {\n const pageOutputPath = calculatePagePath(pageFile, pagesDirectory);\n\n // exact match\n if (requestPathWithoutQuery === pageOutputPath) {\n return pageFile;\n }\n\n // without index.html\n if (basename(pageOutputPath) === \"index.html\" && requestPathWithoutQuery === dirname(pageOutputPath)) {\n return pageFile;\n }\n }\n },\n\n onFileEvent(type, filePath) {\n if (type === \"add\" && isPageDirectorySubpath(filePath, pagesDirectory)) {\n pagesFiles.add(filePath);\n return;\n }\n\n if (type === \"unlink\") {\n pagesFiles.delete(filePath);\n }\n },\n\n // Since we are moving all pages outside the \"pages\" directory, we need to rebase links points to the \"pages\" directory\n rebaseSource(source, filePath, newAbsolutePath) {\n if (!isValidRelativePath(source)) return;\n\n const relativeNewPath = relative(this.root, newAbsolutePath);\n\n const isRebasingFromPages = isPageDirectorySubpath(filePath, pagesDirectory);\n const isRebasingToPages = isPageDirectorySubpath(relativeNewPath, pagesDirectory);\n\n // Same directory rebase. Skip\n if (isRebasingFromPages && isRebasingToPages) {\n return;\n }\n\n // Only proceed when rebasing involves the pages directory. Skip\n if (!isRebasingFromPages && !isRebasingToPages) {\n return;\n }\n\n const [link, suffix] = splitHtmlLink(source);\n\n // Already a self-reference. Return the original source\n if ([\"index.html\", \"index.md\"].includes(basename(filePath)) && [\"./\", \".\", \"\"].includes(link)) {\n return source;\n }\n\n const sourceAbs = join(this.root, dirname(filePath), link);\n\n // Only sources points to directories, HTML, Markdown\n const isSourceHTML = [\".html\", \".md\", \"\"].includes(extname(sourceAbs));\n if (!isSourceHTML) {\n return;\n }\n\n // Only sources points to file inside the \"pages\" directory\n const isSourcePage = isPageDirectorySubpath(relative(this.root, sourceAbs), pagesDirectory);\n if (!isSourcePage) {\n return;\n }\n\n // Going to be a self-reference after rebasing\n const newFileName = basename(newAbsolutePath);\n const absFilePath = join(this.root, filePath);\n if ([\"index.html\", \"index.md\"].includes(newFileName) && isSelfReference(sourceAbs, absFilePath)) {\n return \"./\" + suffix.replace(/^\\//, \"\");\n }\n\n const sourceRootRelative = join(dirname(filePath), link);\n let rebased = relative(dirname(join(pagesDirectory, relativeNewPath)), sourceRootRelative);\n\n // Preserve \"/\" in this edge case\n if (link === \"./\" && !rebased.endsWith(\"/\")) {\n rebased += \"/\";\n }\n\n // Avoid double-slash\n if (rebased.endsWith(\"/\") && suffix.startsWith(\"/\")) {\n rebased = rebased.slice(0, -1);\n }\n\n rebased += suffix;\n\n return rebased;\n },\n\n // Sources from outside the \"pages\" directory pointing to the \"pages\" directory should be rebased as well\n transformSource(source, filePath) {\n if (!isValidRelativePath(source)) return;\n\n // Pages' own sources are handled by rebaseSource during transform\n const isFilePage = [\".html\", \".md\", \"\"].includes(extname(filePath));\n if (isFilePage && isPageDirectorySubpath(filePath, pagesDirectory)) {\n return;\n }\n\n const [sourceLink, suffix] = splitHtmlLink(source);\n\n // Only sources pointing to directories, HTML, Markdown\n const isSourceHTML = [\".html\", \".md\", \"\"].includes(extname(sourceLink));\n if (!isSourceHTML) {\n return;\n }\n\n const sourceRootRelative = join(dirname(filePath), sourceLink);\n\n // Only fix links pointing into the pages directory\n const isPointingToPage = isPageDirectorySubpath(sourceRootRelative, pagesDirectory);\n if (!isPointingToPage) {\n return;\n }\n\n // Where the source page ends up after being moved out of pagesDirectory\n const isPagesItself = normalize(sourceRootRelative) === normalize(pagesDirectory);\n const sourceNewPath = isPagesItself\n ? outputDirectory\n : join(outputDirectory, calculatePagePath(sourceRootRelative, pagesDirectory));\n\n const rebased = relative(dirname(filePath), sourceNewPath);\n\n return rebased + suffix;\n },\n\n async transform(metadata) {\n if (isHtmlMetadata(metadata)) {\n if (!isPageDirectorySubpath(metadata.filePath, pagesDirectory)) return;\n\n const pageOutputPath = calculatePagePath(metadata.filePath, pagesDirectory);\n const absPageOutputPath = join(this.root, outputDirectory, pageOutputPath);\n\n await this.rebase(metadata, absPageOutputPath);\n\n return;\n }\n\n if (isMarkdownMetadata(metadata)) {\n if (!isPageDirectorySubpath(metadata.filePath, pagesDirectory)) return;\n\n const asHtmlString = await metadata.ast.render();\n\n // Load as HTML\n const htmlMetadata = await this.load(metadata.id, { code: asHtmlString, type: \"html\" });\n if (!isHtmlMetadata(htmlMetadata)) {\n this.log.error(`Failed to load HTML metadata for \"${metadata.filePath}\"`);\n return;\n }\n\n // Resolve -> Discover -> Load -> Transform\n const metadataList = await this.resolveAndLoad(htmlMetadata);\n this.addMetadata(metadataList);\n await this.transformAndSync(metadataList);\n\n this.emitExclude.add(metadata);\n\n return;\n }\n },\n };\n}\n\nfunction isPageDirectorySubpath(filePath: string, pagesDirectory: string): boolean {\n filePath = extname(filePath) ? dirname(filePath) : filePath;\n\n if (filePath === pagesDirectory) {\n return true;\n }\n\n return isSubpath(pagesDirectory, dirname(filePath));\n}\n","import { basename, extname } from \"../../utilities/path.ts\";\n\nconst MIME_TYPES: Record<string, string> = Object.freeze({\n // Fonts\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".ttf\": \"font/ttf\",\n \".otf\": \"font/otf\",\n \".eot\": \"application/vnd.ms-fontobject\",\n\n // Audio\n \".mp3\": \"audio/mpeg\",\n \".wav\": \"audio/wav\",\n \".ogg\": \"audio/ogg\",\n \".m4a\": \"audio/mp4\",\n\n // Video\n \".mp4\": \"video/mp4\",\n \".webm\": \"video/webm\",\n \".ogv\": \"video/ogg\",\n\n // Images\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".avif\": \"image/avif\",\n \".svg\": \"image/svg+xml\",\n\n // Files\n \".json\": \"application/json\",\n \".wasm\": \"application/wasm\",\n \".bin\": \"application/octet-stream\",\n \".data\": \"application/octet-stream\",\n \".pb\": \"application/x-protobuf\",\n \".msgpack\": \"application/x-msgpack\",\n});\n\nconst AS_TYPES: Record<string, string> = Object.freeze({\n \".js\": \"script\",\n \".mjs\": \"script\",\n \".css\": \"style\",\n \".woff\": \"font\",\n \".woff2\": \"font\",\n \".ttf\": \"font\",\n \".otf\": \"font\",\n \".eot\": \"font\",\n \".mp3\": \"audio\",\n \".wav\": \"audio\",\n \".ogg\": \"audio\",\n \".m4a\": \"audio\",\n \".mp4\": \"video\",\n \".webm\": \"video\",\n \".ogv\": \"video\",\n \".png\": \"image\",\n \".jpg\": \"image\",\n \".jpeg\": \"image\",\n \".gif\": \"image\",\n \".webp\": \"image\",\n \".avif\": \"image\",\n \".svg\": \"image\",\n\n // fetch — data files loaded via fetch()/XHR\n \".json\": \"fetch\",\n \".wasm\": \"fetch\",\n \".bin\": \"fetch\",\n \".data\": \"fetch\",\n \".pb\": \"fetch\",\n \".msgpack\": \"fetch\",\n});\n\ninterface PreloadInfo {\n rel: \"preload\" | \"modulepreload\";\n as: string;\n type?: string;\n crossorigin?: true;\n}\n\nexport function getPreloadInfo(filePath: string): PreloadInfo | undefined {\n const extension = extname(basename(filePath)).toLowerCase();\n const as = AS_TYPES[extension];\n\n if (!as) {\n return undefined;\n }\n\n const info: PreloadInfo = { rel: \"preload\", as };\n\n const mime = MIME_TYPES[extension];\n if (mime) {\n info.type = mime;\n }\n\n // Fonts must be fetched with CORS or the browser ignores the hint\n if (as === \"font\") {\n info.crossorigin = true;\n }\n\n if (extension === \".wasm\") {\n info.rel = \"modulepreload\";\n }\n\n return info;\n}\n","import { DependenciesFinder as DependenciesFinder } from \"../../helpers/find-dependencies.ts\";\nimport { isScriptType } from \"../../helpers/is-script-type.ts\";\nimport { isDynamic, isJavaScript } from \"../../helpers/lsp-checks.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata, isScriptMetadata, isStyleMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join, isPathMatch, parsePatterns, relative } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { getPreloadInfo } from \"./get-file-type.ts\";\n\nimport type { ElementInfo, HTMLElement, HtmlMetadata, MetadataBase, Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlPreloadOptions {\n /**\n * Attribute name that enables preloading.\n *\n * @default \"preload\"\n */\n preloadAttribute?: string;\n\n /**\n * Attribute name for including files.\n *\n * @default \"preload-include\"\n */\n includeAttribute?: string;\n\n /**\n * Attribute name for excluding files.\n *\n * @default \"preload-exclude\"\n */\n excludeAttribute?: string;\n}\n\n/**\n * Adds \"<link rel=preload>\" tags to the \"<head>\" for the dependencies of the scripts and stylesheets marked with \"preload\"\n * (attribute names configurable via HtmlPreloadOptions), so the browser starts fetching them before parsing gets that far.\n *\n * Attributes:\n *\n * - \"preload\": marks the tag. Its value narrows what to emit to a space-separated list of \"script\", \"style\", \"fetch\", \"font\",\n * \"audio\", \"video\" and \"image\"; an empty value means all of them.\n * - \"preload-include\" and \"preload-exclude\": semicolon-separated glob patterns, matched against paths relative to the project root.\n *\n * Notes:\n *\n * - Production only; in development the three attributes are just stripped.\n * - Handles \"<script>\", \"<style>\" and \"<link rel=stylesheet>\" tags. The attribute on any other tag emits nothing.\n * - The dependency walk covers the whole graph behind the tag (imports, \"@import\", \"url()\") plus the file it points at, and files\n * whose extension has no known \"as\" type are skipped.\n * - The links are appended at the end of \"<head>\", so they come after whatever the page already has there.\n */\nexport function htmlPreloadPlugin(options: HtmlPreloadOptions = {}): Plugin {\n const preloadAttribute = options.preloadAttribute ?? \"preload\";\n const includeAttribute = options.includeAttribute ?? \"preload-include\";\n const excludeAttribute = options.excludeAttribute ?? \"preload-exclude\";\n\n const asTypes = [\"script\", \"style\", \"fetch\", \"font\", \"audio\", \"video\", \"image\"];\n const query = `[${preloadAttribute}]`;\n\n const printFmtError = PrintFormattedError.create({ function: htmlPreloadPlugin });\n\n return {\n name: \"html-preload\",\n\n // Clean up during development\n transform(metadata) {\n if (this.production || !isHtmlMetadata(metadata)) return;\n\n const elements = metadata.ast.querySelectorAll(query);\n for (const node of elements) {\n node.removeAttribute(preloadAttribute);\n node.removeAttribute(includeAttribute);\n node.removeAttribute(excludeAttribute);\n }\n },\n\n async postTransform() {\n if (!this.production) return;\n\n const dependenciesFinder = new DependenciesFinder(this, this.root);\n\n for (const htmlMetadata of this.metadataList) {\n if (!isHtmlMetadata(htmlMetadata)) continue;\n\n const head = htmlMetadata.ast.querySelector(\"head\");\n if (!head) continue;\n\n const elements = htmlMetadata.ast.querySelectorAll(query);\n\n for (const node of elements) {\n const preloadValue = node.getAttribute(preloadAttribute);\n const preloadTypes = preloadValue ? preloadValue.split(\" \").filter(Boolean) : asTypes;\n\n const includePatterns = parsePatterns(node.getAttribute(includeAttribute));\n const include = includePatterns?.length ? includePatterns : [\"**/*\"];\n const ignore = parsePatterns(node.getAttribute(excludeAttribute));\n\n node.removeAttribute(preloadAttribute);\n node.removeAttribute(includeAttribute);\n node.removeAttribute(excludeAttribute);\n\n // Case script or style tag:\n const isScript = node.tagName === \"SCRIPT\";\n const isStyle = node.tagName === \"STYLE\";\n const isStyleSheetLink = node.tagName === \"LINK\" && node.getAttribute(\"rel\") === \"stylesheet\";\n\n const scriptType = node.getAttribute(\"type\");\n if (isScript && !isScriptType(scriptType)) {\n continue;\n }\n\n const preloadPaths = new Set<string>();\n\n if (isScript || isStyle || isStyleSheetLink) {\n const metadata = getMetadata(this.metadataList, htmlMetadata, node);\n if (!isStyleMetadata(metadata) && !isScriptMetadata(metadata)) {\n printFmtError(`Failed to get metadata for ${node.tagName} tag`, { node, filePath: htmlMetadata.id });\n continue;\n }\n\n const dependencies = await dependenciesFinder.findDeps(metadata);\n\n const source = node.getAttribute(\"src\") ?? node.getAttribute(\"href\");\n\n if ((isScript && source) || (isStyleSheetLink && source)) {\n const [link] = splitHtmlLink(source);\n dependencies.add(join(this.root, dirname(htmlMetadata.filePath), link));\n }\n\n for (const dependency of dependencies) {\n const relativeDependencyPath = relative(this.root, dependency);\n\n if (!isPathMatch(relativeDependencyPath, { include, ignore, root: this.root })) {\n continue;\n }\n\n preloadPaths.add(relative(dirname(htmlMetadata.filePath), dependency));\n }\n }\n\n const linkTags: string[] = [];\n\n for (const path of preloadPaths) {\n const typeInfo = getPreloadInfo(path);\n if (!typeInfo) {\n continue;\n }\n\n if (!preloadTypes.includes(typeInfo.as)) {\n continue;\n }\n\n linkTags.push(createLinkTag(typeInfo, path));\n }\n\n head.insertAdjacentHTML(\"beforeend\", linkTags.join(\"\\n\"));\n\n // TODO: Preload for other kinds of tags\n }\n }\n },\n\n lspHtmlData() {\n const attributes = [\n {\n name: preloadAttribute,\n description:\n \"Enable preloading.\" +\n '\\nAutomatically generates `<link rel=\"preload\">` tags for the dependencies of your scripts and stylesheets.' +\n \"\\nThis tells the browser to start fetching those files early, before they are discovered through normal parsing.\" +\n \"\\n\\nYou can narrow down the files to preload by specifying a space-separated list of dependency types,\" +\n ` additionally you can use the \\`${includeAttribute}\\` and \\`${excludeAttribute}\\` attributes.`,\n values: asTypes.map(type => ({ name: type })),\n },\n {\n name: includeAttribute,\n description: `Glob patterns list to include when using the \\`${preloadAttribute}\\` attribute. (semicolon-separated)`,\n },\n {\n name: excludeAttribute,\n description: `Glob patterns list to exclude when using the \\`${preloadAttribute}\\` attribute. (semicolon-separated)`,\n },\n ];\n\n const description =\n `Adds the \\`${preloadAttribute}\\`, \\`${includeAttribute}\\` and \\`${excludeAttribute}\\` attributes,` +\n ` which emit \\`<link rel=\"preload\">\\` tags in the \\`<head>\\` for this tag's dependencies at build time.`;\n\n return {\n version: 1.1,\n tags: [\n { name: \"link\", description, attributes },\n { name: \"script\", description, attributes },\n ],\n };\n },\n\n lspValidate(document, report) {\n for (const element of document.elements) {\n const preload = element.attribute(preloadAttribute);\n if (!preload) continue;\n\n if (!isPreloadable(element)) {\n report.warn(preload.nameRange, `\"${preloadAttribute}\" only works on a script, a style or a stylesheet link`);\n continue;\n }\n\n if (!preload.value) continue;\n if (isDynamic(preload.value)) continue;\n\n const unknownTypes = preload.value.split(\" \").filter(type => type && !asTypes.includes(type));\n if (unknownTypes.length === 0) continue;\n\n report.error(preload, `Unknown preload types ${unknownTypes.join(\", \")}, use ${asTypes.join(\", \")}`);\n }\n },\n };\n}\n\n/** Whether the preload attribute means something on an element: a JavaScript script, a style or a stylesheet link. */\nfunction isPreloadable(element: ElementInfo): boolean {\n if (element.name === \"script\") {\n return isJavaScript(element);\n }\n\n if (element.name === \"style\") {\n return true;\n }\n\n return element.name === \"link\" && element.attribute(\"rel\")?.value === \"stylesheet\";\n}\n\nfunction getMetadata(metadataList: readonly MetadataBase[], htmlMetadata: HtmlMetadata, node: HTMLElement) {\n const isScriptTag = node.tagName === \"SCRIPT\";\n const isStyleTag = node.tagName === \"STYLE\";\n const isStyleSheetLinkTag = node.tagName === \"LINK\" && node.getAttribute(\"rel\") === \"stylesheet\";\n\n // With source\n const source = isScriptTag ? node.getAttribute(\"src\") : isStyleSheetLinkTag ? node.getAttribute(\"href\") : undefined;\n if (source) {\n const [link] = splitHtmlLink(source);\n const filePath = join(dirname(htmlMetadata.filePath), link);\n return metadataList.find(metadata => metadata.filePath === filePath);\n }\n\n // Embedded\n if (isScriptTag || isStyleTag) {\n const metadataID = node.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!metadataID) return;\n\n return htmlMetadata[isScriptTag ? \"scriptsMetadataList\" : \"stylesMetadataList\"].get(metadataID);\n }\n}\n\nfunction createLinkTag(info: NonNullable<ReturnType<typeof getPreloadInfo>>, href: string) {\n return (\n \"<link\" +\n (info.type ? ` type=\"${info.type}\"` : \"\") +\n ` as=\"${info.as}\"` +\n (info.crossorigin ? ` crossorigin` : \"\") +\n ` href=\"${href}\"` +\n ` rel=\"${info.rel}\"` +\n \" />\"\n );\n}\n","import type { Document, HTMLElement } from \"@staticbolt/core\";\n\ninterface ParseHtmlLinksResult {\n get source(): string;\n set source(newValue: string);\n node: HTMLElement;\n}\n\nconst attributeTagsMap = {\n src: new Set([\"img\", \"video\", \"audio\", \"source\", \"track\", \"script\", \"iframe\", \"embed\", \"input\"]),\n srcset: new Set([\"img\", \"source\"]),\n href: new Set([\"a\", \"area\", \"link\", \"base\"]),\n data: new Set([\"object\"]),\n action: new Set([\"form\"]),\n formaction: new Set([\"button\", \"input\"]),\n poster: new Set([\"video\"]),\n cite: new Set([\"blockquote\", \"del\", \"ins\", \"q\"]),\n ping: new Set([\"a\", \"area\"]),\n};\n\n// tag → attributes[] reverse lookup, e.g. \"a\" → [\"href\", \"ping\"]\nconst tagAttributeMap = new Map<string, string[]>();\n\nfor (const [attribute, tags] of Object.entries(attributeTagsMap)) {\n for (const tag of tags) {\n let attributes = tagAttributeMap.get(tag);\n if (!attributes) {\n attributes = [];\n tagAttributeMap.set(tag, attributes);\n }\n\n attributes.push(attribute);\n }\n}\n\nfunction parseSrcset(value: string) {\n const parts = value.split(\",\");\n\n const result: { url: string; descriptor?: string }[] = [];\n\n for (let part of parts) {\n part = part.trim();\n if (part) {\n const [url, descriptor] = part.split(/\\s+/, 2);\n result.push({ url, descriptor });\n }\n }\n\n return result;\n}\n\nfunction stringifySrcset(entries: { url: string; descriptor?: string }[]) {\n let srcset = \"\";\n\n for (const entry of entries) {\n srcset += entry.descriptor ? `, ${entry.url} ${entry.descriptor}` : `, ${entry.url}`;\n }\n\n return srcset;\n}\n\n/** Match placeholders [[ ]] or {{ }} */\nconst placeholderRe = /(?:\\[\\[([^\\]]*[^\\]]*?)\\]\\]|\\{\\{([^}]*[^}]*?)\\}\\})/;\n\n/**\n * Collects elements in document order, cheaper than a `querySelectorAll` with a many-branch selector. Tagless container elements\n * (parsed fragment roots) are descended into but not collected.\n */\nfunction collectElements(node: Document | HTMLElement, out: HTMLElement[]) {\n for (const child of node.childNodes) {\n if (child.nodeType !== 1) continue;\n\n if (child.tagName) {\n out.push(child);\n }\n\n collectElements(child, out);\n }\n}\n\nexport function parseHtmlSources(ast: Document): ParseHtmlLinksResult[] {\n const links: ParseHtmlLinksResult[] = [];\n\n const elements: HTMLElement[] = [];\n collectElements(ast, elements);\n\n for (const node of elements) {\n const attributes = tagAttributeMap.get(node.tagName.toLowerCase());\n if (!attributes) continue;\n\n for (const attribute of attributes) {\n const value = node.getAttribute(attribute);\n if (!value) continue;\n\n if (attribute === \"srcset\") {\n const entries = parseSrcset(value);\n\n for (const [index, entry] of entries.entries()) {\n if (placeholderRe.test(entry.url)) {\n continue;\n }\n\n let decodedEntryUrl: string | undefined;\n\n links.push({\n node,\n get source() {\n return (decodedEntryUrl ??= decodeURIComponent(entry.url));\n },\n set source(newValue: string) {\n const current = parseSrcset(node.getAttribute(\"srcset\") || \"\");\n current[index].url = newValue;\n node.setAttribute(\"srcset\", stringifySrcset(current));\n },\n });\n }\n\n continue;\n }\n\n if (placeholderRe.test(value)) {\n continue;\n }\n\n let decodedValue: string | undefined;\n\n links.push({\n node,\n get source() {\n return (decodedValue ??= decodeURIComponent(value));\n },\n set source(newValue: string) {\n node.setAttribute(attribute, newValue);\n },\n });\n }\n }\n\n return links;\n}\n","import { parse } from \"@staticbolt/node-html-parser\";\n\nimport { valueOrError } from \"../utilities/value-or-error.ts\";\n\nimport type { ParseOptions } from \"@staticbolt/node-html-parser\";\n\nfunction parseHtmlUnsafe(html: string, options: Partial<ParseOptions> = {}) {\n return parse(html, { comment: true, ...options });\n}\n\n/** Parse HTML string and return the root node */\nconst parseHtml = valueOrError(parseHtmlUnsafe);\n\nexport { parseHtml };\n","import { isScriptType, TYPESCRIPT_TYPE } from \"../../../helpers/is-script-type.ts\";\nimport { parseHtml } from \"../../../parsers/html-parser.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../../types/common.ts\";\nimport { METADATA_TYPES } from \"../../../types/metadata.ts\";\nimport { isScriptMetadata, isStyleMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { hashContent } from \"../../../utilities/utilities.ts\";\n\nimport type { ValueOrError } from \"../../../utilities/value-or-error.ts\";\nimport type { App, HtmlMetadata, ScriptMetadata, StyleMetadata } from \"@staticbolt/core\";\n\ntype HtmlLoaderResult = ValueOrError<HtmlMetadata>;\n\nexport async function htmlLoader(this: App, relativePath: string, code: string): Promise<HtmlLoaderResult> {\n const [rootElement, parseError] = parseHtml(code);\n if (parseError !== null) {\n parseError.message = `Failed to parse HTML file \"${relativePath}\"\\n` + parseError.message;\n return [null, parseError];\n }\n\n // Script loader\n const scriptsMetadataList = new Map<string, ScriptMetadata>();\n\n const scripts = rootElement.querySelectorAll(\"script\");\n for (const script of scripts) {\n // For the editor; every script is parsed as TypeScript anyway, and a browser would skip the type\n if (script.getAttribute(\"type\")?.toLowerCase() === TYPESCRIPT_TYPE) {\n script.removeAttribute(\"type\");\n\n // The type slot is taken, so a module says so with its own attribute\n if (script.hasAttribute(\"module\")) {\n script.removeAttribute(\"module\");\n script.setAttribute(\"type\", \"module\");\n }\n }\n\n const hasSource = script.hasAttribute(\"src\");\n if (hasSource) continue;\n\n const scriptType = script.getAttribute(\"type\");\n if (!isScriptType(scriptType)) {\n continue;\n }\n\n const scriptCode = script.rawText;\n if (!scriptCode) {\n return [null, new Error(\"No code found in <script> tag\")];\n }\n\n const scriptMetadata = await this.load(relativePath, { code: scriptCode, type: \"js\" });\n if (!isScriptMetadata(scriptMetadata)) {\n return [null, new Error(\"Script loader returned non-script metadata\")];\n }\n\n const isTypeModule = script.getAttribute(\"type\") === \"module\";\n scriptMetadata.module = isTypeModule;\n\n const astID = hashContent(scriptCode);\n script.setAttribute(CUSTOM_ATTRIBUTES.MetadataID, astID);\n scriptsMetadataList.set(astID, scriptMetadata);\n }\n\n // Style loader\n const stylesMetadataList = new Map<string, StyleMetadata>();\n\n const styles = rootElement.querySelectorAll(\"style\");\n for (const style of styles) {\n const styleCode = style.rawText;\n if (!styleCode) continue;\n\n const styleMetadata = await this.load(relativePath, { code: styleCode, type: \"css\" });\n if (!isStyleMetadata(styleMetadata)) {\n return [null, new Error(\"Style loader returned non-style metadata\")];\n }\n\n const astID = hashContent(styleCode);\n style.setAttribute(CUSTOM_ATTRIBUTES.MetadataID, astID);\n stylesMetadataList.set(astID, styleMetadata);\n }\n\n const htmlMetadata: HtmlMetadata = {\n type: METADATA_TYPES.HTML,\n ast: rootElement,\n filePath: relativePath,\n id: relativePath,\n scriptsMetadataList,\n stylesMetadataList,\n directDependencies: new Set(),\n };\n\n return [htmlMetadata, null];\n}\n","import { TYPESCRIPT_TYPE } from \"../../../helpers/is-script-type.ts\";\nimport { isTypeScriptScript } from \"../../../helpers/lsp-checks.ts\";\n\nimport type { EmbeddedLanguage, HTMLDataV1 } from \"@staticbolt/core\";\n\n/**\n * The bodies of the inline scripts marked `type=\"${TYPESCRIPT_TYPE}\"`, served as TypeScript through the project's own TypeScript,\n * so they see the browser the way the project's tsconfig describes it. A plugin that runs a script elsewhere claims it over\n * this.\n */\nexport function embeddedLanguages(): EmbeddedLanguage[] {\n return [\n {\n name: \"scripts\",\n filter: () => true,\n findRegions: document =>\n document.select(\"script\").flatMap(script => {\n if (!isTypeScriptScript(script) || script.has(\"src\") || !script.contentRange) return [];\n return { ...script.contentRange, isModule: script.has(\"module\") };\n }),\n isColouredByEditor: true,\n },\n ];\n}\n\n/** The attributes the plugin adds to `<script>`, for completion and hover. */\nexport function htmlData(): HTMLDataV1 {\n return {\n version: 1.1,\n tags: [\n {\n name: \"script\",\n attributes: [\n {\n name: \"type\",\n description:\n `\\`${TYPESCRIPT_TYPE}\\` marks the script as TypeScript for the editor: Prettier formats it as such,` +\n \" the staticbolt language server serves it through the project's TypeScript, and the build drops the type.\",\n values: [{ name: TYPESCRIPT_TYPE }],\n },\n {\n name: \"module\",\n description: `With \\`type=\"${TYPESCRIPT_TYPE}\"\\`, whose type slot is taken: the build prints the script as \\`type=\"module\"\\`.`,\n valueSet: \"v\",\n },\n ],\n },\n ],\n };\n}\n","import { parseHtmlSources } from \"../../../ast-utilities/html-utils/parse-html-sources.ts\";\nimport { isScriptType } from \"../../../helpers/is-script-type.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../../types/common.ts\";\nimport { splitHtmlLink } from \"../../../utilities/html-links.ts\";\nimport { isHtmlMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { extname, join, relative } from \"../../../utilities/path.ts\";\nimport { printFmtError } from \"../../../utilities/print-formatted-error.ts\";\nimport { cloneObject } from \"../../../utilities/utilities.ts\";\nimport { formatHtml, formatHtmlPass, minifyHtml, minifyHtmlPass } from \"./deferred.ts\";\nimport { htmlLoader } from \"./html-loader.ts\";\nimport { embeddedLanguages, htmlData } from \"./lsp.ts\";\n\nimport type { FormatHtmlPayload } from \"./deferred.ts\";\nimport type { HTMLElement, MetadataSource, Plugin, ScriptMetadata, StyleMetadata } from \"@staticbolt/core\";\n\nexport interface CoreHtmlPluginOptions {\n /**\n * The attribute name to use for minifying script and style tags.\n *\n * @default \"minify\"\n */\n minifyAttribute?: string;\n}\n\n/**\n * The HTML half of the core pipeline: parses a page into a document, splits its \"<script>\" and \"<style>\" tags into metadata of\n * their own, and prints the whole thing back out.\n *\n * Notes:\n *\n * - Each inline script or style is tied to its tag by an internal id attribute, which is stripped from the printed output.\n * - Sources come from the page's links plus the sources of every extracted script and style, so an import inside an inline script\n * counts as a dependency of the page.\n * - A \"minify\" attribute on a single tag minifies just that tag regardless of the build settings, and when the rest of the page is\n * formatted such a tag is preceded by a \"prettier-ignore\" comment so it stays that way.\n * - Rebasing a page carries its inline scripts and styles along with it.\n */\nexport function coreHtmlPlugin(options: CoreHtmlPluginOptions = {}): Plugin {\n const minifyAttribute = options.minifyAttribute ?? \"minify\";\n const ignoreFormatComment = \"\\n<!-- prettier-ignore -->\\n\";\n\n return {\n name: \"core-html-metadata\",\n\n async load(content, relativePath, { type }) {\n const [link] = splitHtmlLink(relativePath);\n\n type ??= extname(link).slice(1);\n\n if (type !== \"html\") {\n return;\n }\n\n const [fileMetadata, metadataError] = await htmlLoader.call(this, link, content);\n if (metadataError) {\n printFmtError(metadataError, { function: coreHtmlPlugin });\n return;\n }\n\n return fileMetadata;\n },\n\n clone(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const cloned = cloneObject(metadata);\n\n cloned.ast = metadata.ast.clone();\n\n cloned.scriptsMetadataList = new Map<string, ScriptMetadata>();\n for (const [metadataID, scriptMetadata] of metadata.scriptsMetadataList) {\n cloned.scriptsMetadataList.set(metadataID, this.clone(scriptMetadata));\n }\n\n cloned.stylesMetadataList = new Map<string, StyleMetadata>();\n for (const [metadataID, cssMetadata] of metadata.stylesMetadataList) {\n cloned.stylesMetadataList.set(metadataID, this.clone(cssMetadata));\n }\n\n return cloned;\n },\n\n async stringify(metadata, { format, minify, defer }) {\n if (!isHtmlMetadata(metadata)) return;\n\n const nodeIdMap = new Map<HTMLElement, string>();\n\n const scriptsAndStyles = metadata.ast.querySelectorAll(\"script,style\");\n\n for (const node of scriptsAndStyles) {\n const hasMinifyAttribute = node.hasAttribute(minifyAttribute);\n const shouldMinify = minify || hasMinifyAttribute;\n const isScript = node.tagName === \"SCRIPT\";\n\n node.removeAttribute(minifyAttribute);\n\n const scriptType = node.getAttribute(\"type\");\n if (isScript && !isScriptType(scriptType)) {\n continue;\n }\n\n const metadataID = node.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!metadataID) continue;\n\n // Remove metadata id temporarily\n nodeIdMap.set(node, metadataID);\n node.removeAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n\n const tagMetadata = metadata[isScript ? \"scriptsMetadataList\" : \"stylesMetadataList\"].get(metadataID);\n if (!tagMetadata) continue;\n\n const code = await this.stringify(tagMetadata, { format: format && !shouldMinify, minify: shouldMinify });\n if (!code) continue;\n\n node.textContent = code;\n\n if (format && hasMinifyAttribute) {\n node.replaceWith(ignoreFormatComment + node.outerHTML);\n }\n }\n\n const code = metadata.ast.toString();\n\n // Restore metadata ids\n for (const [node, metadataID] of nodeIdMap) {\n node.setAttribute(CUSTOM_ATTRIBUTES.MetadataID, metadataID);\n }\n\n if (format) {\n const payload: FormatHtmlPayload = { filePath: join(this.root, metadata.filePath) };\n\n if (defer) {\n defer(formatHtmlPass(payload));\n return code;\n }\n\n try {\n return await formatHtml(code, payload);\n } catch {\n this.log.error(\"Failed to format html\", metadata.filePath);\n return;\n }\n }\n\n if (minify) {\n if (defer) {\n defer(minifyHtmlPass());\n return code;\n }\n\n try {\n return await minifyHtml(code);\n } catch {\n this.log.error(\"Failed to minify html\", metadata.filePath);\n return;\n }\n }\n\n return code;\n },\n\n async sourcesProvider(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n // HTML Links\n const htmlSources: MetadataSource[] = parseHtmlSources(metadata.ast);\n\n const scriptsAndStyles = metadata.ast.querySelectorAll(\"script,style\");\n const scripts = scriptsAndStyles.filter(node => node.tagName === \"SCRIPT\");\n const styles = scriptsAndStyles.filter(node => node.tagName === \"STYLE\");\n\n // Embedded scripts\n for (const script of scripts) {\n const id = script.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!id) continue;\n\n const scriptMetadata = metadata.scriptsMetadataList.get(id);\n if (!scriptMetadata) continue;\n\n const requestedSources = await this.requestSources(scriptMetadata);\n htmlSources.push(...requestedSources);\n }\n\n // Embedded styles\n for (const style of styles) {\n const id = style.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!id) continue;\n\n const styleMetadata = metadata.stylesMetadataList.get(id);\n if (!styleMetadata) continue;\n\n const requestedSources = await this.requestSources(styleMetadata);\n htmlSources.push(...requestedSources);\n }\n\n return htmlSources;\n },\n\n onMetadataRebase(metadata, _, newAbsolutePath) {\n if (!isHtmlMetadata(metadata)) return;\n\n metadata.filePath = relative(this.root, newAbsolutePath);\n\n for (const [, scriptMetadata] of metadata.scriptsMetadataList) {\n scriptMetadata.filePath = metadata.filePath;\n }\n\n for (const [, cssMetadata] of metadata.stylesMetadataList) {\n cssMetadata.filePath = metadata.filePath;\n }\n },\n\n lspEmbeddedLanguages() {\n return embeddedLanguages();\n },\n\n lspHtmlData() {\n return htmlData();\n },\n };\n}\n","import rehypeExternalLinks from \"rehype-external-links\";\nimport rehypeSlug from \"rehype-slug\";\nimport rehypeStringify from \"rehype-stringify\";\nimport { remark } from \"remark\";\nimport remarkFrontmatter from \"remark-frontmatter\";\nimport remarkGfm from \"remark-gfm\";\nimport remarkRehype from \"remark-rehype\";\nimport remarkSmartypants from \"remark-smartypants\";\nimport { unified } from \"unified\";\nimport { visit } from \"unist-util-visit\";\nimport { parse as parseYaml } from \"yaml\";\n\nimport { METADATA_TYPES, type MarkdownMetadata } from \"../../../types/metadata.ts\";\nimport { splitHtmlLink } from \"../../../utilities/html-links.ts\";\nimport { isMarkdownMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { extname, join } from \"../../../utilities/path.ts\";\nimport { printFmtError } from \"../../../utilities/print-formatted-error.ts\";\nimport { cloneObject } from \"../../../utilities/utilities.ts\";\nimport { formatMarkdown, formatMarkdownPass } from \"./deferred.ts\";\n\nimport type { FormatMarkdownPayload } from \"./deferred.ts\";\nimport type { ValueOrError } from \"../../../utilities/value-or-error.ts\";\nimport type { MarkdownAst, MetadataSource, Plugin } from \"@staticbolt/core\";\nimport type { Pluggable } from \"unified\";\n\nexport interface CoreMarkdownPluginOptions {\n /**\n * Remark plugins.\n *\n * **Default**:\n *\n * 1. `remark-frontmatter`\n * 2. `remark-gfm`\n * 3. `remark-smartypants`\n */\n remarkPlugins?: Pluggable[];\n\n /**\n * Rehype plugins.\n *\n * **Default**:\n *\n * 1. `remark-rehype`\n * 2. `rehype-slug`\n * 3. `rehype-autolink-headings`\n * 4. `rehype-external-links`\n * 5. `rehype-stringify`\n */\n rehypePlugins?: Pluggable[];\n\n /**\n * Whether to allow HTML in markdown.\n *\n * @default false\n */\n allowDangerousHtml?: boolean;\n}\n\n/**\n * The markdown half of the core pipeline: parses \".md\" files with remark, exposes their YAML front matter, and renders them to\n * HTML on demand through \"ast.render()\".\n *\n * The remark chain is front matter, GFM and smartypants, then \"remarkPlugins\"; rendering runs remark-rehype, heading slugs and\n * external links (opened in a new tab, with \"noopener noreferrer\"), then \"rehypePlugins\".\n *\n * Notes:\n *\n * - Raw HTML inside the markdown is dropped unless \"allowDangerousHtml\" is on.\n * - Front matter is only read from the very first node, and only when it is a YAML block.\n * - Links and images are reported as sources, so they get resolved and rebased; anything inside raw HTML is not.\n * - Printing this metadata gives markdown back, not HTML.\n */\nexport function coreMarkdownPlugin(options: CoreMarkdownPluginOptions = {}): Plugin {\n const shouldAllowDangerousHtml = options.allowDangerousHtml ?? false;\n\n const processor = remark()\n .use(remarkFrontmatter, [\"yaml\"])\n .use(remarkGfm)\n .use(remarkSmartypants)\n .use(options.remarkPlugins ?? []);\n\n // HTML renderer (mdast → html), shared across all ast instances\n const htmlProcessor = unified()\n .use(remarkRehype, { allowDangerousHtml: shouldAllowDangerousHtml })\n .use(rehypeSlug)\n .use(rehypeExternalLinks, { target: \"_blank\", rel: [\"noopener\", \"noreferrer\"] })\n .use(options.rehypePlugins ?? [])\n .use(rehypeStringify, { allowDangerousHtml: shouldAllowDangerousHtml });\n\n async function parseMarkdown(code: string): Promise<ValueOrError<MarkdownAst>> {\n try {\n const root = processor.parse(code);\n await processor.run(root);\n\n // Extract frontmatter from the first node if it's a yaml block\n const frontmatter: Record<string, string> = {};\n // eslint-disable-next-line unicorn/better-dom-traversing\n const firstNode = root.children[0];\n if (firstNode?.type === \"yaml\") {\n const parsed = (parseYaml(firstNode.value) as Record<string, string>) ?? {};\n Object.assign(frontmatter, parsed);\n }\n\n const ast: MarkdownAst = {\n root,\n frontmatter,\n render: async () => {\n const hast = await htmlProcessor.run(root);\n return htmlProcessor.stringify(hast);\n },\n };\n\n return [ast, null];\n } catch (error) {\n return [null, error instanceof Error ? error : new Error(String(error))];\n }\n }\n\n return {\n name: \"core-markdown-metadata\",\n\n async load(content, relativePath, { type }) {\n const [link] = splitHtmlLink(relativePath);\n\n type ??= extname(link).slice(1);\n\n if (type !== \"md\") {\n return;\n }\n\n const [markdownAst, parseError] = await parseMarkdown(content);\n if (parseError) {\n printFmtError(parseError, relativePath);\n return;\n }\n\n const markdownMetadata: MarkdownMetadata = {\n type: METADATA_TYPES.Markdown,\n ast: markdownAst,\n filePath: link,\n id: link,\n directDependencies: new Set(),\n };\n\n return markdownMetadata;\n },\n\n clone(metadata) {\n if (!isMarkdownMetadata(metadata)) return;\n\n const cloned = cloneObject(metadata);\n const clonedRoot = structuredClone(metadata.ast.root);\n\n cloned.ast = {\n root: clonedRoot,\n frontmatter: { ...metadata.ast.frontmatter },\n render: async () => {\n const hast = await htmlProcessor.run(clonedRoot);\n return htmlProcessor.stringify(hast);\n },\n };\n\n return cloned;\n },\n\n async stringify(metadata, { format, defer }) {\n if (!isMarkdownMetadata(metadata)) return;\n\n const code = processor.stringify(metadata.ast.root);\n\n if (format) {\n const payload: FormatMarkdownPayload = { filePath: join(this.root, metadata.filePath) };\n\n if (defer) {\n defer(formatMarkdownPass(payload));\n return code;\n }\n\n try {\n return await formatMarkdown(code, payload);\n } catch {\n this.log.error(\"Failed to format markdown\", metadata.filePath);\n return;\n }\n }\n\n return code;\n },\n\n sourcesProvider(metadata) {\n if (!isMarkdownMetadata(metadata)) return;\n\n const sources: MetadataSource[] = [];\n\n visit(metadata.ast.root, node => {\n if (node.type === \"link\" && node.url) {\n sources.push({\n get source() {\n return node.url;\n },\n set source(value: string) {\n node.url = value;\n },\n });\n\n return;\n }\n\n if (node.type === \"image\" && node.url) {\n sources.push({\n get source() {\n return node.url;\n },\n set source(value: string) {\n node.url = value;\n },\n });\n\n return;\n }\n\n // TODO: parse html and extract sources\n // if (node.type === \"html\" && node.value) {\n // }\n });\n\n return sources;\n },\n };\n}\n","import * as t from \"@babel/types\";\n\nimport type { BabelAst } from \"@staticbolt/core\";\n\nexport type Kind = \"value\" | \"type\" | \"typeof\" | \"dynamic\" | \"url\";\nexport type Kinds = Kind[];\n\ninterface Options {\n ast: BabelAst;\n filePath: string;\n}\n\ninterface ParseJsLinksResult {\n kind: Kind;\n node: t.Node;\n get source(): string;\n set source(newValue: string);\n}\n\nexport function parseScriptSources({ ast }: Options): ParseJsLinksResult[] {\n const result: ParseJsLinksResult[] = [];\n\n t.traverseFast(ast, node => {\n // import default from \"source\";\n // import { value } from \"source\";\n // import * as value from \"source\";\n if (t.isImportDeclaration(node)) {\n if (!t.isStringLiteral(node.source)) return;\n\n const kind = node.importKind ?? \"value\";\n if (kind === \"type\") return;\n\n const source = node.source.value;\n\n if (source.startsWith(\"node:\")) {\n return;\n }\n\n result.push({\n kind,\n node,\n get source() {\n return source;\n },\n set source(newValue) {\n if (node) {\n node.source = t.stringLiteral(newValue);\n }\n },\n });\n\n return;\n }\n\n // export * from \"source\";\n if (t.isExportAllDeclaration(node)) {\n if (!node.source.value) return;\n\n const kind = node.exportKind ?? \"value\";\n if (kind === \"type\") return;\n\n result.push({\n kind,\n node,\n get source() {\n return node.source.value;\n },\n set source(newValue) {\n node.source = t.stringLiteral(newValue);\n },\n });\n return;\n }\n\n // export default from \"source\";\n // export { value } from \"source\";\n // export * as value from \"source\";\n if (t.isExportNamedDeclaration(node)) {\n if (!t.isStringLiteral(node.source)) return;\n\n const kind = node.exportKind ?? \"value\";\n if (kind === \"type\") return;\n\n const source = node.source.value;\n\n result.push({\n kind,\n node,\n get source() {\n return source;\n },\n set source(newValue) {\n node.source = t.stringLiteral(newValue);\n },\n });\n\n return;\n }\n\n // await import(\"source\");\n if (t.isCallExpression(node)) {\n if (!t.isImport(node.callee) || !t.isStringLiteral(node.arguments[0])) return;\n\n const setSource = (newValue: string) => {\n node.arguments[0] = t.stringLiteral(newValue);\n };\n\n const source = node.arguments[0].value;\n\n result.push({\n kind: \"dynamic\",\n node,\n get source() {\n return source;\n },\n set source(newValue) {\n setSource(newValue);\n },\n });\n\n return;\n }\n\n // New URL(\"source\", ...)\n if (t.isNewExpression(node)) {\n if (!t.isIdentifier(node.callee, { name: \"URL\" })) return;\n\n const firstArgument = node.arguments[0];\n if (!t.isStringLiteral(firstArgument)) {\n return;\n }\n\n const setSource = (newValue: string) => {\n node.arguments[0] = t.stringLiteral(newValue);\n };\n\n result.push({\n kind: \"url\",\n node,\n get source() {\n return firstArgument.value;\n },\n set source(newValue) {\n setSource(newValue);\n },\n });\n\n return;\n }\n });\n\n return result;\n}\n","import * as babelParser from \"@babel/parser\";\n\nimport { valueOrError } from \"../utilities/value-or-error.ts\";\n\nexport interface ParseJsOptions {\n code: string;\n filePath: string;\n sourceType?: \"script\" | \"module\" | \"unambiguous\";\n}\n\nfunction parseJsUnsafe({ code, filePath, sourceType }: ParseJsOptions) {\n return babelParser.parse(code, {\n plugins: [\"typescript\", \"jsx\", \"decorators\", \"decoratorAutoAccessors\"],\n sourceType: sourceType ?? \"unambiguous\",\n sourceFilename: filePath,\n });\n}\n\n/** Parse JS string and return the AST */\nconst parseJs = valueOrError(parseJsUnsafe);\n\nexport { parseJs };\n","import { parseJs } from \"../../../parsers/js-parser.ts\";\nimport { METADATA_TYPES, type ScriptMetadata } from \"../../../types/metadata.ts\";\n\nimport type { ValueOrError } from \"../../../utilities/value-or-error.ts\";\nimport type { App } from \"@staticbolt/core\";\n\ntype TypescriptLoaderResults = ValueOrError<ScriptMetadata>;\n\nexport function scriptLoader(this: App, relativePath: string, code: string): TypescriptLoaderResults {\n const [ast, parseError] = parseJs({ code, filePath: relativePath });\n if (parseError !== null) {\n parseError.message = `Failed to parse JS file \"${relativePath}\"\\n` + parseError.message;\n return [null, parseError];\n }\n\n const scriptMetadata: ScriptMetadata = {\n type: METADATA_TYPES.Script,\n ast,\n filePath: relativePath,\n id: relativePath,\n directDependencies: new Set(),\n module: true,\n };\n\n return [scriptMetadata, null];\n}\n","import _generator from \"@babel/generator\";\nimport * as t from \"@babel/types\";\n\nimport { parseScriptSources } from \"../../../ast-utilities/babel-utils/parse-script-srouces.ts\";\nimport { splitHtmlLink } from \"../../../utilities/html-links.ts\";\nimport { isScriptMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { extname, join } from \"../../../utilities/path.ts\";\nimport { printFmtError } from \"../../../utilities/print-formatted-error.ts\";\nimport { cloneObject } from \"../../../utilities/utilities.ts\";\nimport { formatScript, formatScriptPass, minifyScript, minifyScriptPass } from \"./deferred.ts\";\nimport { scriptLoader } from \"./script-loader.ts\";\n\nimport type { FormatScriptPayload, MinifyScriptPayload } from \"./deferred.ts\";\nimport type { Plugin } from \"@staticbolt/core\";\n\nconst generator = typeof _generator === \"function\" ? _generator : _generator.default;\n\n/**\n * The script half of the core pipeline: loads JavaScript and TypeScript files (\".js\", \".mjs\", \".cjs\", \".jsx\", \".ts\", \".mts\",\n * \".cts\", \".tsx\") into a Babel AST, prints them back out, and reports their imports as sources.\n *\n * Notes:\n *\n * - Loading only parses. Stripping types and JSX is transformJsPlugin's job.\n * - Printing goes through Babel; \"format\" hands the result to prettier and \"minify\" to SWC, which is told whether the file is a\n * module or a classic script.\n */\nexport function coreScriptPlugin(): Plugin {\n const jsExtensions = new Set([\".js\", \".mjs\", \".cjs\", \".jsx\", \".ts\", \".mts\", \".cts\", \".tsx\"]);\n\n return {\n name: \"core-script-metadata\",\n\n load(content, relativePath, { type }) {\n const [link] = splitHtmlLink(relativePath);\n\n type ??= extname(link).slice(1);\n\n if (!jsExtensions.has(`.${type}`)) {\n return;\n }\n\n const [fileMetadata, metadataError] = scriptLoader.call(this, link, content);\n if (metadataError) {\n printFmtError(metadataError, { function: coreScriptPlugin });\n return;\n }\n\n return fileMetadata;\n },\n\n clone(metadata) {\n if (!isScriptMetadata(metadata)) return;\n\n const cloned = cloneObject(metadata);\n cloned.ast = t.cloneNode(cloned.ast, true);\n\n return cloned;\n },\n\n async stringify(metadata, { format, minify, defer }) {\n if (!isScriptMetadata(metadata)) return;\n\n const code = generator(metadata.ast, { jsescOption: { minimal: true } }).code;\n\n if (format) {\n const payload: FormatScriptPayload = { filePath: join(this.root, metadata.filePath) };\n\n if (defer) {\n defer(formatScriptPass(payload));\n return code;\n }\n\n try {\n return await formatScript(code, payload);\n } catch {\n this.log.error(\"Failed to format script\", metadata.filePath);\n return;\n }\n }\n\n if (minify) {\n const payload: MinifyScriptPayload = { module: metadata.module };\n\n if (defer) {\n defer(minifyScriptPass(payload));\n return code;\n }\n\n try {\n return await minifyScript(code, payload);\n } catch (minifyError) {\n printFmtError(\"Failed to minify script\", minifyError as Error, { filePath: metadata.filePath });\n return;\n }\n }\n\n return code;\n },\n\n sourcesProvider(metadata) {\n if (!isScriptMetadata(metadata)) return;\n\n return parseScriptSources({ ast: metadata.ast, filePath: metadata.filePath });\n },\n };\n}\n","import { parseImportPrelude } from \"./import-prelude.ts\";\n\nimport type { PostcssAst } from \"@staticbolt/core\";\nimport type { AtRule, Declaration } from \"postcss\";\n\nconst cssUrlRe = /url\\((['\"]?)(.+?)\\1\\)/gm;\n\ninterface CssUrlHandle {\n get source(): string;\n set source(newSource: string);\n node: Declaration | AtRule;\n}\n\nexport function parseStyleSources(ast: PostcssAst): CssUrlHandle[] {\n const handles: CssUrlHandle[] = [];\n\n ast.walkDecls(declaration => {\n for (const match of declaration.value.matchAll(cssUrlRe)) {\n const source = match[2];\n if (!source) continue;\n\n handles.push({\n node: declaration,\n get source() {\n return source;\n },\n set source(newSource) {\n declaration.value = declaration.value.replace(source, () => newSource);\n },\n });\n }\n });\n\n ast.walkAtRules(/^import$/i, atRule => {\n const prelude = parseImportPrelude(atRule.params);\n if (!prelude?.url) return;\n\n const { urlStart } = prelude;\n let { url, urlEnd } = prelude;\n\n handles.push({\n node: atRule,\n get source() {\n return url;\n },\n set source(newSource) {\n atRule.params = atRule.params.slice(0, urlStart) + newSource + atRule.params.slice(urlEnd);\n urlEnd = urlStart + newSource.length;\n url = newSource;\n },\n });\n });\n\n return handles;\n}\n","import { parseStyleSources } from \"../../../ast-utilities/postcss-utils/parse-style-srouces.ts\";\nimport { isStyleMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { extname, join } from \"../../../utilities/path.ts\";\nimport { printFmtError } from \"../../../utilities/print-formatted-error.ts\";\nimport { cloneObject } from \"../../../utilities/utilities.ts\";\nimport { formatStyle, formatStylePass, minifyStyle, minifyStylePass } from \"./deferred.ts\";\nimport { styleLoader } from \"./style-loader.ts\";\n\nimport type { FormatStylePayload, MinifyStylePayload } from \"./deferred.ts\";\nimport type { Plugin } from \"@staticbolt/core\";\nimport type { Targets } from \"lightningcss\";\n\n/**\n * The style half of the core pipeline: loads \".css\" files into a PostCSS AST, prints them back out, and reports their \"@import\"\n * and \"url()\" references as sources.\n *\n * Notes:\n *\n * - \"format\" hands the result to prettier; \"minify\" runs Lightning CSS against the project's browserslist, resolved once and reused\n * for the rest of the build.\n */\nexport function coreStylePlugin(): Plugin {\n let targets: Targets | undefined;\n\n return {\n name: \"core-style-metadata\",\n\n load(content, relativePath, { type }) {\n type ??= extname(relativePath).slice(1);\n\n if (type !== \"css\") {\n return;\n }\n\n const [fileMetadata, metadataError] = styleLoader.call(this, relativePath, content);\n if (metadataError) {\n printFmtError(metadataError, { function: coreStylePlugin });\n return;\n }\n\n return fileMetadata;\n },\n\n clone(metadata) {\n if (!isStyleMetadata(metadata)) return;\n\n const cloned = cloneObject(metadata);\n cloned.ast = metadata.ast.clone();\n\n return cloned;\n },\n\n async stringify(metadata, { format, minify, defer }) {\n if (!isStyleMetadata(metadata)) return;\n\n const code = metadata.ast.toString();\n\n if (format) {\n const payload: FormatStylePayload = { filePath: join(this.root, metadata.filePath) };\n\n if (defer) {\n defer(formatStylePass(payload));\n return code;\n }\n\n try {\n return await formatStyle(code, payload);\n } catch {\n this.log.error(\"Failed to format style\", metadata.filePath);\n return;\n }\n }\n\n if (minify) {\n if (targets === undefined) {\n const { browserslistToTargets } = await import(\"lightningcss\");\n targets = browserslistToTargets(this.browserslist);\n }\n\n const payload: MinifyStylePayload = { filePath: metadata.filePath, targets };\n\n if (defer) {\n defer(minifyStylePass(payload));\n return code;\n }\n\n try {\n return await minifyStyle(code, payload);\n } catch {\n this.log.error(\"Failed to minify style\", metadata.filePath);\n return;\n }\n }\n\n return code;\n },\n\n sourcesProvider(metadata) {\n if (!isStyleMetadata(metadata)) return;\n\n return parseStyleSources(metadata.ast);\n },\n };\n}\n","import { parseHtml } from \"../../../parsers/html-parser.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../../types/common.ts\";\nimport { METADATA_TYPES, type StyleMetadata, type SvgMetadata } from \"../../../types/metadata.ts\";\nimport { isStyleMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { hashContent } from \"../../../utilities/utilities.ts\";\n\nimport type { ValueOrError } from \"../../../utilities/value-or-error.ts\";\nimport type { App } from \"@staticbolt/core\";\n\ntype SvgLoaderResult = ValueOrError<SvgMetadata>;\n\nexport async function svgLoader(this: App, relativePath: string, code: string): Promise<SvgLoaderResult> {\n // Parse HTML to AST (HTML root element)\n const [rootElement, parseError] = parseHtml(code);\n if (parseError !== null) {\n parseError.message = `Failed to parse SVG file \"${relativePath}\"\\n` + parseError.message;\n return [null, parseError];\n }\n\n // Style loader\n const stylesMetadataList = new Map<string, StyleMetadata>();\n\n const styles = rootElement.querySelectorAll(\"style\");\n for (const style of styles) {\n const styleCode = style.textContent;\n if (!styleCode) continue;\n\n const styleMetadata = await this.load(relativePath, { code: styleCode, type: \"css\" });\n if (!isStyleMetadata(styleMetadata)) {\n return [null, new Error(\"Style loader returned non-CSS metadata\")];\n }\n\n const astID = hashContent(styleCode);\n style.setAttribute(CUSTOM_ATTRIBUTES.MetadataID, astID);\n stylesMetadataList.set(astID, styleMetadata);\n }\n\n const svgMetadata: SvgMetadata = {\n type: METADATA_TYPES.SVG,\n ast: rootElement,\n filePath: relativePath,\n id: relativePath,\n stylesMetadataList,\n directDependencies: new Set(),\n };\n\n return [svgMetadata, null];\n}\n","import { parseHtmlSources } from \"../../../ast-utilities/html-utils/parse-html-sources.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../../types/common.ts\";\nimport { splitHtmlLink } from \"../../../utilities/html-links.ts\";\nimport { isSvgMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { extname, join } from \"../../../utilities/path.ts\";\nimport { printFmtError } from \"../../../utilities/print-formatted-error.ts\";\nimport { cloneObject } from \"../../../utilities/utilities.ts\";\nimport { formatSvg, formatSvgPass, minifySvg, minifySvgPass } from \"./deferred.ts\";\nimport { svgLoader } from \"./svg-loader.ts\";\n\nimport type { FormatSvgPayload } from \"./deferred.ts\";\nimport type { MetadataSource, Plugin, StyleMetadata } from \"@staticbolt/core\";\n\n/**\n * The SVG half of the core pipeline: parses \".svg\" files as documents, splits their \"<style>\" tags into metadata of their own,\n * and prints them back out.\n *\n * Notes:\n *\n * - Sources come from the document's own links plus the sources of the extracted styles.\n * - \"format\" runs prettier as HTML, and \"minify\" goes through the HTML minifier.\n */\nexport function coreSvgPlugin(): Plugin {\n return {\n name: \"core-svg-metadata\",\n\n async load(content, relativePath, { type }) {\n const [link] = splitHtmlLink(relativePath);\n\n type ??= extname(link).slice(1);\n\n if (type !== \"svg\") {\n return;\n }\n\n const [fileMetadata, metadataError] = await svgLoader.call(this, link, content);\n if (metadataError) {\n printFmtError(metadataError, { function: coreSvgPlugin });\n return;\n }\n\n return fileMetadata;\n },\n\n clone(metadata) {\n if (!isSvgMetadata(metadata)) return;\n\n const cloned = cloneObject(metadata);\n\n cloned.ast = metadata.ast.clone();\n\n cloned.stylesMetadataList = new Map<string, StyleMetadata>();\n for (const [metadataID, cssMetadata] of metadata.stylesMetadataList) {\n cloned.stylesMetadataList.set(metadataID, this.clone(cssMetadata));\n }\n\n return cloned;\n },\n\n async stringify(metadata, { format, minify, defer }) {\n if (!isSvgMetadata(metadata)) return;\n\n const styles = metadata.ast.querySelectorAll(\"style\");\n\n for (const node of styles) {\n const id = node.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!id) continue;\n\n const styleMetadata = metadata.stylesMetadataList.get(id);\n if (!styleMetadata) continue;\n\n node.textContent = await this.stringify(styleMetadata);\n }\n\n const code = metadata.ast.toString();\n\n if (format) {\n const payload: FormatSvgPayload = { filePath: join(this.root, metadata.filePath) };\n\n if (defer) {\n defer(formatSvgPass(payload));\n return code;\n }\n\n try {\n return await formatSvg(code, payload);\n } catch {\n this.log.error(\"Failed to format svg\", metadata.filePath);\n return;\n }\n }\n\n if (minify) {\n if (defer) {\n defer(minifySvgPass());\n return code;\n }\n\n try {\n return await minifySvg(code);\n } catch {\n this.log.error(\"Failed to minify svg\", metadata.filePath);\n return;\n }\n }\n\n return code;\n },\n\n async sourcesProvider(metadata) {\n if (!isSvgMetadata(metadata)) return;\n\n // HTML Links\n const htmlSources = parseHtmlSources(metadata.ast);\n\n const stylesSources: MetadataSource[] = [];\n\n // Embedded styles\n const styles = metadata.ast.querySelectorAll(\"style\");\n for (const style of styles) {\n const id = style.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!id) continue;\n\n const styleMetadata = metadata.stylesMetadataList.get(id);\n if (!styleMetadata) continue;\n\n const requestedSources = await this.requestSources(styleMetadata);\n stylesSources.push(...requestedSources);\n }\n\n return [...htmlSources, ...stylesSources];\n },\n };\n}\n","import json5 from \"json5\";\n\nimport { METADATA_TYPES, type WebManifestMetadata } from \"../../../types/metadata.ts\";\nimport { valueOrError, type ValueOrError } from \"../../../utilities/value-or-error.ts\";\n\nimport type { App } from \"@staticbolt/core\";\n\nexport function webManifestLoader(this: App, relativePath: string, code: string): ValueOrError<WebManifestMetadata> {\n const [manifestData, manifestError] = valueOrError(json5.parse<WebManifestMetadata[\"ast\"]>)(code);\n if (manifestError !== null) {\n return [null, manifestError];\n }\n\n // check if the manifest is valid\n if (!manifestData.name || !manifestData.short_name || !manifestData.icons) {\n return [null, new Error(`Invalid manifest.json file: ${relativePath}`)];\n }\n\n const webManifestMetadata: WebManifestMetadata = {\n type: METADATA_TYPES.WebAppManifest,\n ast: manifestData,\n filePath: relativePath,\n id: relativePath,\n directDependencies: new Set(),\n };\n\n return [webManifestMetadata, null];\n}\n","import { splitHtmlLink } from \"../../../utilities/html-links.ts\";\nimport { isWebManifestMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { basename } from \"../../../utilities/path.ts\";\nimport { printFmtError } from \"../../../utilities/print-formatted-error.ts\";\nimport { cloneObject } from \"../../../utilities/utilities.ts\";\nimport { webManifestLoader } from \"./web-manifest-loader.ts\";\n\nimport type { MetadataSource, Plugin } from \"@staticbolt/core\";\n\n/**\n * The web app manifest half of the core pipeline: loads a \"manifest.json\" as JSON data and reports the assets it points at.\n *\n * Notes:\n *\n * - Detection is by file name, so a manifest under a different name is only picked up when the type is passed explicitly.\n * - Icons, screenshots and shortcut icons are reported as sources, so their paths are resolved and rebased with everything else.\n * - Printing gives compact JSON, or indented when formatting.\n */\nexport function coreWebManifestPlugin(): Plugin {\n return {\n name: \"core-web-manifest-metadata\",\n\n load(content, relativePath, { type }) {\n const [link] = splitHtmlLink(relativePath);\n\n type ??= basename(link);\n\n if (type !== \"manifest.json\") {\n return;\n }\n\n const [fileMetadata, metadataError] = webManifestLoader.call(this, link, content);\n if (metadataError) {\n printFmtError(metadataError, { function: coreWebManifestPlugin, filePath: relativePath });\n return;\n }\n\n return fileMetadata;\n },\n\n clone(metadata) {\n if (!isWebManifestMetadata(metadata)) return;\n\n const cloned = cloneObject(metadata);\n cloned.ast = structuredClone(metadata.ast);\n\n return cloned;\n },\n\n stringify(metadata, { format }) {\n if (!isWebManifestMetadata(metadata)) return;\n\n if (format) {\n return JSON.stringify(metadata.ast, null, 2);\n }\n\n return JSON.stringify(metadata.ast);\n },\n\n sourcesProvider(metadata) {\n if (!isWebManifestMetadata(metadata)) return;\n\n const icons = metadata.ast.icons ?? [];\n const shortcutIcons = metadata.ast.shortcuts?.flatMap(shortcut => shortcut.icons ?? []) ?? [];\n const screenshots = metadata.ast.screenshots ?? [];\n\n const sources: MetadataSource[] = [];\n\n for (const asset of [...icons, ...screenshots, ...shortcutIcons]) {\n const source = asset.src;\n if (!source) continue;\n\n sources.push({\n node: asset,\n get source() {\n return source;\n },\n set source(newValue) {\n asset.src = newValue;\n },\n });\n }\n\n return sources;\n },\n };\n}\n","import { createServer } from \"node:net\";\nimport { createInterface } from \"node:readline/promises\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport chalk from \"chalk\";\n\nimport { Log } from \"../../../utilities/logger.ts\";\n\nexport const PROJECT_HEADER = \"x-staticbolt-project\";\nexport const PID_HEADER = \"x-staticbolt-pid\";\n\nconst FREE_PORT_SEARCH = 20;\nconst KILL_TIMEOUT_MS = 3000;\n\ntype PortOwner = { kind: \"other\" } | { kind: \"staticbolt\"; project: string; pid: number };\n\ninterface Choice {\n label: string;\n port?: number;\n killPid?: number;\n}\n\n/**\n * The port to listen on: `port` when it is free, otherwise what the user picks. Another dev server of ours can be killed to take\n * its port over, any holder can be sidestepped with the next free port, and declining, or having no terminal to ask on, fails\n * with the wanted port's error.\n */\nexport async function claimPort(port: number, host: string, project: string): Promise<number> {\n if (await isPortFree(port, host)) return port;\n\n const owner = await identifyOwner(port);\n const problem = describeOwner(owner, port, project);\n const choice = process.stdin.isTTY ? await ask(problem, await listChoices(owner, port, host)) : undefined;\n\n if (choice?.port === undefined) {\n throw new Error(`${problem} Stop what is using it, or pick another with developmentServerPlugin({ port })`, { cause: owner });\n }\n\n if (choice.killPid !== undefined) {\n await kill(choice.killPid, port, host);\n }\n\n return choice.port;\n}\n\n/** A `HEAD /` answered with the project header means a dev server of ours. Anything else, or no answer, is another application. */\nasync function identifyOwner(port: number): Promise<PortOwner> {\n try {\n const response = await fetch(`http://127.0.0.1:${port}/`, { method: \"HEAD\", signal: AbortSignal.timeout(1000) });\n const project = response.headers.get(PROJECT_HEADER);\n const pid = Number(response.headers.get(PID_HEADER));\n\n return project && pid ? { kind: \"staticbolt\", project, pid } : { kind: \"other\" };\n } catch {\n return { kind: \"other\" };\n }\n}\n\nfunction describeOwner(owner: PortOwner, port: number, project: string): string {\n if (owner.kind === \"other\") return `Port ${port} is used by another application.`;\n if (owner.project === project) return `A dev server for this project is already running on port ${port}.`;\n\n return `Port ${port} is used by the dev server of \"${owner.project}\".`;\n}\n\nasync function listChoices(owner: PortOwner, port: number, host: string): Promise<Choice[]> {\n const choices: Choice[] = [];\n\n if (owner.kind === \"staticbolt\") {\n choices.push({ label: `Kill it and use port ${port}`, port, killPid: owner.pid });\n }\n\n const freePort = await findFreePort(port + 1, host);\n if (freePort !== undefined) {\n choices.push({ label: `Use port ${freePort}`, port: freePort });\n }\n\n choices.push({ label: \"Do nothing\" });\n\n return choices;\n}\n\nasync function kill(pid: number, port: number, host: string): Promise<void> {\n process.kill(pid);\n\n const deadline = Date.now() + KILL_TIMEOUT_MS;\n while (Date.now() < deadline) {\n if (await isPortFree(port, host)) return;\n await sleep(100);\n }\n\n throw new Error(`Port ${port} is still busy after stopping process ${pid}`);\n}\n\nasync function findFreePort(from: number, host: string): Promise<number | undefined> {\n for (let port = from; port < from + FREE_PORT_SEARCH; port++) {\n if (await isPortFree(port, host)) return port;\n }\n\n return undefined;\n}\n\nfunction isPortFree(port: number, host: string): Promise<boolean> {\n return new Promise(resolve => {\n const server = createServer();\n\n server.once(\"error\", () => resolve(false));\n server.listen(port, host, () => server.close(() => resolve(true)));\n });\n}\n\n/** Numbered choices in the terminal. An empty answer takes the first, a closed input the last. */\nasync function ask(question: string, choices: Choice[]): Promise<Choice> {\n const readline = createInterface({ input: process.stdin, output: process.stdout });\n\n try {\n Log.warn(question);\n for (const [index, choice] of choices.entries()) {\n console.log(` ${chalk.bold(index + 1)}) ${choice.label}`);\n }\n\n while (true) {\n const answer = await readline.question(chalk.bold(\" Choice (1): \"));\n const picked = choices[answer.trim() === \"\" ? 0 : Number(answer) - 1];\n\n if (picked) return picked;\n }\n } catch {\n return choices.at(-1)!;\n } finally {\n readline.close();\n }\n}\n","import { isHtmlMetadata } from \"../../../utilities/metadata-utilities.ts\";\n\nimport type { MetadataBase } from \"@staticbolt/core\";\n\nconst id = \"inject-reload-script\";\n\nexport function injectReloadScript(metadata: MetadataBase) {\n if (!isHtmlMetadata(metadata)) return;\n\n // eslint-disable-next-line unicorn/require-css-escape\n const isAlreadyInjected = metadata.ast.querySelector(`script[id=\"${id}\"]`);\n if (isAlreadyInjected) return;\n\n const element = metadata.ast.querySelector(\"html\");\n if (!element) return;\n\n const newNode = `<script id=\"${id}\">${HOT_RELOAD_SCRIPT(metadata.id)}</script>`;\n\n element.insertAdjacentHTML(\"beforeend\", newNode);\n}\n\nconst HOT_RELOAD_SCRIPT = (htmlFilePath: string) => String.raw`\n// Code injected by staticbolt\n\nconst htmlFilePath = \"${htmlFilePath}\";\n\nfunction refreshCSS() {\n const sheets = [].slice.call(document.getElementsByTagName(\"link\"));\n const head = document.getElementsByTagName(\"head\")[0];\n\n for (let i = 0; i < sheets.length; ++i) {\n const elem = sheets[i];\n const parent = elem.parentElement || head;\n parent.removeChild(elem);\n const rel = elem.rel;\n if ((elem.href && typeof rel != \"string\") || rel.length == 0 || rel.toLowerCase() == \"stylesheet\") {\n const url = elem.href.replace(/(&|\\?)_cacheOverride=\\d+/, \"\");\n elem.href = url + (url.indexOf(\"?\") >= 0 ? \"&\" : \"?\") + \"_cacheOverride=\" + new Date().valueOf();\n }\n parent.appendChild(elem);\n }\n}\n\nfunction cleanHref(el) {\n const url = new URL(el.href, window.location.origin);\n\n let path = url.pathname;\n\n if (!path.startsWith(\"./\") && !path.startsWith(\"../\")) {\n path = \".\" + path;\n }\n\n return path;\n}\n\nfunction getCssLinks() {\n const links = document.querySelectorAll(\"link[rel=stylesheet]\");\n return Array.from(links).map(link => cleanHref(link));\n}\n\nconst address = (window.location.protocol === \"http:\" ? \"ws://\" : \"wss://\")\n + window.location.host + window.location.pathname + \"/ws\";\n\nconst RETRY_INTERVAL_MS = 1000;\n\nlet retryTimeout = null;\nlet hasConnected = false;\nlet socket = null;\n\nfunction connect() {\n socket = new WebSocket(address);\n\n\n socket.onopen = function () {\n if (hasConnected) {\n location.reload();\n return;\n }\n\n hasConnected = true;\n console.log(\"[staticbolt] WebSocket connected.\");\n };\n\n socket.onmessage = function (msg) {\n const data = JSON.parse(msg.data).data;\n\n if (!Array.isArray(data)) return;\n\n if (data.includes(htmlFilePath)) {\n location.reload();\n return;\n }\n\n const links = getCssLinks();\n if (data.some(link => links.includes(link))) {\n refreshCSS();\n }\n };\n\n socket.onclose = function () {\n console.log(\"[staticbolt] WebSocket disconnected. Retrying in \" + RETRY_INTERVAL_MS + \"ms...\");\n retryTimeout = setTimeout(() => {\n connect();\n }, RETRY_INTERVAL_MS);\n };\n\n socket.onerror = function () {\n socket.close();\n };\n}\n\n// Navigating away does not reliably close the socket\nwindow.addEventListener(\"pagehide\", function () {\n clearTimeout(retryTimeout);\n\n if (socket) {\n socket.onclose = null;\n socket.close();\n }\n});\n\n// Restored from the back/forward cache.\nwindow.addEventListener(\"pageshow\", function (event) {\n if (event.persisted) {\n location.reload();\n }\n});\n\nconnect();\n`;\n","import type { MetadataBase } from \"@staticbolt/core\";\n\nexport function orderByDependencyDepth(\n allMetadata: readonly MetadataBase[],\n entryPoints: string[],\n filePaths: Set<string>\n): string[] {\n const metadataById = new Map(allMetadata.map(m => [m.id, m]));\n\n // BFS from all entry points to compute max depth for each reachable node\n const maxDepth = new Map<string, number>();\n const queue: { id: string; depth: number }[] = entryPoints.map(id => ({ id, depth: 0 }));\n\n while (queue.length > 0) {\n const { id, depth } = queue.shift()!;\n\n // Keep the deepest (max) depth seen for this node\n const known = maxDepth.get(id) ?? -1;\n if (depth <= known) continue;\n maxDepth.set(id, depth);\n\n const metadata = metadataById.get(id);\n if (!metadata) continue;\n\n if (depth >= allMetadata.length) continue;\n\n for (const dependencyId of metadata.directDependencies) {\n queue.push({ id: dependencyId, depth: depth + 1 });\n }\n }\n\n const reachable: string[] = [];\n const unreachable: string[] = [];\n\n for (const id of filePaths) {\n if (maxDepth.has(id)) {\n reachable.push(id);\n continue;\n }\n\n unreachable.push(id);\n }\n\n // Sort reachable: deepest first (highest depth number first)\n reachable.sort((a, b) => (maxDepth.get(b) ?? 0) - (maxDepth.get(a) ?? 0));\n\n return [...unreachable, ...reachable];\n}\n","import type { IncomingMessage } from \"node:http\";\nimport { networkInterfaces } from \"node:os\";\nimport type { Duplex } from \"node:stream\";\nimport fastifyStatic from \"@fastify/static\";\nimport fastifyUrlData from \"@fastify/url-data\";\nimport chalk from \"chalk\";\nimport Fastify from \"fastify\";\nimport { WebSocketServer } from \"ws\";\n\nimport { Log } from \"../../../utilities/logger.ts\";\nimport { isHtmlMetadata, isPackageMetadata, isScriptMetadata, isStyleMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { basename, extname, join, normalize } from \"../../../utilities/path.ts\";\nimport { claimPort, PID_HEADER, PROJECT_HEADER } from \"./claim-port.ts\";\nimport { injectReloadScript } from \"./inject-reload-script.ts\";\nimport { orderByDependencyDepth } from \"./order-by-dependency-depth.ts\";\n\nimport type { MetadataBase, Plugin } from \"@staticbolt/core\";\nimport type { onRequestHookHandler } from \"fastify\";\nimport type { Server, WebSocket } from \"ws\";\n\n/** What the serve command hands over through `app.pluginData`, taking precedence over the plugin options for that run. */\nexport interface DevelopmentServerOverrides {\n host?: boolean | string;\n}\n\nexport const DEVELOPMENT_SERVER_OVERRIDES = \"development-server\";\n\nexport interface DevelopmentServerOptions {\n /**\n * Where the dev server listens. `true` listens on every address, so the site is reachable from other devices on the network; a\n * string is a specific address to listen on. The `--host` flag of the serve command turns this on for one run.\n *\n * @default false\n */\n host?: boolean | string;\n\n /**\n * The dev server port.\n *\n * @default 3000\n */\n port?: number;\n\n /**\n * Entry url pathname when opening the browser.\n *\n * @default /\n */\n entry?: string;\n\n /**\n * Files in the public directory are served from the root as a fallback.\n *\n * @default \"public\"\n */\n publicDirectory?: string;\n}\n\n/**\n * The dev server: serves the build from memory over Fastify, compiles pages on demand, and pushes updates to the browser over a\n * web socket.\n *\n * Notes:\n *\n * - Development only.\n * - A request is answered from what is already compiled; otherwise the path is resolved to an entry point and compiled on the spot,\n * with a directory path getting \"index.html\" appended. Anything that is not an entry point falls through to the static handler,\n * which serves the project root and the public directory.\n * - The reload script is injected into HTML entry points as they are served, so it never exists in the built output.\n * - On a change, the affected pages are recompiled in dependency order and metadata nothing references any more is dropped. If only\n * CSS changed the stylesheets are swapped in place, otherwise the page reloads.\n * - Compiled pages are trimmed to the number of connected clients, dropping the least recently served ones.\n * - Closing the app drops the connected clients and stops the server, which frees the port for the next one; the browser reloads\n * itself as soon as it reconnects.\n */\nexport function developmentServerPlugin(options: DevelopmentServerOptions = {}): Plugin {\n const port = options.port ?? 3000;\n const entry = options.entry ?? \"/\";\n const publicDirectory = options.publicDirectory ?? \"public\";\n\n let fastify: Fastify.FastifyInstance | undefined;\n let websocket: Server | undefined;\n const wsClients: Set<WebSocket> = new Set();\n const entryPointAgeMap = new Map<string, number>();\n\n function upgradeWebSocketHandler(server: Server, request: IncomingMessage, socket: Duplex, head: Buffer) {\n server.handleUpgrade(request, socket, head, ws => {\n wsClients.add(ws);\n server.emit(\"connection\", ws, request);\n\n ws.send(JSON.stringify({ data: \"connected\" }));\n\n ws.on(\"close\", () => {\n wsClients.delete(ws);\n });\n\n ws.on(\"error\", error => {\n Log.error(\"WebSocket error:\", error.message);\n });\n });\n }\n\n function sendMessageToClients(message: string[]) {\n for (const client of wsClients) {\n if (client) client.send(JSON.stringify({ data: message }));\n }\n }\n\n return {\n name: \"dev-server\",\n\n async setup() {\n if (this.production) return;\n\n // Web Socket\n const websocketServer = new WebSocketServer({ noServer: true });\n websocket = websocketServer;\n\n // Web Server\n const projectName = basename(this.root);\n const fastifyServe: onRequestHookHandler = async (request, reply) => {\n reply.header(PROJECT_HEADER, projectName).header(PID_HEADER, process.pid);\n\n const requestPath = normalize(\".\" + decodeURIComponent(request.urlData().path || \"./\"));\n await this.handleRequest(requestPath, reply, request);\n };\n\n fastify = Fastify();\n fastify.register(fastifyUrlData);\n fastify.register(fastifyStatic, { root: [this.root, join(this.root, publicDirectory)] });\n fastify.addHook(\"onRequest\", fastifyServe);\n fastify.server.on(\"upgrade\", (request, socket, head) => upgradeWebSocketHandler(websocketServer, request, socket, head));\n\n websocketServer.on(\"connection\", () => {\n // From oldest to newest\n const sortedByAge = Array.from(entryPointAgeMap)\n .toSorted((a, b) => a[1] - b[1])\n .map(([id]) => id);\n\n // Trim excess\n const excess = sortedByAge.length - wsClients.size;\n\n // Trim excess\n if (excess > 0) {\n for (const id of sortedByAge.slice(0, excess)) {\n entryPointAgeMap.delete(id);\n removeAndPruneOrphans(this.metadataList, id);\n }\n }\n });\n\n const overrides = this.pluginData[DEVELOPMENT_SERVER_OVERRIDES] as DevelopmentServerOverrides | undefined;\n const host = resolveHost(overrides?.host ?? options.host);\n const listeningPort = await claimPort(port, host, projectName);\n await fastify.listen({ port: listeningPort, host });\n\n this.log.info(describeAddresses(host, listeningPort, entry));\n },\n\n async teardown() {\n for (const client of wsClients) {\n client.terminate();\n }\n\n wsClients.clear();\n websocket?.close();\n\n await fastify?.close();\n },\n\n async onFileEvent(event, changedSource) {\n if (event === \"unlink\") {\n removeAndPruneOrphans(this.metadataList, changedSource);\n return;\n }\n\n if (event !== \"change\") return;\n\n const htmlEntryPoints = this.metadataList.filter(meta => this.entryPoints.has(meta.id) && isHtmlMetadata(meta));\n const affected = htmlEntryPoints\n .filter(meta => meta.id === changedSource || isDependency(this.metadataList, meta, changedSource))\n .map(entry => entry.id);\n\n const compileList = await this.getCompileList(\"change\", changedSource);\n compileList.add(changedSource);\n\n const ordered = orderByDependencyDepth(this.metadataList, affected, compileList);\n\n let isStyleOnly = true;\n\n for (const id of ordered) {\n const oldMetadataList = this.filterMetadata({ id });\n\n // Nothing to recompile\n if (oldMetadataList.length === 0) {\n continue;\n }\n\n // Capture all old dependencies before removal\n const oldDependencies = new Set(oldMetadataList.flatMap(m => Array.from(m.directDependencies)));\n\n // Remove any previous metadata before processing\n this.removeMetadata(oldMetadataList);\n\n // Process\n const isSuccess = await this.process(id);\n if (!isSuccess) {\n this.addMetadata(oldMetadataList);\n continue;\n }\n\n // Capture new dependencies\n const newMetadataList = this.filterMetadata({ id });\n const newDependencies = new Set(newMetadataList.flatMap(m => Array.from(m.directDependencies)));\n\n // Diff to find removed dependencies\n const removedDependencies = Array.from(oldDependencies).filter(dependency => !newDependencies.has(dependency));\n\n // Remove orphans\n for (const dependency of removedDependencies) {\n const isStillReferenced = this.metadataList.some(m => m.directDependencies && m.directDependencies.has(dependency));\n if (isStillReferenced) continue;\n\n const orphans = this.filterMetadata({ id: dependency });\n if (orphans && orphans.length > 0) {\n this.removeMetadata(orphans);\n }\n }\n\n if (extname(id) !== \".css\") {\n isStyleOnly = false;\n }\n\n this.log.info(\"Recompiled:\", id);\n }\n\n // Refresh CSS or reload clients\n if (isStyleOnly) {\n // changedSource may be a deeply @import-ed file. The browser can only\n // hot-swap <link> tags it actually has in the DOM, so resolve upward\n // to the CSS files that are direct dependencies of the affected HTML pages.\n const rootCssFiles = new Set<string>();\n\n for (const htmlId of affected) {\n const metadataListWithId = this.filterMetadata({ id: htmlId });\n for (const meta of metadataListWithId) {\n for (const dependency of meta.directDependencies) {\n if (extname(dependency) === \".css\") {\n rootCssFiles.add(dependency);\n }\n }\n }\n }\n\n // Fallback: if nothing resolved (e.g. changedSource IS a root), use it directly\n sendMessageToClients(rootCssFiles.size > 0 ? Array.from(rootCssFiles) : [changedSource]);\n return;\n }\n\n // Reload clients\n sendMessageToClients(affected);\n },\n\n async handleRequest(requestPath, reply) {\n // Add index.html for a directory path\n if (!extname(requestPath)) {\n requestPath = join(requestPath, \"index.html\");\n }\n\n // Already compiled\n let metadata = this.metadataList.find(\n m =>\n // Flatten paths outside of root\n m.filePath.replace(/^(\\.\\.\\/)+/, \"./\") === requestPath\n );\n\n if (!metadata) {\n // Try to get the real file path\n const resolvedRequestPath = (await this.resolveRequestPath(requestPath)) ?? requestPath;\n\n // Only compile entry points\n if (this.entryPoints.has(resolvedRequestPath)) {\n this.log.info(\"Compiling:\", resolvedRequestPath);\n\n await this.process(resolvedRequestPath);\n\n // Should be added after compilation\n metadata = this.findMetadata({ filePath: requestPath });\n }\n }\n\n if (!metadata) {\n return;\n }\n\n if (this.entryPoints.has(metadata.id) && isHtmlMetadata(metadata)) {\n // Hot reload script\n injectReloadScript(metadata);\n\n entryPointAgeMap.set(metadata.id, Date.now());\n }\n\n const stringified = await this.stringify(metadata);\n if (typeof stringified !== \"string\") return;\n\n reply.type(getMetadataMimeType(metadata)).send(stringified);\n\n return true;\n },\n };\n}\n\n/** The URLs the server answers on: localhost, plus every LAN address when it is bound to all interfaces. */\nfunction describeAddresses(host: string, port: number, entry: string): string {\n const isEveryInterface = host === \"0.0.0.0\" || host === \"::\";\n const isLoopback = host === \"127.0.0.1\" || host === \"::1\";\n const url = (hostname: string) => chalk.green(`http://${hostname}:${port}${entry}`);\n\n const lines = [`${chalk.bold(\"Local:\")} ${url(isEveryInterface || isLoopback ? \"localhost\" : host)}`];\n\n if (isEveryInterface) {\n for (const address of lanAddresses()) {\n lines.push(`${chalk.bold(\"Network:\")} ${url(address)}`);\n }\n } else if (isLoopback) {\n lines.push(`${chalk.bold(\"Network:\")} ${chalk.dim(\"use --host to expose\")}`);\n }\n\n return \"\\n\" + lines.join(\"\\n\");\n}\n\nfunction lanAddresses(): string[] {\n return Object.values(networkInterfaces())\n .flat()\n .filter(address => address?.family === \"IPv4\" && !address.internal)\n .map(address => address!.address);\n}\n\nfunction isDependency(allMetadata: readonly MetadataBase[], metadata: MetadataBase, filePath: string): boolean {\n if (metadata.directDependencies.has(filePath)) {\n return true;\n }\n\n const metadataByPath = new Map(allMetadata.map(m => [m.id, m]));\n\n const visited = new Set<string>();\n const queue = [...metadata.directDependencies];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n\n if (visited.has(current)) continue;\n visited.add(current);\n\n const currentMetadata = metadataByPath.get(current);\n if (!currentMetadata) continue;\n\n for (const dependency of currentMetadata.directDependencies) {\n if (dependency === filePath) return true;\n if (!visited.has(dependency)) queue.push(dependency);\n }\n }\n\n return false;\n}\n\nfunction getMetadataMimeType(metadata: MetadataBase) {\n if (isHtmlMetadata(metadata)) {\n return \"text/html\";\n }\n\n if (isStyleMetadata(metadata)) {\n return \"text/css\";\n }\n\n if (isScriptMetadata(metadata) || isPackageMetadata(metadata)) {\n return \"application/javascript\";\n }\n\n return \"text/plain\";\n}\n\n/**\n * Removes a metadata entry by ID from the array in place, then cascades removal to any of its dependencies that are no longer\n * referenced by any remaining entry. Repeats until no unreferenced entries remain.\n */\nfunction removeAndPruneOrphans(metadataList: MetadataBase[], targetId: string): void {\n const queue = [targetId];\n const removed = new Set<string>();\n\n while (queue.length > 0) {\n const currentId = queue.shift()!;\n\n if (removed.has(currentId)) continue;\n removed.add(currentId);\n\n // Collect deps from ALL entries with this id\n const entries = metadataList.filter(m => m.id === currentId);\n if (entries.length === 0) continue;\n\n const dependencies = new Set(entries.flatMap(m => [...m.directDependencies]));\n\n // Remove all copies\n for (let index = metadataList.length - 1; index >= 0; index--) {\n if (metadataList[index].id === currentId) metadataList.splice(index, 1);\n }\n\n // Queue orphaned deps\n for (const dependencyId of dependencies) {\n const isStillUsed = metadataList.some(m => m.directDependencies.has(dependencyId));\n if (!isStillUsed) queue.push(dependencyId);\n }\n }\n}\n\n/** Every address, a given one, or the IPv4 loopback: \"localhost\" itself can resolve to IPv6 only, Windows being the usual case. */\nfunction resolveHost(host: boolean | string | undefined): string {\n if (host === true) return \"0.0.0.0\";\n if (typeof host === \"string\" && host !== \"\") return host;\n return \"127.0.0.1\";\n}\n","import chalk from \"chalk\";\n\ntype ExecutionTime = Record<string, Record<string, number>>;\n\nfunction formatDuration(ms: number): string {\n if (ms < 1) {\n return chalk.gray(`${(ms * 1000).toFixed(2)}μs`);\n }\n if (ms < 1000) {\n const color = ms < 100 ? chalk.green : ms < 500 ? chalk.yellow : chalk.red;\n return color(`${ms.toFixed(2)}ms`);\n }\n return ms < 60_000 ? chalk.redBright(`${(ms / 1000).toFixed(2)}s`) : chalk.magenta(`${(ms / 60_000).toFixed(2)}m`);\n}\n\nfunction buildBar(value: number, total: number): string {\n const BAR_WIDTH = 16;\n const ratio = total > 0 ? value / total : 0;\n const filled = Math.round(ratio * BAR_WIDTH);\n const empty = BAR_WIDTH - filled;\n const pct = (ratio * 100).toFixed(0).padStart(3);\n\n const filledBar =\n ratio < 0.2\n ? chalk.green(\"█\".repeat(filled))\n : ratio < 0.5\n ? chalk.yellow(\"█\".repeat(filled))\n : chalk.red(\"█\".repeat(filled));\n\n return filledBar + chalk.dim(\"░\".repeat(empty)) + chalk.dim(` ${pct}%`);\n}\n\nexport function printExecutionTime(executionTime: ExecutionTime): void {\n // Sort groups by their total time descending\n const sortedGroups = Object.entries(executionTime).toSorted(([, a], [, b]) => {\n const totalA = Object.values(a).reduce((sum, v) => sum + v, 0);\n const totalB = Object.values(b).reduce((sum, v) => sum + v, 0);\n return totalB - totalA;\n });\n\n for (const [groupName, metrics] of sortedGroups) {\n const total = Object.values(metrics).reduce((sum, v) => sum + v, 0);\n\n // Filter out hooks under 1ms, sort remaining by duration descending\n const entries = Object.entries(metrics)\n .filter(([, v]) => v >= 1)\n .toSorted(([, a], [, b]) => b - a);\n\n console.log();\n\n // Empty groups: single line, no box\n if (entries.length === 0) {\n console.log(chalk.bold.cyan(\"─ \") + chalk.bold.white(groupName) + chalk.dim(` total: ${formatDuration(total)}`));\n continue;\n }\n\n const maxLabelLength = Math.max(...entries.map(([k]) => k.length));\n\n console.log(chalk.bold.cyan(\"─ \") + chalk.bold.white(groupName) + chalk.dim(` total: ${formatDuration(total)}`));\n\n for (const [key, value] of entries) {\n const label = chalk.dim(key.padEnd(maxLabelLength));\n const bar = buildBar(value, total);\n const time = formatDuration(value);\n\n console.log(` ${label} ${bar} ${time}`);\n }\n }\n\n console.log();\n}\n","import browserslistFn from \"browserslist\";\nimport chokidar from \"chokidar\";\n\nimport { printExecutionTime } from \"./helpers/pirnt-debug.ts\";\nimport { coreBasePlugin } from \"./plugins/core-plugins/base-plugin/base-plugin.ts\";\nimport { Resolver } from \"./resolver/resolver.ts\";\nimport { createLog, Log } from \"./utilities/logger.ts\";\nimport { basename, isAbsolute, join, normalize, relative, resolve } from \"./utilities/path.ts\";\n\nimport type {\n MetadataBase,\n AppConfig,\n BoundPlugin,\n MetadataSource,\n Plugin,\n ServerReply,\n ServerRequest,\n StringifyOptions,\n} from \"@staticbolt/core\";\nimport type { FSWatcher } from \"chokidar\";\n\ntype PluginOnlyHooks = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof BoundPlugin as BoundPlugin[K] extends (...arguments_: any) => any ? K : never]: BoundPlugin[K];\n};\n\ntype PluginHook = keyof PluginOnlyHooks;\n\ntype AnyHook = (...arguments_: never[]) => unknown;\n\n/** The hooks that run on an app context. `cli` runs on the CLI program instead, and the `lsp*` hooks are called as written. */\ntype BoundHook = Exclude<PluginHook, \"cli\" | \"lspHtmlData\" | \"lspEmbeddedLanguages\" | \"lspValidate\">;\n\n/** Every bound hook, in bind order. The `satisfies` makes a hook added to `Plugin` a type error until it is listed here. */\nconst BOUND_HOOKS = Object.keys({\n setup: true,\n teardown: true,\n read: true,\n load: true,\n resolveSource: true,\n transformSource: true,\n preTransform: true,\n transform: true,\n postTransform: true,\n write: true,\n postBuild: true,\n clone: true,\n stringify: true,\n sourcesProvider: true,\n rebaseSource: true,\n onMetadataRebase: true,\n\n // Dev server\n handleRequest: true,\n resolveRequestPath: true,\n onFileEvent: true,\n resolveCompileList: true,\n} satisfies Record<BoundHook, true>) as BoundHook[];\n\n/**\n * Shared no-op bound to hooks a plugin doesn't implement. Hot loops compare against it to skip the call (and the `await`\n * microtask) entirely.\n */\nconst emptyFunction = () => {};\n\nexport class App {\n readonly configPath: string;\n\n /** The absolute path to the project root. */\n readonly root: string;\n\n /** The absolute path to the output directory. */\n readonly outdir: string;\n\n /** Whether the application is running in production mode. */\n readonly production: boolean;\n\n /** A list of browsers to target. */\n readonly browserslist: string[];\n\n readonly metadataList: MetadataBase[] = [];\n\n private readonly plugins: BoundPlugin[] = [];\n\n readonly resolver: Resolver;\n\n log = Log;\n\n /** File paths to load as sources. */\n readonly entryPoints: Set<string> = new Set();\n\n /** Any type of data for plugins to use. */\n readonly pluginData: Record<string, unknown> = {};\n\n /** Exclude paths from being emitted. */\n readonly emitExclude: Set<MetadataBase> = new Set();\n\n /** Chokidar watcher. Development only, and gone once the app is closed. */\n watcher: FSWatcher | undefined;\n\n private isPluginInitialized = false;\n private isClosed = false;\n\n private measureExecutionTime = false;\n private executionTime: Record<string, Record<string, number>> = {};\n\n /** How long the hooks called from inside the hook currently being measured took. Held in an object so plugin contexts share it. */\n private readonly nestedTime = { ms: 0 };\n\n readonly pluginIndex: number = -1;\n readonly pluginName: string = \"\";\n\n constructor(options: AppConfig = {}, configPath: string) {\n // Config\n this.configPath = configPath;\n this.root = resolve(options.root ?? process.cwd());\n this.production = options.production ?? false;\n this.measureExecutionTime = options.measureExecutionTime ?? false;\n options.outdir ??= \"./dist\";\n this.outdir = isAbsolute(options.outdir) ? options.outdir : join(this.root, options.outdir);\n this.browserslist = browserslistFn(options.browserslist, { path: this.root });\n this.resolver = new Resolver(this.root, this.production, options.aliases);\n\n // Load plugins\n const pluginsList = options.plugins ?? [];\n for (const pluginOrPlugins of pluginsList) {\n const items = Array.isArray(pluginOrPlugins) ? pluginOrPlugins : [pluginOrPlugins];\n for (const plugin of items) {\n this.plugins.push(this.bindPlugin(plugin, this.plugins.length));\n }\n }\n\n // Base plugin\n this.plugins.push(this.bindPlugin(coreBasePlugin(), this.plugins.length));\n\n // Rename duplicates\n const groups = new Map<string, Plugin[]>();\n\n for (const plugin of this.plugins) {\n const name = plugin.name;\n\n if (!groups.has(name)) {\n groups.set(name, []);\n }\n\n groups.get(name)!.push(plugin);\n }\n\n for (const [name, list] of groups) {\n if (list.length <= 1) continue;\n\n for (const [index, p] of list.entries()) {\n p.name = `${name}#${index}`;\n }\n }\n\n if (this.production) {\n return;\n }\n\n // Create watcher\n this.watcher = chokidar.watch([], { cwd: this.root, ignoreInitial: true });\n this.watcher\n .on(\"change\", async changePath => await this.emitFileChange(\"change\", changePath))\n .on(\"add\", async changePath => await this.emitFileChange(\"add\", changePath))\n .on(\"unlink\", async changePath => await this.emitFileChange(\"unlink\", changePath))\n .on(\"error\", error => {\n this.log.error(\"FILE WATCHER ERROR:\");\n console.error(error);\n });\n }\n\n /** Binds a copy of the plugin's hooks to this app, leaving the user's object untouched. */\n private bindPlugin(plugin: Plugin, pluginIndex: number): BoundPlugin {\n const pluginContext = Object.create(this) as App & { pluginIndex: number; pluginName: string };\n pluginContext.pluginIndex = pluginIndex;\n pluginContext.pluginName = plugin.name;\n pluginContext.log = createLog(`[${plugin.name}]`);\n\n const boundPlugin = { ...plugin } as BoundPlugin;\n\n // A hook the plugin does not implement becomes the shared no-op.\n const hooks = boundPlugin as Record<BoundHook, AnyHook | undefined>;\n\n for (const hookName of BOUND_HOOKS) {\n const hook = hooks[hookName];\n hooks[hookName] = hook ? hook.bind(pluginContext) : emptyFunction;\n }\n\n return boundPlugin;\n }\n\n private callPluginMethod<T extends keyof PluginOnlyHooks>(\n plugin: BoundPlugin,\n method: T,\n ...arguments_: Parameters<PluginOnlyHooks[T]>\n ) {\n if (!this.measureExecutionTime) {\n const methodFunction = plugin[method] as (...arguments__: unknown[]) => unknown;\n return methodFunction(...arguments_) as ReturnType<BoundPlugin[T]>;\n }\n\n this.executionTime[plugin.name] ??= {};\n this.executionTime[plugin.name][method] ??= 0;\n\n const now = performance.now();\n const callerNestedTime = this.nestedTime.ms;\n this.nestedTime.ms = 0;\n\n /**\n * Hooks call back into the app, so what a hook spends inside other hooks is subtracted from its own time and handed to the\n * caller instead. Every dispatch is awaited in order, so one hook is ever being measured at a time.\n */\n const record = () => {\n const elapsed = performance.now() - now;\n this.executionTime[plugin.name][method] += elapsed - this.nestedTime.ms;\n this.nestedTime.ms = callerNestedTime + elapsed;\n };\n\n const methodFunction = plugin[method] as (...arguments__: unknown[]) => unknown;\n const result = methodFunction(...arguments_) as ReturnType<BoundPlugin[T]>;\n\n // Async hooks must be timed until they settle, not until they return their promise.\n if (result instanceof Promise) {\n return result.finally(record) as ReturnType<BoundPlugin[T]>;\n }\n\n record();\n\n return result;\n }\n\n private async emitFileChange(event: \"change\" | \"add\" | \"unlink\", filePath: string) {\n filePath = normalize(filePath);\n\n for (const plugin of this.plugins) {\n if (plugin.onFileEvent === emptyFunction) continue;\n await this.callPluginMethod(plugin, \"onFileEvent\", event, filePath);\n }\n }\n\n async run() {\n const mode = this.production ? \"production\" : \"development\";\n this.log.info(`Starting in ${mode} mode`);\n\n // setup\n if (this.plugins.length > 0) {\n this.log.info(`Setting up ${this.plugins.length} plugin(s)`);\n\n for (const plugin of this.plugins) {\n await this.callPluginMethod(plugin, \"setup\");\n }\n }\n\n this.isPluginInitialized = true;\n\n if (!this.production) {\n this.log.info(\"Dev mode: on-demand build active, skipping build pipeline\");\n return;\n }\n\n // Load initial entry points\n for (const entryFile of this.entryPoints) {\n const exists = this.findMetadata({ id: entryFile });\n if (exists) continue;\n\n const metadata = await this.load(entryFile);\n if (!metadata) {\n this.log.error(`Could not load \"${entryFile}\".`);\n return;\n }\n\n this.addMetadata(metadata);\n }\n\n // Resolve & Load\n this.log.info(`Resolving ${this.metadataList.length} entry point(s)`);\n await this.resolveAndLoad(this.metadataList);\n\n // Transform\n this.log.info(`Transforming ${this.metadataList.length} file(s)`);\n\n for (const plugin of this.plugins) {\n await this.callPluginMethod(plugin, \"preTransform\");\n }\n\n await this.transform(this.metadataList);\n\n for (const plugin of this.plugins) {\n await this.callPluginMethod(plugin, \"postTransform\");\n }\n\n // Write\n this.log.info(`Writing ${this.metadataList.length} output file(s)`);\n await this.writeFiles();\n\n // Post Build\n this.log.info(\"Finalizing\");\n for (const plugin of this.plugins) {\n await this.callPluginMethod(plugin, \"postBuild\");\n }\n\n this.log.info(\"Build complete\");\n\n if (this.measureExecutionTime) {\n printExecutionTime(this.executionTime);\n }\n }\n\n /**\n * Stops watching and lets every plugin release what its `setup` took, in reverse order. A teardown that throws is reported and\n * the rest still run. Closing again does nothing.\n */\n async close() {\n if (this.isClosed) return;\n this.isClosed = true;\n\n await this.watcher?.close();\n this.watcher = undefined;\n\n for (const plugin of this.plugins.toReversed()) {\n if (plugin.teardown !== emptyFunction) {\n try {\n await this.callPluginMethod(plugin, \"teardown\");\n } catch (error) {\n this.log.error(`[${plugin.name}] Teardown failed:`);\n console.error(error);\n }\n }\n }\n }\n\n async process(id: string): Promise<boolean> {\n const metadata = await this.load(id);\n if (!metadata) {\n this.log.error(`Could not load \"${id}\".`);\n return false;\n }\n\n const metadataList = await this.resolveAndLoad(metadata);\n\n // Snapshot\n const previouslyTransformed = new Set(this.metadataList);\n\n // Merge\n this.addMetadata(metadataList);\n\n // Ready\n for (const plugin of this.plugins) {\n await this.callPluginMethod(plugin, \"preTransform\");\n }\n\n // Transform only newly added metadata\n for (const plugin of this.plugins) {\n if (plugin.transform === emptyFunction) continue;\n for (const metadataItem of this.metadataList) {\n if (!previouslyTransformed.has(metadataItem)) {\n await this.callPluginMethod(plugin, \"transform\", metadataItem);\n }\n }\n }\n\n // Pre-write\n for (const plugin of this.plugins) {\n await this.callPluginMethod(plugin, \"postTransform\");\n }\n\n return true;\n }\n\n async resolve(metadata: MetadataBase): Promise<Set<string>> {\n if (!this.isPluginInitialized) {\n this.log.warn(\"[resolve] Plugins are not fully setup yet.\");\n }\n\n const discoveredSet = new Set<string>();\n\n const sources = await this.requestSources(metadata);\n\n for (const sourceReference of sources) {\n let dependencyID: string | undefined;\n\n for (const plugin of this.plugins) {\n if (plugin.resolveSource === emptyFunction) continue;\n const resolved = await this.callPluginMethod(\n plugin,\n \"resolveSource\",\n sourceReference.source,\n metadata.filePath,\n metadata\n );\n if (!resolved) continue;\n\n sourceReference.source = resolved.source;\n dependencyID = resolved.dependencyID;\n\n if (dependencyID) {\n discoveredSet.add(dependencyID);\n this.watcher?.add(dependencyID);\n }\n\n break; // first plugin that resolves wins, skip remaining plugins\n }\n\n // After resolution is settled, let plugins transform the source\n for (const plugin of this.plugins) {\n if (plugin.transformSource === emptyFunction) continue;\n const transformed = await this.callPluginMethod(\n plugin,\n \"transformSource\",\n sourceReference.source,\n metadata.filePath,\n metadata,\n dependencyID\n );\n if (!transformed) continue;\n\n sourceReference.source = transformed;\n break; // same first-wins convention\n }\n }\n\n return discoveredSet;\n }\n\n /**\n * Resolve and load recursively\n *\n * 1. Resolves given metadata item or list\n * 2. Loads discovered dependencies if not already loaded skipping entry points\n * 3. Returns metadata list\n */\n async resolveAndLoad(metadataItemOrList: MetadataBase | MetadataBase[]) {\n const metadataList = Array.isArray(metadataItemOrList) ? metadataItemOrList : [metadataItemOrList];\n\n for (const metadataItem of metadataList) {\n const discovered = await this.resolve(metadataItem);\n\n for (const discoveredID of discovered) {\n if (discoveredID === metadataItem.id || this.entryPoints.has(discoveredID)) continue;\n\n metadataItem.directDependencies.add(discoveredID);\n\n const exists = this.findMetadata({ id: discoveredID }) ?? metadataList.find(m => m.id === discoveredID);\n if (exists) continue;\n\n const loadedMetadata = await this.load(discoveredID);\n if (!loadedMetadata) continue;\n\n // eslint-disable-next-line unicorn/no-loop-iterable-mutation -- It's intentional\n metadataList.push(loadedMetadata);\n }\n }\n\n return metadataList;\n }\n\n async transform(metadataItemOrList: MetadataBase | MetadataBase[]) {\n if (!this.isPluginInitialized) {\n this.log.warn(\"[transform] Plugins are not fully setup yet.\");\n }\n\n const metadataList = Array.isArray(metadataItemOrList) ? metadataItemOrList : [metadataItemOrList];\n\n for (const plugin of this.plugins) {\n if (plugin.transform === emptyFunction) continue;\n for (const metadata of metadataList) {\n await this.callPluginMethod(plugin, \"transform\", metadata);\n }\n }\n }\n\n async transformAndSync(metadataItemOrList: MetadataBase | MetadataBase[]) {\n if (!this.isPluginInitialized) {\n this.log.warn(\"[transformAndSync] Plugins are not fully setup yet.\");\n }\n\n if (this.pluginIndex < 0) {\n this.log.error(`[transformAndSync] Plugin index is not set.`);\n return;\n }\n\n if (!Object.hasOwn(this.plugins, this.pluginIndex)) {\n this.log.error(`[transformAndSync] Plugin with index \"${this.pluginIndex}\" does not exist.`);\n return;\n }\n\n const metadataList = Array.isArray(metadataItemOrList) ? metadataItemOrList : [metadataItemOrList];\n\n for (let index = 0; index <= this.pluginIndex; index++) {\n const plugin = this.plugins[index];\n if (plugin.transform === emptyFunction) continue;\n\n for (const metadata of metadataList) {\n await this.callPluginMethod(plugin, \"transform\", metadata);\n }\n }\n }\n\n async rebase(metadata: MetadataBase, newAbsolutePath: string) {\n if (!this.isPluginInitialized) {\n this.log.warn(\"[rebase] Plugins are not fully setup yet.\");\n }\n\n const oldAbsolutePath = join(this.root, metadata.filePath);\n if (oldAbsolutePath === newAbsolutePath) return;\n\n const sources = await this.requestSources(metadata);\n\n for (const sourceReference of sources) {\n for (const plugin of this.plugins) {\n if (plugin.rebaseSource === emptyFunction) continue;\n const rebased = await this.callPluginMethod(\n plugin,\n \"rebaseSource\",\n sourceReference.source,\n metadata.filePath,\n newAbsolutePath\n );\n\n if (rebased !== undefined) {\n sourceReference.source = rebased;\n break;\n }\n }\n }\n\n for (const plugin of this.plugins) {\n if (plugin.onMetadataRebase === emptyFunction) continue;\n await this.callPluginMethod(plugin, \"onMetadataRebase\", metadata, oldAbsolutePath, newAbsolutePath);\n }\n }\n\n async writeFiles() {\n if (!this.isPluginInitialized) {\n this.log.warn(\"[emit] Plugins are not fully setup yet.\");\n }\n\n for (const plugin of this.plugins) {\n if (plugin.write === emptyFunction) continue;\n await this.callPluginMethod(plugin, \"write\");\n }\n }\n\n async read(filePath: string) {\n filePath = normalize(filePath);\n\n if (!isAbsolute(filePath)) {\n filePath = join(this.root, filePath);\n }\n\n for (const plugin of this.plugins) {\n if (plugin.read === emptyFunction) continue;\n const content = await this.callPluginMethod(plugin, \"read\", filePath);\n if (content !== undefined) return content;\n }\n }\n\n async load(relativePath: string, options: { code?: string; type?: string } = {}) {\n // Try to find the exact file to load\n // In some cases a path like ./sources/index.js does not exist, but ./sources/index.ts does\n const resolved = this.resolver.resolve(basename(relativePath), relativePath);\n if (resolved) {\n relativePath = relative(this.root, resolved.path);\n }\n\n relativePath = normalize(relativePath);\n\n const content = options.code ?? (await this.read(relativePath));\n if (!content) return;\n\n for (const plugin of this.plugins) {\n if (plugin.load === emptyFunction) continue;\n const metadata = await this.callPluginMethod(plugin, \"load\", content, relativePath, { type: options.type });\n\n // Don't load\n if (metadata === null) break;\n\n if (metadata) {\n return metadata;\n }\n }\n }\n\n async requestSources(metadata: MetadataBase) {\n if (!this.isPluginInitialized) {\n this.log.warn(\"[requestSources] Plugins are not fully setup yet.\");\n }\n\n const result: MetadataSource[] = [];\n\n for (const plugin of this.plugins) {\n if (plugin.sourcesProvider === emptyFunction) continue;\n const sources = await this.callPluginMethod(plugin, \"sourcesProvider\", metadata);\n if (sources) result.push(...sources);\n }\n\n return result;\n }\n\n async stringify(metadata: MetadataBase, options: StringifyOptions = {}): Promise<string> {\n if (!this.isPluginInitialized) {\n this.log.warn(\"[stringify] Plugins are not fully setup yet.\");\n }\n\n for (const plugin of this.plugins) {\n if (plugin.stringify === emptyFunction) continue;\n const string = await this.callPluginMethod(plugin, \"stringify\", metadata, options);\n if (typeof string === \"string\") {\n return string;\n }\n }\n\n this.log.fatal(`Failed to stringify metadata: ${metadata.id}`);\n return \"\";\n }\n\n async getCompileList(event: \"change\" | \"add\" | \"unlink\", filePath: string) {\n filePath = normalize(filePath);\n\n const compileSet = new Set<string>([filePath]);\n\n for (const plugin of this.plugins) {\n if (plugin.resolveCompileList === emptyFunction) continue;\n await this.callPluginMethod(plugin, \"resolveCompileList\", compileSet, event, filePath);\n }\n\n return compileSet;\n }\n\n async handleRequest(requestPath: string, reply: ServerReply, request: ServerRequest) {\n for (const plugin of this.plugins) {\n if (plugin.handleRequest === emptyFunction) continue;\n const serve = await this.callPluginMethod(plugin, \"handleRequest\", requestPath, reply, request);\n if (serve) return serve;\n }\n }\n\n async resolveRequestPath(requestPath: string) {\n for (const plugin of this.plugins) {\n if (plugin.resolveRequestPath === emptyFunction) continue;\n const resolvedPath = await this.callPluginMethod(plugin, \"resolveRequestPath\", requestPath);\n if (resolvedPath) {\n requestPath = resolvedPath;\n }\n }\n\n return requestPath;\n }\n\n clone<T extends MetadataBase>(metadata: T): T {\n for (const plugin of this.plugins) {\n if (plugin.clone === emptyFunction) continue;\n const clone = this.callPluginMethod(plugin, \"clone\", metadata);\n if (clone) {\n return clone as T;\n }\n }\n\n this.log.fatal(`Failed to stringify metadata: ${metadata.id}`);\n\n return metadata;\n }\n\n addMetadata(itemOrList: MetadataBase | MetadataBase[]) {\n const items = Array.isArray(itemOrList) ? itemOrList : [itemOrList];\n\n for (const item of items) {\n this.metadataList.push(item);\n }\n }\n\n removeMetadata(metadataOrIndex: MetadataBase | MetadataBase[] | number) {\n if (typeof metadataOrIndex === \"number\") {\n if (metadataOrIndex === -1) return;\n\n this.metadataList.splice(metadataOrIndex, 1);\n return;\n }\n\n const items = Array.isArray(metadataOrIndex) ? metadataOrIndex : [metadataOrIndex];\n\n for (const item of items) {\n const index = this.metadataList.indexOf(item);\n if (index === -1) continue;\n\n this.metadataList.splice(index, 1);\n }\n }\n\n findMetadata<T extends MetadataBase>(metadataFilter: Partial<T>) {\n const filterEntries = Object.entries(metadataFilter);\n\n for (const metadata of this.metadataList) {\n // Match by reference\n if (metadata === metadataFilter) {\n return metadata as T;\n }\n\n let isMatch = true;\n\n for (const [key, value] of filterEntries) {\n if ((metadata as unknown as Record<string, unknown>)[key] !== value) {\n isMatch = false;\n break;\n }\n }\n\n if (isMatch) {\n return metadata as T;\n }\n }\n }\n\n filterMetadata<T extends MetadataBase>(metadataFilter: Partial<T>) {\n const filterEntries = Object.entries(metadataFilter);\n\n return this.metadataList.filter(metadata => {\n // Match by reference\n if (metadata === metadataFilter) {\n return true;\n }\n\n for (const [key, value] of filterEntries) {\n if ((metadata as unknown as Record<string, unknown>)[key] !== value) {\n return false;\n }\n }\n\n return true;\n }) as T[];\n }\n}\n","import chalk from \"chalk\";\nimport * as z from \"zod\";\n\nimport { App } from \"../../../main.ts\";\nimport { Log } from \"../../../utilities/logger.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface BuildCliPluginOptions {\n /**\n * Build command name.\n *\n * @default \"build\"\n */\n command?: string;\n\n /**\n * Build command aliases.\n *\n * @default [\"b\"]\n */\n aliases?: string[];\n}\n\n/**\n * Adds the \"build\" command (aliased \"b\"): runs the pipeline once in production mode and reports how long it took.\n *\n * Notes:\n *\n * - The command owns the run. It forces production mode onto the config and creates its own App.\n * - \"--measure\" turns on per-plugin hook timing and prints the report when the build finishes.\n */\nexport function buildCliPlugin(options: BuildCliPluginOptions = {}): Plugin {\n const name = options.command ?? \"build\";\n const aliases = options.aliases ?? [\"b\"];\n\n return {\n name: \"build-cli-plugin\",\n\n cli(config, configPath) {\n const buildCommand = this.defineSubcommand({\n name,\n aliases,\n meta: { description: \"Build static website command.\" },\n\n options: {\n measure: {\n schema: z.boolean().optional(),\n coerce: this.coerce.boolean,\n meta: {\n description: \"Measure per-plugin hook execution time and print a report after the build.\",\n },\n },\n },\n });\n\n buildCommand.onExecute(async ({ options: cliOptions }) => {\n const startTime = performance.now();\n\n config.production = true;\n config.measureExecutionTime = cliOptions.measure ?? config.measureExecutionTime;\n\n const app = new App(config, configPath);\n await app.run();\n\n Log.info(`Built in ${chalk.bold.green(Math.round(performance.now() - startTime) / 1000)} seconds.`);\n });\n\n this.addCommand(buildCommand);\n },\n };\n}\n","import { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { globSync } from \"glob\";\nimport * as z from \"zod\";\n\nimport { Log } from \"../../../utilities/logger.ts\";\nimport { basename, join, replaceExtension } from \"../../../utilities/path.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface ConvertFontsCliPluginOptions {\n /**\n * The name of the command.\n *\n * @default \"convert-fonts\"\n */\n command?: string;\n\n /**\n * The aliases of the command.\n *\n * @default [\"woff2\"]\n */\n aliases?: string[];\n\n /**\n * The default value of the `--fonts` option.\n *\n * A glob pattern to match font files.\n */\n fonts?: string;\n\n /**\n * The default value of the `--exclude` option.\n *\n * A glob patterns to exclude input files.\n */\n exclude?: string;\n\n /**\n * The default value of the `--out-dir` option.\n *\n * Where to save the output files.\n */\n outDir?: string;\n}\n\n/**\n * Adds the \"convert-fonts\" command (aliased \"woff2\"): converts the TTF files matched by \"--fonts\" to WOFF2.\n *\n * Notes:\n *\n * - The options given here become the defaults of the matching flags; a flag left without one has to be passed on the command line.\n * - Every font lands directly in \"--out-dir\" under its own name, so the source directory structure is flattened and fonts that\n * share a name overwrite each other.\n */\nexport function convertFontsCliPlugin(options: ConvertFontsCliPluginOptions = {}): Plugin {\n const name = options.command ?? \"convert-fonts\";\n const aliases = options.aliases ?? [\"woff2\"];\n\n return {\n name: \"convert-fonts-cli-plugin\",\n\n cli(config) {\n const convertFontsCommand = this.defineSubcommand({\n name,\n aliases,\n meta: { description: \"Convert TTF fonts to WOFF2 format.\" },\n\n options: {\n fonts: {\n schema: options.fonts ? z.string().default(options.fonts) : z.string(),\n meta: {\n placeholder: \"<pattern>\",\n description: \"A glob pattern to match font files.\",\n },\n },\n exclude: {\n schema: options.exclude ? z.string().default(options.exclude) : z.string().optional(),\n meta: {\n placeholder: \"<pattern>\",\n description: \"A glob patterns to exclude input files.\",\n },\n },\n outDir: {\n aliases: [\"o\"],\n schema: options.outDir ? z.string().default(options.outDir) : z.string(),\n meta: {\n placeholder: \"<path>\",\n description: \"Where to save the output files.\",\n },\n },\n },\n });\n\n convertFontsCommand.onExecute(async ({ options }) => {\n const { default: ttf2woff2 } = await import(\"ttf2woff2\");\n const fontFiles = globSync(options.fonts, { ignore: options.exclude, cwd: config.root });\n\n for (const inputPath of fontFiles) {\n Log.info(`Converting ${inputPath}...`);\n\n const inputBuffer = readFileSync(inputPath);\n const outputBuffer = ttf2woff2(inputBuffer);\n\n mkdirSync(options.outDir, { recursive: true });\n\n const fileName = replaceExtension(basename(inputPath), \".woff2\");\n const outputPath = join(options.outDir, fileName);\n\n writeFileSync(outputPath, outputBuffer);\n }\n });\n\n this.addCommand(convertFontsCommand);\n },\n };\n}\n","import { readFileSync } from \"node:fs\";\nimport * as fontKit from \"fontkit\";\n\nimport { relative, dirname, basename } from \"../../../utilities/path.ts\";\n\ninterface FontFaceOptions {\n /** Absolute or relative path to the font file (.ttf, .otf, .woff, .woff2) */\n fontPath: string;\n\n /** Absolute or relative path to the CSS file that will contain the @font-face rule */\n cssOutputPath: string;\n\n /**\n * Override font-display value\n *\n * @default \"swap\"\n */\n fontDisplay?: \"auto\" | \"block\" | \"swap\" | \"fallback\" | \"optional\";\n\n /** Override the font-family name instead of using the one extracted from the file */\n familyOverride?: string;\n}\n\ninterface FontFaceMeta {\n family: string;\n weight: string | number;\n style: \"normal\" | \"italic\" | \"oblique\";\n format: string;\n relativeSource: string;\n}\n\n// Only 400 and 700 have named CSS keywords; all other usWeightClass values\n// are emitted as plain numbers, which is valid CSS (e.g. font-weight: 300)\nconst WEIGHT_KEYWORDS: Partial<Record<number, string>> = {\n 400: \"normal\",\n 700: \"bold\",\n};\n\nfunction resolveWeight(usWeightClass: number): string | number {\n return WEIGHT_KEYWORDS[usWeightClass] ?? usWeightClass;\n}\n\nconst FORMAT_MAP: Record<string, string> = {\n ttf: \"truetype\",\n otf: \"opentype\",\n woff: \"woff\",\n woff2: \"woff2\",\n eot: \"embedded-opentype\",\n svg: \"svg\",\n};\n\nfunction detectFormat(fontPath: string): string {\n const extension = basename(fontPath).split(\".\").pop()?.toLowerCase() ?? \"\";\n return FORMAT_MAP[extension] ?? extension;\n}\n\nfunction resolveStyle(\n fsSelection: fontKit.Os2Table[\"fsSelection\"],\n macStyle: { italic?: boolean } | undefined\n): FontFaceMeta[\"style\"] {\n // fsSelection (OS/2 table) is the canonical source per the OpenType spec\n if (fsSelection.oblique) {\n return \"oblique\";\n }\n\n if (fsSelection.italic) {\n return \"italic\";\n }\n\n // macStyle (head table) as a fallback for older/legacy fonts\n if (macStyle?.italic) {\n return \"italic\";\n }\n\n return \"normal\";\n}\n\nfunction getPreferredFamilyName(font: fontKit.Font): string {\n return font.getName(\"preferredFamily\", \"en\") ?? font.getName(\"preferredFamily\", \"\") ?? font.familyName;\n}\n/**\n * Reads a font file, extracts metadata from its binary tables, and returns a ready-to-use CSS @font-face rule string plus a\n * structured metadata object.\n */\nexport function generateFontFace(options: FontFaceOptions) {\n const { fontPath, cssOutputPath, fontDisplay = \"swap\", familyOverride } = options;\n\n const buffer = readFileSync(fontPath);\n const font = fontKit.create(buffer) as fontKit.Font;\n\n // Extract metadata\n const family = familyOverride ?? getPreferredFamilyName(font);\n const os2 = font[\"OS/2\"];\n const weight = resolveWeight(os2.usWeightClass);\n\n // head.macStyle is not exposed in @types/fontkit so we cast carefully\n const headTable = (font as unknown as Record<string, unknown>)[\"head\"] as { macStyle?: { italic?: boolean } } | undefined;\n\n const style = resolveStyle(os2.fsSelection, headTable?.macStyle);\n const format = detectFormat(fontPath);\n\n const relativeSource = relative(dirname(cssOutputPath), fontPath);\n\n const css = [\n `@font-face {`,\n ` font-family: ${family.includes(\" \") ? `\"${family}\"` : family};`,\n ` font-style: ${style};`,\n ` font-weight: ${weight};`,\n ` src: url(\"${relativeSource}\") format(\"${format}\");`,\n ` font-display: ${fontDisplay};`,\n `}`,\n ].join(\"\\n\");\n\n return css;\n}\n","import { writeFileSync } from \"node:fs\";\nimport { globSync } from \"glob\";\nimport * as z from \"zod\";\n\nimport { Log } from \"../../../utilities/logger.ts\";\nimport { generateFontFace } from \"./generate-font-face.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface GenerateFontFacesCliPluginOptions {\n /**\n * The name of the command.\n *\n * @default \"fontface\"\n */\n command?: string;\n\n /**\n * The aliases of the command.\n *\n * @default [\"font\"]\n */\n aliases?: string[];\n\n /**\n * The default value of the `fonts` option.\n *\n * A glob pattern to match font files.\n */\n fonts?: string;\n\n /**\n * The default value of the `exclude` option.\n *\n * A glob patterns to exclude input files.\n */\n exclude?: string;\n\n /**\n * The default value of the `cssOut` option.\n *\n * Where to save the output CSS file.\n */\n cssOut?: string;\n\n /**\n * The default value of the `fontDisplay` option.\n *\n * @default \"swap\"\n */\n fontDisplay?: \"auto\" | \"block\" | \"swap\" | \"fallback\" | \"optional\";\n}\n\n/**\n * Adds the \"fontface\" command (aliased \"font\"): writes one stylesheet of \"@font-face\" rules for the fonts matched by \"--fonts\".\n *\n * Notes:\n *\n * - Family, weight and style are read from the font's own tables, not from its file name, and the format comes from the extension.\n * - The \"src\" path of each rule is written relative to \"--css-out\", and the file is overwritten as a whole on every run.\n * - The options given here become the defaults of the matching flags; \"--font-display\" falls back to \"swap\".\n * - Matching no font at all is reported and nothing is written.\n */\nexport function generateFontFacesCliPlugin(options: GenerateFontFacesCliPluginOptions = {}): Plugin {\n const name = options.command ?? \"fontface\";\n const aliases = options.aliases ?? [\"font\"];\n\n return {\n name: \"generate-font-faces-cli-plugin\",\n cli(config) {\n const fontFaceCommand = this.defineSubcommand({\n name,\n aliases,\n meta: {\n description: \"Generate @font-face rules for all fonts and save it to css file.\",\n },\n\n options: {\n fonts: {\n schema: options.fonts ? z.string().default(options.fonts) : z.string(),\n meta: {\n placeholder: \"<pattern>\",\n description: \"A glob pattern to match font files.\",\n },\n },\n exclude: {\n schema: options.exclude ? z.string().default(options.exclude) : z.string().optional(),\n meta: {\n placeholder: \"<pattern>\",\n description: \"A glob patterns to exclude input files.\",\n },\n },\n cssOut: {\n aliases: [\"o\"],\n schema: options.cssOut ? z.string().default(options.cssOut) : z.string(),\n meta: {\n placeholder: \"<path>\",\n description: \"Where to save the output CSS file.\",\n },\n },\n fontDisplay: {\n schema: z\n .union([z.literal(\"auto\"), z.literal(\"block\"), z.literal(\"swap\"), z.literal(\"fallback\"), z.literal(\"optional\")])\n .default(options.fontDisplay ?? \"swap\"),\n meta: {\n placeholder: \"<auto|block|swap|fallback|optional>\",\n description: \"The font display property.\",\n },\n },\n },\n });\n\n fontFaceCommand.onExecute(({ options }) => {\n const fontFiles = globSync(options.fonts, { ignore: options.exclude, cwd: config.root });\n\n if (fontFiles.length === 0) {\n Log.error(\"No font files found.\");\n return;\n }\n\n const cssResults: string[] = [];\n\n for (const fontPath of fontFiles) {\n const fontFace = generateFontFace({\n fontPath,\n cssOutputPath: options.cssOut,\n fontDisplay: options.fontDisplay,\n });\n\n cssResults.push(fontFace);\n }\n\n writeFileSync(options.cssOut, cssResults.join(\"\\n\\n\"));\n\n Log.success(`Generated ${options.cssOut}`);\n });\n\n this.addCommand(fontFaceCommand);\n },\n };\n}\n","const Color = {\n TRANSPARENT: 0,\n\n clampRGB: (value: number) => Color.clamp(Math.round(value), 0, 255),\n clamp: (value: number, min: number, max: number) => Math.max(min, Math.min(value, max)),\n\n // prettier-ignore\n red: (color: number) => (color >> 16) & 0xFF,\n\n green: (color: number) => (color >> 8) & 0xff,\n\n blue: (color: number) => color & 0xff,\n\n rgb(red: number, green: number, blue: number) {\n red = Color.clampRGB(red);\n green = Color.clampRGB(green);\n blue = Color.clampRGB(blue);\n\n return 0xff_00_00_00 | (red << 16) | (green << 8) | blue;\n },\n};\n\nexport default Color;\n","import { Cam } from \"../cam/cam.ts\";\nimport Color from \"./color.ts\";\n\nconst ColorUtilities = {\n XYZ_WHITE_REFERENCE_X: 95.047,\n XYZ_WHITE_REFERENCE_Y: 100,\n XYZ_WHITE_REFERENCE_Z: 108.883,\n\n constrain(amount: number, low: number, high: number) {\n return amount < low ? low : Math.min(amount, high);\n },\n\n /**\n * Converts a color from CIE XYZ to its RGB representation.\n *\n * This method expects the XYZ representation to use the D65 illuminant and the CIE 2° Standard Observer (1931).\n *\n * @param x X component value [0...95.047)\n * @param y Y component value [0...100)\n * @param z Z component value [0...108.883)\n * @returns Int containing the RGB representation\n */\n XYZToColor(x: number, y: number, z: number) {\n x = Color.clamp(x, 0, ColorUtilities.XYZ_WHITE_REFERENCE_X);\n y = Color.clamp(y, 0, ColorUtilities.XYZ_WHITE_REFERENCE_Y);\n z = Color.clamp(z, 0, ColorUtilities.XYZ_WHITE_REFERENCE_Z);\n\n let r = (x * 3.2406 + y * -1.5372 + z * -0.4986) / 100;\n let g = (x * -0.9689 + y * 1.8758 + z * 0.0415) / 100;\n let b = (x * 0.0557 + y * -0.204 + z * 1.057) / 100;\n\n r = r > 0.0031308 ? 1.055 * Math.pow(r, 1 / 2.4) - 0.055 : 12.92 * r;\n g = g > 0.0031308 ? 1.055 * Math.pow(g, 1 / 2.4) - 0.055 : 12.92 * g;\n b = b > 0.0031308 ? 1.055 * Math.pow(b, 1 / 2.4) - 0.055 : 12.92 * b;\n\n return Color.rgb(\n ColorUtilities.constrain(Math.round(r * 255), 0, 255),\n ColorUtilities.constrain(Math.round(g * 255), 0, 255),\n ColorUtilities.constrain(Math.round(b * 255), 0, 255)\n );\n },\n\n /**\n * Convert a color appearance model representation to an ARGB color.\n *\n * Note: the returned color may have a lower chroma than requested. Whether a chroma is available depends on luminance. For\n * example, there's no such thing as a high chroma light red, due to the limitations of our eyes and/or physics. If the\n * requested chroma is unavailable, the highest possible chroma at the requested luminance is returned.\n *\n * @param hue Hue, in degrees, in CAM coordinates\n * @param chroma Chroma in CAM coordinates.\n * @param lstar Perceptual luminance, L* in L_a_b*\n */\n CAMToColor(hue: number, chroma: number, lstar: number) {\n return Cam.getInt(hue, chroma, lstar);\n },\n};\n\nexport default ColorUtilities;\n","const MathUtilities = {\n lerp(start: number, stop: number, amount: number) {\n return start + (stop - start) * amount;\n },\n\n toRadians(degrees: number) {\n return degrees * (Math.PI / 180);\n },\n};\n\nexport default MathUtilities;\n","/*\n * This code was originally written in Java and has been converted to JavaScript.\n *\n * Original Java code source: [https://android.googlesource.com/platform/frameworks/base/+/refs/heads/main/core/java/com/android/internal/graphics/cam]\n *\n * Copyright (C) 2021 The Android Open Source Project.\n * The original code is licensed under the Apache License, Version 2.0.\n *\n * This JavaScript version is licensed under the MIT License.\n *\n * See the respective licenses for the specific terms, permissions, and limitations.\n */\nimport MathUtilities from \"../utils/math-utilities.ts\";\nimport { CamUtilities, Frame } from \"./cam.ts\";\n\n// eslint-disable-next-line unicorn/no-static-only-class\nexport default class HctSolver {\n /** Weights for transforming a set of linear RGB coordinates to Y in XYZ. */\n static Y_FROM_LINRGB: [number, number, number] = [0.2126, 0.7152, 0.0722];\n\n // Matrix used when converting from CAM16 to linear RGB.\n static LINRGB_FROM_SCALED_DISCOUNT: [[number, number, number], [number, number, number], [number, number, number]] = [\n [1373.2198709594231, -1100.4251190754821, -7.278681089101213],\n [-271.815969077903, 559.6580465940733, -32.46047482791194],\n [1.9622899599665666, -57.173814538844006, 308.7233197812385],\n ];\n\n /** Matrix used when converting from linear RGB to CAM16. */\n static SCALED_DISCOUNT_FROM_LINRGB: [[number, number, number], [number, number, number], [number, number, number]] = [\n [0.001200833568784504, 0.002389694492170889, 0.0002795742885861124],\n [0.0005891086651375999, 0.0029785502573438758, 0.0003270666104008398],\n [0.00010146692491640572, 0.0005364214359186694, 0.0032979401770712076],\n ];\n\n /**\n * Lookup table for plane in XYZ's Y axis (relative luminance) that corresponds to a given L* in L_a_b*. HCT's T is L*, and\n * XYZ's Y is directly correlated to linear RGB, this table allows us to thus find the intersection between HCT and RGB, giving\n * a solution to the RGB coordinates that correspond to a given set of HCT coordinates.\n */\n static CRITICAL_PLANES = [\n 0.015176349177441876, 0.045529047532325624, 0.07588174588720938, 0.10623444424209313, 0.13658714259697685,\n 0.16693984095186062, 0.19729253930674434, 0.2276452376616281, 0.2579979360165119, 0.28835063437139563, 0.3188300904430532,\n 0.350925934958123, 0.3848314933096426, 0.42057480301049466, 0.458183274052838, 0.4976837250274023, 0.5391024159806381,\n 0.5824650784040898, 0.6277969426914107, 0.6751227633498623, 0.7244668422128921, 0.775853049866786, 0.829304845476233,\n 0.8848452951698498, 0.942497089126609, 1.0022825574869039, 1.0642236851973577, 1.1283421258858297, 1.1946592148522128,\n 1.2631959812511864, 1.3339731595349034, 1.407011200216447, 1.4823302800086415, 1.5599503113873272, 1.6398909516233677,\n 1.7221716113234105, 1.8068114625156377, 1.8938294463134073, 1.9832442801866852, 2.075074464868551, 2.1693382909216234,\n 2.2660538449872063, 2.36523901573795, 2.4669114995532007, 2.5710888059345764, 2.6777882626779785, 2.7870270208169257,\n 2.898822059350997, 3.0131901897720907, 3.1301480604002863, 3.2497121605402226, 3.3718988244681087, 3.4967242352587946,\n 3.624204428461639, 3.754355295633311, 3.887192587735158, 4.022731918402185, 4.160988767090289, 4.301978482107941,\n 4.445716283538092, 4.592217266055746, 4.741496401646282, 4.893568542229298, 5.048448422192488, 5.20615066083972,\n 5.3666897647573375, 5.5300801301023865, 5.696336044816294, 5.865471690767354, 6.037501145825082, 6.212438385869475,\n 6.390297286737924, 6.571091626112461, 6.7548350853498045, 6.941541251256611, 7.131223617812143, 7.323895587840543,\n 7.5195704746346665, 7.7182615035334345, 7.919981813454504, 8.124744458384042, 8.332562408825165, 8.543448553206703,\n 8.757415699253682, 8.974476575321063, 9.194643831691977, 9.417930041841839, 9.644347703669503, 9.873909240696694,\n 10.106627003236781, 10.342513269534024, 10.58158024687427, 10.8238400726681, 11.069304815507364, 11.317986476196008,\n 11.569896988756009, 11.825048221409341, 12.083451977536606, 12.345119996613247, 12.610063955123938, 12.878295467455942,\n 13.149826086772048, 13.42466730586372, 13.702830557985108, 13.984327217668513, 14.269168601521828, 14.55736596900856,\n 14.848930523210871, 15.143873411576273, 15.44220572664832, 15.743938506781891, 16.04908273684337, 16.35764934889634,\n 16.66964922287304, 16.985093187232053, 17.30399201960269, 17.62635644741625, 17.95219714852476, 18.281524751807332,\n 18.614349837764564, 18.95068293910138, 19.290534541298456, 19.633915083172692, 19.98083495742689, 20.331304511189067,\n 20.685334046541502, 21.042933821039977, 21.404114048223256, 21.76888489811322, 22.137256497705877, 22.50923893145328,\n 22.884842241736916, 23.264076429332462, 23.6469514538663, 24.033477234264016, 24.42366364919083, 24.817520537484558,\n 25.21505769858089, 25.61628489293138, 26.021211842414342, 26.429848230738664, 26.842203703840827, 27.258287870275353,\n 27.678110301598522, 28.10168053274597, 28.529008062403893, 28.96010235337422, 29.39497283293396, 29.83362889318845,\n 30.276079891419332, 30.722335150426627, 31.172403958865512, 31.62629557157785, 32.08401920991837, 32.54558406207592,\n 33.010999283389665, 33.4802739966603, 33.953417292456834, 34.430438229418264, 34.911345834551085, 35.39614910352207,\n 35.88485700094671, 36.37747846067349, 36.87402238606382, 37.37449765026789, 37.87891309649659, 38.38727753828926,\n 38.89959975977785, 39.41588851594697, 39.93615253289054, 40.460400508064545, 40.98864111053629, 41.520882981230194,\n 42.05713473317016, 42.597404951718396, 43.141702194811224, 43.6900349931913, 44.24241185063697, 44.798841244188324,\n 45.35933162437017, 45.92389141541209, 46.49252901546552, 47.065252796817916, 47.64207110610409, 48.22299226451468,\n 48.808024568002054, 49.3971762874833, 49.9904556690408, 50.587870934119984, 51.189430279724725, 51.79514187861014,\n 52.40501387947288, 53.0190544071392, 53.637271562750364, 54.259673423945976, 54.88626804504493, 55.517063457223934,\n 56.15206766869424, 56.79128866487574, 57.43473440856916, 58.08241284012621, 58.734331877617365, 59.39049941699807,\n 60.05092333227251, 60.715611475655585, 61.38457167773311, 62.057811747619894, 62.7353394731159, 63.417162620860914,\n 64.10328893648692, 64.79372614476921, 65.48848194977529, 66.18756403501224, 66.89098006357258, 67.59873767827808,\n 68.31084450182222, 69.02730813691093, 69.74813616640164, 70.47333615344107, 71.20291564160104, 71.93688215501312,\n 72.67524319850172, 73.41800625771542, 74.16517879925733, 74.9167682708136, 75.67278210128072, 76.43322770089146,\n 77.1981124613393, 77.96744375590167, 78.74122893956174, 79.51947534912904, 80.30219030335869, 81.08938110306934,\n 81.88105503125999, 82.67721935322541, 83.4778813166706, 84.28304815182372, 85.09272707154808, 85.90692527145302,\n 86.72564993000343, 87.54890820862819, 88.3767072518277, 89.2090541872801, 90.04595612594655, 90.88742016217518,\n 91.73345337380438, 92.58406282226491, 93.43925555268066, 94.29903859396902, 95.16341895893969, 96.03240364439274,\n 96.9059996312159, 97.78421388448044, 98.6670533535366, 99.55452497210776,\n ];\n\n /**\n * Sanitizes a degree measure as a floating-point number.\n *\n * @returns A degree measure between 0.0 (inclusive) and 360.0 (exclusive).\n */\n static sanitizeDegreesDouble(degrees: number) {\n degrees %= 360;\n if (degrees < 0) {\n degrees += 360;\n }\n return degrees;\n }\n\n /** Equation used in CAM16 conversion that removes the effect of chromatic adaptation. */\n static inverseChromaticAdaptation(adapted: number) {\n const adaptedAbs = Math.abs(adapted);\n const base = Math.max(0, (27.13 * adaptedAbs) / (400 - adaptedAbs));\n\n return CamUtilities.signum(adapted) * Math.pow(base, 1 / 0.42);\n }\n\n /**\n * Finds a color with the given hue, chroma, and Y.\n *\n * @param hueRadians The desired hue in radians.\n * @param chroma The desired chroma.\n * @param y The desired Y.\n * @returns The desired color as a hexadecimal integer, if found; 0 otherwise.\n */\n static findResultByJ(hueRadians: number, chroma: number, y: number) {\n // Initial estimate of j.\n let index = Math.sqrt(y) * 11;\n\n // ===========================================================\n // Operations inlined from Cam16 to avoid repeated calculation\n // ===========================================================\n const viewingConditions = Frame.DEFAULT,\n tInnerCoeff = 1 / Math.pow(1.64 - Math.pow(0.29, viewingConditions.getN()), 0.73),\n ehue = 0.25 * (Math.cos(hueRadians + 2) + 3.8),\n p1 = ehue * (50_000 / 13) * viewingConditions.getNc() * viewingConditions.getNcb(),\n hSin = Math.sin(hueRadians),\n hCos = Math.cos(hueRadians);\n\n for (let iterationRound = 0; iterationRound < 5; iterationRound++) {\n // ===========================================================\n // Operations inlined from Cam16 to avoid repeated calculation\n // ===========================================================\n const indexNormalized = index / 100,\n alpha = chroma === 0 || index === 0 ? 0 : chroma / Math.sqrt(indexNormalized),\n t = Math.pow(alpha * tInnerCoeff, 1 / 0.9),\n acExponent = 1 / viewingConditions.getC() / viewingConditions.getZ(),\n ac = viewingConditions.getAw() * Math.pow(indexNormalized, acExponent),\n p2 = ac / viewingConditions.getNbb(),\n gamma = (23 * (p2 + 0.305) * t) / (23 * p1 + 11 * t * hCos + 108 * t * hSin),\n a = gamma * hCos,\n b = gamma * hSin,\n rA = (460 * p2 + 451 * a + 288 * b) / 1403,\n gA = (460 * p2 - 891 * a - 261 * b) / 1403,\n bA = (460 * p2 - 220 * a - 6300 * b) / 1403,\n rCScaled = this.inverseChromaticAdaptation(rA),\n gCScaled = this.inverseChromaticAdaptation(gA),\n bCScaled = this.inverseChromaticAdaptation(bA),\n matrix = this.LINRGB_FROM_SCALED_DISCOUNT,\n linrgbR = rCScaled * matrix[0][0] + gCScaled * matrix[0][1] + bCScaled * matrix[0][2],\n linrgbG = rCScaled * matrix[1][0] + gCScaled * matrix[1][1] + bCScaled * matrix[1][2],\n linrgbB = rCScaled * matrix[2][0] + gCScaled * matrix[2][1] + bCScaled * matrix[2][2];\n\n // ===========================================================\n // Operations inlined from Cam16 to avoid repeated calculation\n // ===========================================================\n if (linrgbR < 0 || linrgbG < 0 || linrgbB < 0) {\n return 0;\n }\n\n const kR = this.Y_FROM_LINRGB[0],\n kG = this.Y_FROM_LINRGB[1],\n kB = this.Y_FROM_LINRGB[2],\n fnj = kR * linrgbR + kG * linrgbG + kB * linrgbB;\n\n if (fnj <= 0) {\n return 0;\n }\n if (iterationRound === 4 || Math.abs(fnj - y) < 0.002) {\n if (linrgbR > 100.01 || linrgbG > 100.01 || linrgbB > 100.01) {\n return 0;\n }\n return CamUtilities.argbFromLinrgbComponents(linrgbR, linrgbG, linrgbB);\n }\n\n // Iterates with Newton method,\n // Using 2 * fn(j) / j as the approximation of fn'(j)\n index -= ((fnj - y) * index) / (2 * fnj);\n }\n\n return 0;\n }\n\n /**\n * Finds an sRGB color with the given hue, chroma, and L*, if possible.\n *\n * @param hueDegrees The desired hue, in degrees.\n * @param chroma The desired chroma.\n * @param lstar The desired L*.\n * @returns A hexadecimal representing the sRGB color. The color has sufficiently close hue, chroma, and L* to the desired\n * values, if possible; otherwise, the hue and L* will be sufficiently close, and chroma will be maximized.\n */\n static solveToInt(hueDegrees: number, chroma: number, lstar: number) {\n if (chroma < 0.0001 || lstar < 0.0001 || lstar > 99.9999) {\n return CamUtilities.argbFromLstar(lstar);\n }\n\n hueDegrees = this.sanitizeDegreesDouble(hueDegrees);\n const hueRadians = MathUtilities.toRadians(hueDegrees);\n const y = CamUtilities.yFromLstar(lstar);\n\n const exactAnswer = this.findResultByJ(hueRadians, chroma, y);\n\n if (exactAnswer !== 0) {\n return exactAnswer;\n }\n\n return this.bisectToLimit(y, hueRadians);\n }\n\n /** Ensure X is between 0 and 100. */\n static isBounded(x: number) {\n return x >= 0 && x <= 100;\n }\n\n /**\n * Returns the nth possible vertex of the polygonal intersection.\n *\n * @param y The Y value of the plane.\n * @param n The zero-based index of the point. 0 <= n <= 11.\n * @returns The nth possible vertex of the polygonal intersection of the y plane and the RGB cube in linear RGB coordinates, if\n * it exists. If the possible vertex lies outside of the cube, [-1.0, -1.0, -1.0] is returned.\n */\n static nthVertex(y: number, n: number): [number, number, number] {\n const kR = this.Y_FROM_LINRGB[0],\n kG = this.Y_FROM_LINRGB[1],\n kB = this.Y_FROM_LINRGB[2],\n coordA = n % 4 <= 1 ? 0 : 100,\n coordB = n % 2 === 0 ? 0 : 100;\n\n if (n < 4) {\n const g = coordA;\n const b = coordB;\n const r = (y - g * kG - b * kB) / kR;\n return this.isBounded(r) ? [r, g, b] : [-1, -1, -1];\n }\n if (n < 8) {\n const b = coordA;\n const r = coordB;\n const g = (y - r * kR - b * kB) / kG;\n return this.isBounded(g) ? [r, g, b] : [-1, -1, -1];\n }\n\n const r = coordA;\n const g = coordB;\n const b = (y - r * kR - g * kG) / kB;\n return this.isBounded(b) ? [r, g, b] : [-1, -1, -1];\n }\n\n static chromaticAdaptation(component: number) {\n const af = Math.pow(Math.abs(component), 0.42);\n return (CamUtilities.signum(component) * 400 * af) / (af + 27.13);\n }\n\n /**\n * Returns the hue of a linear RGB color in CAM16.\n *\n * @param linrgb The linear RGB coordinates of a color.\n * @returns The hue of the color in CAM16, in radians.\n */\n static hueOf(linrgb: [number, number, number]) {\n // Calculate scaled discount components using in-lined matrix multiplication to avoid\n // an array allocation.\n const matrix = this.SCALED_DISCOUNT_FROM_LINRGB,\n row = linrgb,\n rD = linrgb[0] * matrix[0][0] + row[1] * matrix[0][1] + row[2] * matrix[0][2],\n gD = linrgb[0] * matrix[1][0] + row[1] * matrix[1][1] + row[2] * matrix[1][2],\n bD = linrgb[0] * matrix[2][0] + row[1] * matrix[2][1] + row[2] * matrix[2][2];\n\n const rA = this.chromaticAdaptation(rD),\n gA = this.chromaticAdaptation(gD),\n bA = this.chromaticAdaptation(bD);\n\n // redness-greenness\n const a = (11 * rA + -12 * gA + bA) / 11;\n\n // yellowness-blueness\n const b = (rA + gA - 2 * bA) / 9;\n\n return Math.atan2(b, a);\n }\n\n /**\n * Sanitizes a small enough angle in radians.\n *\n * @param angle An angle in radians; must not deviate too much from 0.\n * @returns A coterminal angle between 0 and 2pi.\n */\n static sanitizeRadians(angle: number) {\n return (angle + Math.PI * 8) % (Math.PI * 2);\n }\n\n /**\n * Cyclic order is the idea that 330° → 5° → 200° is in order, but, 180° → 270° → 210° is not. Visually, A B and C are angles,\n * and they are in cyclic order if travelling from A to C in a way that increases angle (ex. counter-clockwise if +x axis = 0\n * degrees and +y = 90) means you must cross B.\n *\n * @param a First angle in possibly cyclic triplet\n * @param b Second angle in possibly cyclic triplet\n * @param c Third angle in possibly cyclic triplet\n * @returns True if B is between A and C\n */\n static areInCyclicOrder(a: number, b: number, c: number) {\n const deltaAB = this.sanitizeRadians(b - a);\n const deltaAC = this.sanitizeRadians(c - a);\n\n return deltaAB < deltaAC;\n }\n\n /**\n * Finds the segment containing the desired color.\n *\n * @param y The Y value of the color.\n * @param targetHue The hue of the color.\n * @returns A list of two sets of linear RGB coordinates, each corresponding to an endpoint of the segment containing the\n * desired color.\n */\n static bisectToSegment(y: number, targetHue: number) {\n let left: [number, number, number] = [-1, -1, -1],\n right = left,\n leftHue = 0,\n rightHue = 0,\n isInitialized = false,\n isUncut = true;\n\n for (let n = 0; n < 12; n++) {\n const mid = this.nthVertex(y, n);\n if (mid[0] < 0) {\n continue;\n }\n\n const midHue = this.hueOf(mid);\n if (!isInitialized) {\n left = mid;\n right = mid;\n leftHue = midHue;\n rightHue = midHue;\n isInitialized = true;\n continue;\n }\n\n if (isUncut || this.areInCyclicOrder(leftHue, midHue, rightHue)) {\n isUncut = false;\n if (this.areInCyclicOrder(leftHue, targetHue, midHue)) {\n right = mid;\n rightHue = midHue;\n } else {\n left = mid;\n leftHue = midHue;\n }\n }\n }\n\n return [left, right] as [[number, number, number], [number, number, number]];\n }\n\n static criticalPlaneBelow(x: number) {\n return Math.floor(x - 0.5);\n }\n\n static criticalPlaneAbove(x: number) {\n return Math.ceil(x - 0.5);\n }\n\n /**\n * Delinearizes an RGB component, returning a floating-point number.\n *\n * @param rgbComponent 0.0 <= rgb_component <= 100.0, represents linear R/G/B channel\n * @returns 0.0 <= output <= 255.0, color channel converted to regular RGB space\n */\n static trueDelinearized(rgbComponent: number) {\n const normalized = rgbComponent / 100;\n\n const delinearized = normalized <= 0.0031308 ? normalized * 12.92 : 1.055 * Math.pow(normalized, 1 / 2.4) - 0.055;\n\n return delinearized * 255;\n }\n\n /**\n * Find an intercept using linear interpolation.\n *\n * @param source The starting number.\n * @param mid The number in the middle.\n * @param target The ending number.\n * @returns A number t such that lerp(source, target, t) = mid.\n */\n static intercept(source: number, mid: number, target: number) {\n if (target === source) return target;\n\n return (mid - source) / (target - source);\n }\n\n /**\n * Linearly interpolate between two points in three dimensions.\n *\n * @param source Three dimensions representing the starting point\n * @param t The percentage to travel between source and target, from 0 to 1\n * @param target Three dimensions representing the end point\n * @returns Three dimensions representing the point t percent from source to target.\n */\n static lerpPoint(source: [number, number, number], t: number, target: [number, number, number]) {\n return [\n source[0] + (target[0] - source[0]) * t,\n source[1] + (target[1] - source[1]) * t,\n source[2] + (target[2] - source[2]) * t,\n ] as [number, number, number];\n }\n\n /**\n * Intersects a segment with a plane.\n *\n * @param source The coordinates of point A.\n * @param coordinate The R-, G-, or B-coordinate of the plane.\n * @param target The coordinates of point B.\n * @param axis The axis the plane is perpendicular with. (0: R, 1: G, 2: B)\n * @returns The intersection point of the segment AB with the plane R=coordinate, G=coordinate, or B=coordinate\n */\n static setCoordinate(source: [number, number, number], coordinate: number, target: [number, number, number], axis: 0 | 1 | 2) {\n const t = this.intercept(source[axis], coordinate, target[axis]);\n return this.lerpPoint(source, t, target);\n }\n\n /**\n * Finds a color with the given Y and hue on the boundary of the cube.\n *\n * @param y The Y value of the color.\n * @param targetHue The hue of the color.\n * @returns The desired color, in linear RGB coordinates.\n */\n static bisectToLimit(y: number, targetHue: number) {\n const segment = this.bisectToSegment(y, targetHue);\n\n let left = segment[0],\n leftHue = this.hueOf(left),\n right = segment[1];\n\n for (let axis = 0 as 0 | 1 | 2; axis < 3; axis++) {\n if (left[axis] === right[axis]) {\n continue;\n }\n\n let lPlane: number;\n let rPlane: number;\n\n if (left[axis] < right[axis]) {\n lPlane = this.criticalPlaneBelow(this.trueDelinearized(left[axis]));\n rPlane = this.criticalPlaneAbove(this.trueDelinearized(right[axis]));\n } else {\n lPlane = this.criticalPlaneAbove(this.trueDelinearized(left[axis]));\n rPlane = this.criticalPlaneBelow(this.trueDelinearized(right[axis]));\n }\n\n for (let index = 0; index < 8; index++) {\n if (Math.abs(rPlane - lPlane) <= 1) {\n break;\n }\n\n const mPlane = Math.floor((lPlane + rPlane) / 2);\n const midPlaneCoordinate = this.CRITICAL_PLANES[mPlane] ?? 0;\n\n const mid: [number, number, number] = this.setCoordinate(left, midPlaneCoordinate, right, axis);\n const midHue = this.hueOf(mid);\n if (this.areInCyclicOrder(leftHue, targetHue, midHue)) {\n right = mid;\n rPlane = mPlane;\n } else {\n left = mid;\n leftHue = midHue;\n lPlane = mPlane;\n }\n }\n }\n\n return CamUtilities.argbFromLinrgbComponents((left[0] + right[0]) / 2, (left[1] + right[1]) / 2, (left[2] + right[2]) / 2);\n }\n}\n","/*\n * This code was originally written in Java and has been converted to JavaScript.\n *\n * Original Java code source: [https://android.googlesource.com/platform/frameworks/base/+/refs/heads/main/core/java/com/android/internal/graphics/cam]\n *\n * Copyright (C) 2021 The Android Open Source Project.\n * The original code is licensed under the Apache License, Version 2.0.\n *\n * This JavaScript version is licensed under the MIT License.\n *\n * See the respective licenses for the specific terms, permissions, and limitations.\n */\nimport ColorUtilities from \"../utils/color-utilities.ts\";\nimport Color from \"../utils/color.ts\";\nimport MathUtilities from \"../utils/math-utilities.ts\";\nimport HctSolver from \"./hct-solver.ts\";\n\n/**\n * A color appearance model, based on CAM16, extended to use L* as the lightness dimension, and coupled to a gamut mapping\n * algorithm. Creates a color system, enables a digital design system.\n */\nexport class Cam {\n // When the delta between the floor & ceiling of a binary search for chroma is less than this,\n // the binary search terminates.\n static CHROMA_SEARCH_ENDPOINT = 0.4;\n\n // When the delta between the floor & ceiling of a binary search for J, lightness in CAM16,\n // is less than this, the binary search terminates.\n static LIGHTNESS_SEARCH_ENDPOINT = 0.01;\n\n // The maximum difference between the requested L* and the L* returned.\n static DL_MAX = 0.2;\n\n // The maximum color distance, in CAM16-UCS, between a requested color and the color returned.\n static DE_MAX = 1;\n\n /** The maximum difference between the requested L* and the L* returned. */\n DL_MAX = 0.2;\n /** When the delta between the floor & ceiling of a binary search for chroma is less than this, the binary search terminates. */\n CHROMA_SEARCH_ENDPOINT = 0.4;\n /**\n * When the delta between the floor & ceiling of a binary search for J, lightness in CAM16, is less than this, the binary search\n * terminates.\n */\n LIGHTNESS_SEARCH_ENDPOINT = 0.01;\n /**\n * SRGB specification has D65 whitepoint - Stokes, Anderson, Chandrasekar, Motta - A Standard Default Color Space for the\n * Internet: sRGB, 1996\n */\n WHITE_POINT_D65: [number, number, number] = [95.047, 100, 108.883];\n\n // CAM16 color dimensions, see getters for documentation.\n mHue: number;\n mChroma: number;\n mJ: number;\n mQ: number;\n mM: number;\n mS: number;\n\n // Coordinates in UCS space. Used to determine color distance, like delta E equations in L*a*b*.\n mJstar: number;\n mAstar: number;\n mBstar: number;\n\n constructor(\n hue: number,\n chroma: number,\n index: number,\n q: number,\n m: number,\n s: number,\n jstar: number,\n astar: number,\n bstar: number\n ) {\n this.mHue = hue;\n this.mChroma = chroma;\n this.mJ = index;\n this.mQ = q;\n this.mM = m;\n this.mS = s;\n this.mJstar = jstar;\n this.mAstar = astar;\n this.mBstar = bstar;\n }\n\n /** Hue in CAM16 */\n getHue() {\n return this.mHue;\n }\n\n /** Chroma in CAM16 */\n getChroma() {\n return this.mChroma;\n }\n\n /** Lightness in CAM16 */\n getJ() {\n return this.mJ;\n }\n\n /** A* coordinate in CAM16-UCS */\n getAstar() {\n return this.mAstar;\n }\n\n /** Lightness coordinate in CAM16-UCS */\n getJstar() {\n return this.mJstar;\n }\n\n /** B* coordinate in CAM16-UCS */\n getBstar() {\n return this.mBstar;\n }\n\n /**\n * Create a CAM from lightness, chroma, and hue coordinates. It is assumed those coordinates were measured in the sRGB standard\n * frame.\n */\n static fromJch(index: number, c: number, h: number) {\n return this.fromJchInFrame(index, c, h);\n }\n\n /** Create a CAM from lightness, chroma, and hue coordinates, and also specify the frame in which the color is being viewed. */\n static fromJchInFrame(index: number, c: number, h: number) {\n const q = (4 / Frame.DEFAULT.getC()) * Math.sqrt(index / 100) * (Frame.DEFAULT.getAw() + 4) * Frame.DEFAULT.getFlRoot();\n const m = c * Frame.DEFAULT.getFlRoot();\n const alpha = c / Math.sqrt(index / 100);\n const s = 50 * Math.sqrt((alpha * Frame.DEFAULT.getC()) / (Frame.DEFAULT.getAw() + 4));\n\n const hueRadians = (h * Math.PI) / 180;\n const jstar = ((1 + 100 * 0.007) * index) / (1 + 0.007 * index);\n const mstar = (1 / 0.0228) * Math.log(1 + 0.0228 * m);\n const astar = mstar * Math.cos(hueRadians);\n const bstar = mstar * Math.sin(hueRadians);\n return new Cam(h, c, index, q, m, s, jstar, astar, bstar);\n }\n\n /** Returns perceived color as an ARGB integer, as viewed in standard sRGB frame. */\n viewedInSrgb() {\n return this.viewed(Frame.DEFAULT);\n }\n\n /** Returns color perceived in a frame as an ARGB integer. */\n viewed(frame: Frame) {\n const alpha = this.getChroma() === 0 || this.getJ() === 0 ? 0 : this.getChroma() / Math.sqrt(this.getJ() / 100);\n\n const t = Math.pow(alpha / Math.pow(1.64 - Math.pow(0.29, frame.getN()), 0.73), 1 / 0.9),\n hRad = (this.getHue() * Math.PI) / 180;\n\n const ehue = 0.25 * (Math.cos(hRad + 2) + 3.8),\n ac = frame.getAw() * Math.pow(this.getJ() / 100, 1 / frame.getC() / frame.getZ()),\n p1 = ehue * (50_000 / 13) * frame.getNc() * frame.getNcb(),\n p2 = ac / frame.getNbb();\n\n const hSin = Math.sin(hRad),\n hCos = Math.cos(hRad);\n\n const gamma = (23 * (p2 + 0.305) * t) / (23 * p1 + 11 * t * hCos + 108 * t * hSin),\n a = gamma * hCos,\n b = gamma * hSin,\n rA = (460 * p2 + 451 * a + 288 * b) / 1403,\n gA = (460 * p2 - 891 * a - 261 * b) / 1403,\n bA = (460 * p2 - 220 * a - 6300 * b) / 1403;\n\n const rCBase = Math.max(0, (27.13 * Math.abs(rA)) / (400 - Math.abs(rA))),\n rC = Math.sign(rA) * (100 / frame.getFl()) * Math.pow(rCBase, 1 / 0.42),\n gCBase = Math.max(0, (27.13 * Math.abs(gA)) / (400 - Math.abs(gA))),\n gC = Math.sign(gA) * (100 / frame.getFl()) * Math.pow(gCBase, 1 / 0.42),\n bCBase = Math.max(0, (27.13 * Math.abs(bA)) / (400 - Math.abs(bA))),\n bC = Math.sign(bA) * (100 / frame.getFl()) * Math.pow(bCBase, 1 / 0.42),\n rF = rC / frame.getRgbD()[0],\n gF = gC / frame.getRgbD()[1],\n bF = bC / frame.getRgbD()[2];\n\n const matrix = CamUtilities.CAM16RGB_TO_XYZ,\n x = rF * matrix[0][0] + gF * matrix[0][1] + bF * matrix[0][2],\n y = rF * matrix[1][0] + gF * matrix[1][1] + bF * matrix[1][2],\n z = rF * matrix[2][0] + gF * matrix[2][1] + bF * matrix[2][2];\n\n return ColorUtilities.XYZToColor(x, y, z);\n }\n\n /**\n * Distance in CAM16-UCS space between two colors.\n *\n * Much like L_a_b* was designed to measure distance between colors, the CAM16 standard defined a color space called CAM16-UCS\n * to measure distance between CAM16 colors.\n */\n distance(other: Cam) {\n const dJ = this.getJstar() - other.getJstar(),\n dA = this.getAstar() - other.getAstar(),\n dB = this.getBstar() - other.getBstar(),\n dEPrime = Math.hypot(dJ, dA, dB),\n dE = 1.41 * Math.pow(dEPrime, 0.63);\n return dE;\n }\n\n /**\n * Find J, lightness in CAM16 color space, that creates a color with L* = `lstar` in the L_a_b* color space. Returns null if no\n * J could be found that generated a color with L* `lstar`.\n */\n static findCamByJ(hue: number, chroma: number, lstar: number) {\n let low = 0,\n high = 100,\n mid,\n bestdL = 1000,\n bestdE = 1000;\n\n let bestCam: Cam | null = null;\n while (Math.abs(low - high) > this.LIGHTNESS_SEARCH_ENDPOINT) {\n mid = low + (high - low) / 2;\n\n // Create the intended CAM color\n const camBeforeClip = this.fromJch(mid, chroma, hue);\n\n // Convert the CAM color to RGB. If the color didn't fit in RGB, during the conversion,\n // the initial RGB values will be outside 0 to 255. The final RGB values are clipped to\n // 0 to 255, distorting the intended color.\n const clipped = camBeforeClip.viewedInSrgb();\n const clippedLstar = CamUtilities.lstarFromInt(clipped);\n const dL = Math.abs(lstar - clippedLstar);\n\n // If the clipped color's L* is within error margin...\n if (dL < this.DL_MAX) {\n // ...check if the CAM equivalent of the clipped color is far away from intended CAM\n // color. For the intended color, use lightness and chroma from the clipped color,\n // and the intended hue. Callers are wondering what the lightness is, they know\n // chroma may be distorted, so the only concern here is if the hue slipped too far.\n const camClipped = this.fromInt(clipped);\n const dE = camClipped.distance(this.fromJch(camClipped.getJ(), camClipped.getChroma(), hue));\n if (dE <= this.DE_MAX) {\n bestdL = dL;\n bestdE = dE;\n bestCam = camClipped;\n }\n }\n\n // If there's no error at all, there's no need to search more.\n //\n // Note: this happens much more frequently than expected, but this is a very delicate\n // property which relies on extremely precise sRGB <=> XYZ calculations, as well as fine\n // tuning of the constants that determine error margins and when the binary search can\n // terminate.\n if (bestdL === 0 && bestdE === 0) {\n break;\n }\n\n if (clippedLstar < lstar) {\n low = mid;\n } else {\n high = mid;\n }\n }\n\n return bestCam;\n }\n\n /**\n * Given a hue & chroma in CAM16, L* in L_a_b*, return an ARGB integer. The chroma of the color returned may, and frequently\n * will, be lower than requested. Assumes the color is viewed in the frame defined by the sRGB standard.\n */\n static getInt(hue: number, chroma: number, lstar: number) {\n return this.getInt_(hue, chroma, lstar, Frame.DEFAULT);\n }\n\n /**\n * Given a hue & chroma in CAM16, L* in L_a_b*, and the frame in which the color will be viewed, return an ARGB integer.\n *\n * The chroma of the color returned may, and frequently will, be lower than requested. This is a fundamental property of color\n * that cannot be worked around by engineering. For example, a red hue, with high chroma, and high L* does not exist: red hues\n * have a maximum chroma below 10 in light shades, creating pink.\n */\n static getInt_(hue: number, chroma: number, lstar: number, frame: Frame) {\n // This is a crucial routine for building a color system, CAM16 itself is not sufficient.\n //\n // * Why these dimensions?\n // Hue and chroma from CAM16 are used because they're the most accurate measures of those\n // quantities. L* from L*a*b* is used because it correlates with luminance, luminance is\n // used to measure contrast for a11y purposes, thus providing a key constraint on what\n // colors\n // can be used.\n //\n // * Why is this routine required to build a color system?\n // In all perceptually accurate color spaces (i.e. L*a*b* and later), `chroma` may be\n // impossible for a given `hue` and `lstar`.\n // For example, a high chroma light red does not exist - chroma is limited to below 10 at\n // light red shades, we call that pink. High chroma light green does exist, but not dark\n // Also, when converting from another color space to RGB, the color may not be able to be\n // represented in RGB. In those cases, the conversion process ends with RGB values\n // outside 0-255\n // The vast majority of color libraries surveyed simply round to 0 to 255. That is not an\n // option for this library, as it distorts the expected luminance, and thus the expected\n // contrast needed for a11y\n //\n // * What does this routine do?\n // Dealing with colors in one color space not fitting inside RGB is, loosely referred to as\n // gamut mapping or tone mapping. These algorithms are traditionally idiosyncratic, there is\n // no universal answer. However, because the intent of this library is to build a system for\n // digital design, and digital design uses luminance to measure contrast/a11y, we have one\n // very important constraint that leads to an objective algorithm: the L* of the returned\n // color _must_ match the requested L*.\n //\n // Intuitively, if the color must be distorted to fit into the RGB gamut, and the L*\n // requested *must* be fulfilled, than the hue or chroma of the returned color will need\n // to be different from the requested hue/chroma.\n //\n // After exploring both options, it was more intuitive that if the requested chroma could\n // not be reached, it used the highest possible chroma. The alternative was finding the\n // closest hue where the requested chroma could be reached, but that is not nearly as\n // intuitive, as the requested hue is so fundamental to the color description.\n\n // If the color doesn't have meaningful chroma, return a gray with the requested Lstar.\n //\n // Yellows are very chromatic at L = 100, and blues are very chromatic at L = 0. All the\n // other hues are white at L = 100, and black at L = 0. To preserve consistency for users of\n // this system, it is better to simply return white at L* > 99, and black and L* < 0.\n if (frame === Frame.DEFAULT) {\n // If the viewing conditions are the same as the default sRGB-like viewing conditions,\n // skip to using HctSolver: it uses geometrical insights to find the closest in-gamut\n // match to hue/chroma/lstar.\n return HctSolver.solveToInt(hue, chroma, lstar);\n }\n\n if (chroma < 1 || Math.round(lstar) <= 0 || Math.round(lstar) >= 100) {\n return CamUtilities.intFromLstar(lstar);\n }\n\n hue = hue < 0 ? 0 : Math.min(360, hue);\n\n // The highest chroma possible. Updated as binary search proceeds.\n let high = chroma;\n\n // The guess for the current binary search iteration. Starts off at the highest chroma,\n // thus, if a color is possible at the requested chroma, the search can stop after one try.\n let mid = chroma;\n let low = 0;\n let isFirstLoop = true;\n\n let answer: Cam | null = null;\n\n while (Math.abs(low - high) >= this.CHROMA_SEARCH_ENDPOINT) {\n // Given the current chroma guess, mid, and the desired hue, find J, lightness in\n // CAM16 color space, that creates a color with L* = `lstar` in the L*a*b* color space.\n const possibleAnswer = this.findCamByJ(hue, mid, lstar);\n\n if (isFirstLoop) {\n if (possibleAnswer == undefined) {\n // If this binary search iteration was the first iteration, and this point\n // has been reached, it means the requested chroma was not available at the\n // requested hue and L*.\n // Proceed to a traditional binary search that starts at the midpoint between\n // the requested chroma and 0.\n isFirstLoop = false;\n mid = low + (high - low) / 2;\n continue;\n }\n return possibleAnswer.viewed(frame);\n }\n\n if (possibleAnswer == undefined) {\n // There isn't a CAM16 J that creates a color with L* `lstar`. Try a lower chroma.\n high = mid;\n } else {\n answer = possibleAnswer;\n // It is possible to create a color. Try higher chroma.\n low = mid;\n }\n\n mid = low + (high - low) / 2;\n }\n\n // There was no answer: meaning, for the desired hue, there was no chroma low enough to\n // generate a color with the desired L*.\n // All values of L* are possible when there is 0 chroma. Return a color with 0 chroma, i.e.\n // a shade of gray, with the desired L*.\n if (answer == undefined) {\n return CamUtilities.intFromLstar(lstar);\n }\n\n return answer.viewed(frame);\n }\n\n static intFromLstar(lstar: number) {\n if (lstar < 1) {\n return 0xff_00_00_00;\n }\n if (lstar > 99) {\n return 0xff_ff_ff_ff;\n }\n\n // XYZ to LAB conversion routine, assume a and b are 0.\n const fy = (lstar + 16) / 116;\n\n // fz = fx = fy because a and b are 0\n const fz = fy,\n fx = fy;\n\n const kappa = 24_389 / 27,\n epsilon = 216 / 24_389,\n isLExceedsEpsilonKappa = lstar > 8,\n yT = isLExceedsEpsilonKappa ? fy * fy * fy : lstar / kappa,\n isCubeExceedEpsilon = fy * fy * fy > epsilon,\n xT = isCubeExceedEpsilon ? fx * fx * fx : (116 * fx - 16) / kappa,\n zT = isCubeExceedEpsilon ? fz * fz * fz : (116 * fx - 16) / kappa;\n\n return ColorUtilities.XYZToColor(\n xT * CamUtilities.WHITE_POINT_D65[0],\n yT * CamUtilities.WHITE_POINT_D65[1],\n zT * CamUtilities.WHITE_POINT_D65[2]\n );\n }\n\n static fromIntInFrame(argb: number, frame: Frame) {\n // Transform ARGB int to XYZ\n const xyz: [number, number, number] = CamUtilities.xyzFromInt(argb);\n\n // Transform XYZ to 'cone'/'rgb' responses\n const matrix = CamUtilities.XYZ_TO_CAM16RGB,\n rT: number = xyz[0] * matrix[0][0] + xyz[1] * matrix[0][1] + xyz[2] * matrix[0][2],\n gT: number = xyz[0] * matrix[1][0] + xyz[1] * matrix[1][1] + xyz[2] * matrix[1][2],\n bT: number = xyz[0] * matrix[2][0] + xyz[1] * matrix[2][1] + xyz[2] * matrix[2][2];\n\n // Discount illuminant\n const rD = frame.getRgbD()[0] * rT,\n gD = frame.getRgbD()[1] * gT,\n bD = frame.getRgbD()[2] * bT;\n\n // Chromatic adaptation\n const rAF = Math.pow((frame.getFl() * Math.abs(rD)) / 100, 0.42),\n gAF = Math.pow((frame.getFl() * Math.abs(gD)) / 100, 0.42),\n bAF = Math.pow((frame.getFl() * Math.abs(bD)) / 100, 0.42),\n rA = (Math.sign(rD) * 400 * rAF) / (rAF + 27.13),\n gA = (Math.sign(gD) * 400 * gAF) / (gAF + 27.13),\n bA = (Math.sign(bD) * 400 * bAF) / (bAF + 27.13);\n\n // redness-greennes\n const a = (11 * rA + -12 * gA + bA) / 11;\n // yellowness-blueness\n const b = (rA + gA - 2 * bA) / 9;\n\n // auxiliary components\n const u = (20 * rA + 20 * gA + 21 * bA) / 20,\n p2 = (40 * rA + 20 * gA + bA) / 20;\n\n // hue\n const atan2 = Math.atan2(b, a),\n atanDegrees = (atan2 * 180) / Math.PI,\n hue = atanDegrees < 0 ? atanDegrees + 360 : atanDegrees >= 360 ? atanDegrees - 360 : atanDegrees,\n hueRadians = (hue * Math.PI) / 180;\n\n // achromatic response to color\n const ac = p2 * frame.getNbb();\n\n // CAM16 lightness and brightness\n const index = 100 * Math.pow(ac / frame.getAw(), frame.getC() * frame.getZ());\n const q = (4 / frame.getC()) * Math.sqrt(index / 100) * (frame.getAw() + 4) * frame.getFlRoot();\n\n // CAM16 chroma, colorfulness, and saturation.\n const huePrime = hue < 20.14 ? hue + 360 : hue,\n ehue = 0.25 * (Math.cos((huePrime * Math.PI) / 180 + 2) + 3.8),\n p1 = (50_000 / 13) * ehue * frame.getNc() * frame.getNcb(),\n t = (p1 * Math.hypot(a, b)) / (u + 0.305),\n alpha = Math.pow(t, 0.9) * Math.pow(1.64 - Math.pow(0.29, frame.getN()), 0.73);\n\n // CAM16 chroma, colorfulness, saturation\n const c = alpha * Math.sqrt(index / 100),\n m = c * frame.getFlRoot(),\n s = 50 * Math.sqrt((alpha * frame.getC()) / (frame.getAw() + 4));\n\n // CAM16-UCS components\n const jstar = ((1 + 100 * 0.007) * index) / (1 + 0.007 * index),\n mstar = (1 / 0.0228) * Math.log(1 + 0.0228 * m),\n astar = mstar * Math.cos(hueRadians),\n bstar = mstar * Math.sin(hueRadians);\n\n return new Cam(hue, c, index, q, m, s, jstar, astar, bstar);\n }\n\n /**\n * Create a color appearance model from a ARGB integer representing a color. It is assumed the color was viewed in the frame\n * defined in the sRGB standard.\n */\n static fromInt(argb: number) {\n return this.fromIntInFrame(argb, Frame.DEFAULT);\n }\n}\n\n/**\n * Collection of methods for transforming between color spaces.\n *\n * Methods are named $xFrom$Y. For example, lstarFromInt() returns L* from an ARGB integer.\n *\n * These methods, generally, convert colors between the L_a_b*, XYZ, and sRGB spaces.\n *\n * L_a_b* is a perceptually accurate color space. This is particularly important in the L* dimension: it measures luminance and\n * unlike lightness measures traditionally used in UI work via RGB or HSL, this luminance transitions smoothly, permitting\n * creation of pleasing shades of a color, and more pleasing transitions between colors.\n *\n * XYZ is commonly used as an intermediate color space for converting between one color space to another. For example, to convert\n * RGB to L_a_b*, first RGB is converted to XYZ, then XYZ is converted to L_a_b*.\n *\n * SRGB is a \"specification originated from work in 1990s through cooperation by Hewlett-Packard and Microsoft, and it was\n * designed to be a standard definition of RGB for the internet, which it indeed became...The standard is based on a sampling of\n * computer monitors at the time...The whole idea of sRGB is that if everyone assumed that RGB meant the same thing, then the\n * results would be consistent, and reasonably good. It worked.\" - Fairchild, Color Models and Systems: Handbook of Color\n * Psychology, 2015\n */\n// eslint-disable-next-line unicorn/no-static-only-class\nexport class CamUtilities {\n /**\n * This is a more precise sRGB to XYZ transformation matrix than traditionally used. It was derived using Schlomer's technique\n * of transforming the xyY primaries to XYZ, then applying a correction to ensure mapping from sRGB 1, 1, 1 to the reference\n * white point, D65.\n */\n static SRGB_TO_XYZ: [[number, number, number], [number, number, number], [number, number, number]] = [\n [0.41233895, 0.35762064, 0.18051042],\n [0.2126, 0.7152, 0.0722],\n [0.01932141, 0.11916382, 0.95034478],\n ];\n\n /** Transforms XYZ color space coordinates to 'cone'/'RGB' responses in CAM16. */\n static XYZ_TO_CAM16RGB: [[number, number, number], [number, number, number], [number, number, number]] = [\n [0.401288, 0.650173, -0.051461],\n [-0.250268, 1.204414, 0.045854],\n [-0.002079, 0.048952, 0.953127],\n ];\n\n static XYZ_TO_SRGB: [[number, number, number], [number, number, number], [number, number, number]] = [\n [3.2413774792388685, -1.5376652402851851, -0.49885366846268053],\n [-0.9691452513005321, 1.8758853451067872, 0.04156585616912061],\n [0.05562093689691305, -0.20395524564742123, 1.0571799111220335],\n ];\n\n /** Transforms 'cone'/'RGB' responses in CAM16 to XYZ color space coordinates. */\n static CAM16RGB_TO_XYZ: [[number, number, number], [number, number, number], [number, number, number]] = [\n [1.86206786, -1.01125463, 0.14918677],\n [0.38752654, 0.62144744, -0.00897398],\n [-0.0158415, -0.03412294, 1.04996444],\n ];\n\n /**\n * SRGB specification has D65 whitepoint - Stokes, Anderson, Chandrasekar, Motta - A Standard Default Color Space for the\n * Internet: sRGB, 1996\n */\n static WHITE_POINT_D65: [number, number, number] = [95.047, 100, 108.883];\n\n /** Returns L* from L_a_b*, perceptual luminance, from an ARGB integer (ColorInt). */\n static lstarFromInt(argb: number) {\n return this.lstarFromY(this.yFromInt(argb));\n }\n\n static lstarFromY(y: number) {\n y /= 100;\n const element = 216 / 24_389;\n if (y <= element) {\n return (24_389 / 27) * y;\n }\n const yIntermediate = Math.cbrt(y);\n return 116 * yIntermediate - 16;\n }\n\n static yFromInt(argb: number) {\n const r = this.linearized(Color.red(argb)),\n g = this.linearized(Color.green(argb)),\n b = this.linearized(Color.blue(argb)),\n matrix = this.SRGB_TO_XYZ,\n y = r * matrix[1][0] + g * matrix[1][1] + b * matrix[1][2];\n return y;\n }\n\n static xyzFromInt(argb: number): [number, number, number] {\n const r = this.linearized(Color.red(argb)),\n g = this.linearized(Color.green(argb)),\n b = this.linearized(Color.blue(argb));\n\n const matrix = this.SRGB_TO_XYZ,\n x = r * matrix[0][0] + g * matrix[0][1] + b * matrix[0][2],\n y = r * matrix[1][0] + g * matrix[1][1] + b * matrix[1][2],\n z = r * matrix[2][0] + g * matrix[2][1] + b * matrix[2][2];\n\n return [x, y, z];\n }\n\n static linearized(rgbComponent: number): number {\n const normalized = rgbComponent / 255;\n\n return normalized <= 0.04045 ? (normalized / 12.92) * 100 : Math.pow((normalized + 0.055) / 1.055, 2.4) * 100;\n }\n\n /**\n * Converts an L* value to a Y value.\n *\n * L* in L_a_b* and Y in XYZ measure the same quantity, luminance.\n *\n * L* measures perceptual luminance, a linear scale. Y in XYZ measures relative luminance, a logarithmic scale.\n *\n * @param lstar L* in L_a_b*\n * @returns Y in XYZ\n */\n static yFromLstar(lstar: number) {\n const ke = 8;\n return lstar > ke ? Math.pow((lstar + 16) / 116, 3) * 100 : (lstar / (24_389 / 27)) * 100;\n }\n\n /**\n * Clamps an integer between two integers.\n *\n * @returns Input when min <= input <= max, and either min or max otherwise.\n */\n static clampInt(min: number, max: number, input: number) {\n if (input < min) {\n return min;\n }\n if (input > max) {\n return max;\n }\n\n return input;\n }\n\n /**\n * Delinearizes an RGB component.\n *\n * @param rgbComponent 0 <= rgb_component <= 100, represents linear R/G/B channel\n * @returns 0 <= output <= 255, color channel converted to regular RGB space\n */\n static delinearized(rgbComponent: number) {\n const normalized = rgbComponent / 100;\n const delinearized = normalized <= 0.0031308 ? normalized * 12.92 : 1.055 * Math.pow(normalized, 1 / 2.4) - 0.055;\n return this.clampInt(0, 255, Math.round(delinearized * 255));\n }\n\n /** Converts a color from RGB components to ARGB format. */\n static argbFromRgb(red: number, green: number, blue: number) {\n return (255 << 24) | ((red & 255) << 16) | ((green & 255) << 8) | (blue & 255);\n }\n\n /** Converts a color from ARGB to XYZ. */\n static argbFromXyz(x: number, y: number, z: number) {\n const matrix = this.XYZ_TO_SRGB,\n linearR = matrix[0][0] * x + matrix[0][1] * y + matrix[0][2] * z,\n linearG = matrix[1][0] * x + matrix[1][1] * y + matrix[1][2] * z,\n linearB = matrix[2][0] * x + matrix[2][1] * y + matrix[2][2] * z,\n r = this.delinearized(linearR),\n g = this.delinearized(linearG),\n b = this.delinearized(linearB);\n\n return this.argbFromRgb(r, g, b);\n }\n\n /**\n * Convert a color appearance model representation to an ARGB color.\n *\n * Note: the returned color may have a lower chroma than requested. Whether a chroma is available depends on luminance. For\n * example, there's no such thing as a high chroma light red, due to the limitations of our eyes and/or physics. If the\n * requested chroma is unavailable, the highest possible chroma at the requested luminance is returned.\n *\n * @param hue Hue, in degrees, in CAM coordinates\n * @param chroma Chroma in CAM coordinates.\n * @param lstar Perceptual luminance, L* in L_a_b*\n */\n static CAMToColor(hue: number, chroma: number, lstar: number) {\n return Cam.getInt(hue, chroma, lstar);\n }\n\n /**\n * Converts an L* value to an ARGB representation.\n *\n * @param lstar L* in L_a_b*\n * @returns ARGB representation of grayscale color with lightness matching L*\n */\n static argbFromLstar(lstar: number) {\n const fy = (lstar + 16) / 116,\n fz = fy,\n fx = fy,\n kappa = 24_389 / 27,\n epsilon = 216 / 24_389,\n isLExceedsEpsilonKappa = lstar > 8,\n y = isLExceedsEpsilonKappa ? fy * fy * fy : lstar / kappa,\n isCubeExceedEpsilon = fy * fy * fy > epsilon,\n x = isCubeExceedEpsilon ? fx * fx * fx : lstar / kappa,\n z = isCubeExceedEpsilon ? fz * fz * fz : lstar / kappa,\n whitePoint = this.WHITE_POINT_D65;\n\n return this.argbFromXyz(x * whitePoint[0], y * whitePoint[1], z * whitePoint[2]);\n }\n\n /** Converts a color from linear RGB components to ARGB format. */\n static argbFromLinrgbComponents(r: number, g: number, b: number) {\n return this.argbFromRgb(this.delinearized(r), this.delinearized(g), this.delinearized(b));\n }\n\n /**\n * The signum function.\n *\n * @returns 1 if num > 0, -1 if num < 0, and 0 if num = 0\n */\n static signum(number_: number) {\n if (number_ < 0) {\n return -1;\n }\n return number_ === 0 ? 0 : 1;\n }\n\n static intFromLstar(lstar: number) {\n if (lstar < 1) {\n return 0xff_00_00_00;\n }\n if (lstar > 99) {\n return 0xff_ff_ff_ff;\n }\n\n // XYZ to LAB conversion routine, assume a and b are 0.\n const fy = (lstar + 16) / 116;\n\n // fz = fx = fy because a and b are 0\n const fz = fy;\n const fx = fy;\n\n const kappa = 24_389 / 27;\n const epsilon = 216 / 24_389;\n const isLExceedsEpsilonKappa = lstar > 8;\n const yT = isLExceedsEpsilonKappa ? fy * fy * fy : lstar / kappa;\n const isCubeExceedEpsilon = fy * fy * fy > epsilon;\n const xT = isCubeExceedEpsilon ? fx * fx * fx : (116 * fx - 16) / kappa;\n const zT = isCubeExceedEpsilon ? fz * fz * fz : (116 * fx - 16) / kappa;\n\n return ColorUtilities.XYZToColor(xT * this.WHITE_POINT_D65[0], yT * this.WHITE_POINT_D65[1], zT * this.WHITE_POINT_D65[2]);\n }\n}\n\n/**\n * The frame, or viewing conditions, where a color was seen. Used, along with a color, to create a color appearance model\n * representing the color.\n *\n * To convert a traditional color to a color appearance model, it requires knowing what conditions the color was observed in. Our\n * perception of color depends on, for example, the tone of the light illuminating the color, how bright that light was, etc.\n *\n * This class is modelled separately from the color appearance model itself because there are a number of calculations during the\n * color => CAM conversion process that depend only on the viewing conditions. Caching those calculations in a Frame instance\n * saves a significant amount of time.\n */\nexport class Frame {\n mN: number;\n mAw: number;\n mNbb: number;\n mNcb: number;\n mC: number;\n mNc: number;\n mRgbD: [number, number, number];\n mFl: number;\n mFlRoot: number;\n mZ: number;\n\n constructor(\n n: number,\n aw: number,\n nbb: number,\n ncb: number,\n c: number,\n nc: number,\n rgbD: [number, number, number],\n fl: number,\n fLRoot: number,\n z: number\n ) {\n this.mN = n;\n this.mAw = aw;\n this.mNbb = nbb;\n this.mNcb = ncb;\n this.mC = c;\n this.mNc = nc;\n this.mRgbD = rgbD;\n this.mFl = fl;\n this.mFlRoot = fLRoot;\n this.mZ = z;\n }\n\n getRgbD() {\n return this.mRgbD;\n }\n getFl() {\n return this.mFl;\n }\n getNbb() {\n return this.mNbb;\n }\n getAw() {\n return this.mAw;\n }\n getC() {\n return this.mC;\n }\n getFlRoot() {\n return this.mFlRoot;\n }\n getNc() {\n return this.mNc;\n }\n getNcb() {\n return this.mNcb;\n }\n getZ() {\n return this.mZ;\n }\n getN() {\n return this.mN;\n }\n\n static make(\n whitepoint: [number, number, number],\n adaptingLuminance: number,\n backgroundLstar: number,\n surround: number,\n shouldDiscountingIlluminant: boolean\n ) {\n // Transform white point XYZ to 'cone'/'rgb' responses\n const matrix = CamUtilities.XYZ_TO_CAM16RGB,\n xyz = whitepoint,\n rW = xyz[0] * matrix[0][0] + xyz[1] * matrix[0][1] + xyz[2] * matrix[0][2],\n gW = xyz[0] * matrix[1][0] + xyz[1] * matrix[1][1] + xyz[2] * matrix[1][2],\n bW = xyz[0] * matrix[2][0] + xyz[1] * matrix[2][1] + xyz[2] * matrix[2][2];\n\n // Scale input surround, domain (0, 2), to CAM16 surround, domain (0.8, 1)\n const f = 0.8 + surround / 10;\n // \"Exponential non-linearity\"\n const c = f >= 0.9 ? MathUtilities.lerp(0.59, 0.69, (f - 0.9) * 10) : MathUtilities.lerp(0.525, 0.59, (f - 0.8) * 10);\n // Calculate degree of adaptation to illuminant\n let d = shouldDiscountingIlluminant ? 1 : f * (1 - (1 / 3.6) * Math.exp((-adaptingLuminance - 42) / 92));\n // Per Li et al, if D is greater than 1 or less than 0, set it to 1 or 0.\n d = d > 1 ? 1 : Math.max(d, 0);\n // Chromatic induction factor\n const nc = f;\n\n // Cone responses to the whitepoint, adjusted for illuminant discounting.\n //\n // Why use 100 instead of the white point's relative luminance?\n //\n // Some papers and implementations, for both CAM02 and CAM16, use the Y\n // value of the reference white instead of 100. Fairchild's Color Appearance\n // Models (3rd edition) notes that this is in error: it was included in the\n // CIE 2004a report on CIECAM02, but, later parts of the conversion process\n // account for scaling of appearance relative to the white point relative\n // luminance. This part should simply use 100 as luminance.\n const rgbD = [d * (100 / rW) + 1 - d, d * (100 / gW) + 1 - d, d * (100 / bW) + 1 - d] as [number, number, number];\n // Luminance-level adaptation factor\n const k = 1 / (5 * adaptingLuminance + 1);\n const k4 = k * k * k * k;\n const k4F = 1 - k4;\n const fl = k4 * adaptingLuminance + 0.1 * k4F * k4F * Math.cbrt(5 * adaptingLuminance);\n\n // Intermediate factor, ratio of background relative luminance to white relative luminance\n const n = CamUtilities.yFromLstar(backgroundLstar) / whitepoint[1];\n\n // Base exponential nonlinearity\n // note Schlomer 2018 has a typo and uses 1.58, the correct factor is 1.48\n const z = 1.48 + Math.sqrt(n);\n\n // Luminance-level induction factors\n const nbb = 0.725 / Math.pow(n, 0.2);\n const ncb = nbb;\n\n // Discounted cone responses to the white point, adjusted for post-chromatic\n // adaptation perceptual nonlinearities.\n const rgbAFactors = [\n Math.pow((fl * rgbD[0] * rW) / 100, 0.42),\n Math.pow((fl * rgbD[1] * gW) / 100, 0.42),\n Math.pow((fl * rgbD[2] * bW) / 100, 0.42),\n ] as const;\n\n const rgbA = [\n (400 * rgbAFactors[0]) / (rgbAFactors[0] + 27.13),\n (400 * rgbAFactors[1]) / (rgbAFactors[1] + 27.13),\n (400 * rgbAFactors[2]) / (rgbAFactors[2] + 27.13),\n ] as const;\n\n const aw = (2 * rgbA[0] + rgbA[1] + 0.05 * rgbA[2]) * nbb;\n\n return new Frame(n, aw, nbb, ncb, c, nc, rgbD, fl, Math.pow(fl, 0.25), z);\n }\n\n static DEFAULT = Frame.make(CamUtilities.WHITE_POINT_D65, ((200 / Math.PI) * CamUtilities.yFromLstar(50)) / 100, 50, 2, false);\n}\n","/*\n * This code was originally written in Java and has been converted to JavaScript.\n *\n * Original Java code source: [https://android.googlesource.com/platform/frameworks/base/+/6844741fb8351f3aa82b96ce64a1bd83ea7989bd/packages/SystemUI/monet/src/com/android/systemui/monet?autodive=0%2F]\n *\n * Copyright (C) 2021 The Android Open Source Project.\n * The original code is licensed under the Apache License, Version 2.0.\n *\n * This JavaScript version is licensed under the MIT License.\n *\n * See the respective licenses for the specific terms, permissions, and limitations.\n */\nimport ColorUtilities from \"../utils/color-utilities.ts\";\n\nconst Shades = {\n /**\n * Combining the ability to convert between relative luminance and perceptual luminance with contrast leads to a design system\n * that can be based on a linear value to determine contrast, rather than a ratio.\n *\n * This codebase implements a design system that has that property, and as a result, we can guarantee that any shades 5 steps\n * from each other have a contrast ratio of at least 4.5. 4.5 is the requirement for smaller text contrast in WCAG 2.1 and\n * earlier.\n *\n * However, lstar 50 does _not_ have a contrast ratio >= 4.5 with lstar 100. lstar 49.6 is the smallest lstar that will lead to\n * a contrast ratio >= 4.5 with lstar 100, and it also contrasts >= 4.5 with lstar 100.\n */\n MIDDLE_LSTAR: 49.6,\n\n /**\n * Generate shades of a color. Ordered in lightness _descending_. The first shade will be at 95% lightness, the next at 90, 80,\n * etc. through 0.\n *\n * @param hue Hue in CAM16 color space\n * @param chroma Chroma in CAM16 color space\n * @returns Shades of a color, as argb integers. Ordered by lightness descending.\n */\n of(hue: number, chroma: number) {\n const shades: number[] = [];\n\n const shadesLStar = [99, 95, 90, 85, 80, 75, 70, 65, 60, 55, Shades.MIDDLE_LSTAR, 45, 40, 35, 30, 25, 20, 15, 10, 5, 1, 0];\n\n for (const lStar of shadesLStar) {\n if (lStar >= 90) chroma = Math.min(40, chroma);\n shades.push(ColorUtilities.CAMToColor(hue, chroma, lStar));\n }\n\n shades.unshift(16_777_215); // first color is always pure white\n\n return shades;\n },\n};\n\nexport default Shades;\n","/*\n * This code was originally written in Java and has been converted to JavaScript.\n *\n * Original Java code source: [https://android.googlesource.com/platform/frameworks/base/+/6844741fb8351f3aa82b96ce64a1bd83ea7989bd/packages/SystemUI/monet/src/com/android/systemui/monet?autodive=0%2F]\n *\n * Copyright (C) 2021 The Android Open Source Project.\n * The original code is licensed under the Apache License, Version 2.0.\n *\n * This JavaScript version is licensed under the MIT License.\n *\n * See the respective licenses for the specific terms, permissions, and limitations.\n */\nimport { Cam } from \"../cam/cam.ts\";\nimport Color from \"../utils/color.ts\";\nimport Shades from \"./shades.ts\";\n\nimport type { GenerationStyle, MaterialYouPalette } from \"../types.d.ts\";\n\ntype StyleType = Record<GenerationStyle, Record<\"a1\" | \"a2\" | \"a3\" | \"n1\" | \"n2\", [number, number]>>;\n\nconst Palette = {\n ACCENT1_CHROMA: 48,\n ACCENT2_CHROMA: 16,\n ACCENT3_CHROMA: 32,\n ACCENT3_HUE_SHIFT: 60,\n NEUTRAL1_CHROMA: 4,\n NEUTRAL2_CHROMA: 8,\n GOOGLE_BLUE: 0xff_1b_6e_f3,\n\n getStyle(hue: number, chroma: number): StyleType {\n return {\n SPRITZ: {\n a1: [hue, 12],\n a2: [hue, 8],\n a3: [hue, 16],\n n1: [hue, 2],\n n2: [hue, 2],\n },\n TONAL_SPOT: {\n a1: [hue, 36],\n a2: [hue, 16],\n a3: [Palette.HueAdd(hue, 60), 24],\n n1: [hue, 4],\n n2: [hue, 8],\n },\n VIBRANT: {\n a1: [hue, 130],\n a2: [Palette.HueVibrantSecondary(hue), 24],\n a3: [Palette.HueVibrantTertiary(hue), 32],\n n1: [hue, 10],\n n2: [hue, 12],\n },\n EXPRESSIVE: {\n a1: [Palette.HueAdd(hue, 240), 40],\n a2: [Palette.HueExpressiveSecondary(hue), 24],\n a3: [Palette.HueExpressiveTertiary(hue), 32],\n n1: [Palette.HueAdd(hue, 15), 8],\n n2: [Palette.HueAdd(hue, 15), 12],\n },\n RAINBOW: {\n a1: [hue, 48],\n a2: [hue, 16],\n a3: [Palette.HueAdd(hue, 60), 24],\n n1: [hue, 0],\n n2: [hue, 0],\n },\n FRUIT_SALAD: {\n a1: [Palette.HueSubtract(hue, 50), 48],\n a2: [Palette.HueSubtract(hue, 50), 36],\n a3: [hue, 36],\n n1: [hue, 10],\n n2: [hue, 16],\n },\n CONTENT: {\n a1: [hue, chroma],\n a2: [hue, Palette.ChromaMultiple(chroma, 0.33)],\n a3: [hue, Palette.ChromaMultiple(chroma, 0.66)],\n n1: [hue, Palette.ChromaMultiple(chroma, 0.0833)],\n n2: [hue, Palette.ChromaMultiple(chroma, 0.1666)],\n },\n MONOCHROMATIC: {\n a1: [hue, 0],\n a2: [hue, 0],\n a3: [hue, 0],\n n1: [hue, 0],\n n2: [hue, 0],\n },\n };\n },\n\n HueAdd(hue: number, amountDegrees: number): number {\n return Palette.wrapDegreesDouble(hue + amountDegrees);\n },\n\n HueSubtract(hue: number, amountDegrees: number): number {\n return Palette.wrapDegreesDouble(hue - amountDegrees);\n },\n\n ChromaMultiple(chroma: number, multiple: number): number {\n return chroma * multiple;\n },\n\n getHueRotation(sourceHue: number, hueAndRotations: Array<[number, number]>): number {\n const sanitizedSourceHue = sourceHue < 0 || sourceHue >= 360 ? 0 : sourceHue;\n\n for (let index = 0; index < hueAndRotations.length - 1; index++) {\n const thisHue = hueAndRotations[index][0];\n const nextHue = hueAndRotations[index + 1][0];\n\n if (thisHue <= sanitizedSourceHue && sanitizedSourceHue < nextHue) {\n return Palette.wrapDegreesDouble(sanitizedSourceHue + hueAndRotations[index][1]);\n }\n }\n\n // If this statement executes, something is wrong, there should have been a rotation\n // found using the arrays.\n return sourceHue;\n },\n\n HueVibrantSecondary(hue: number) {\n const hueToRotations: Array<[number, number]> = [\n [0, 18],\n [41, 15],\n [61, 10],\n [101, 12],\n [131, 15],\n [181, 18],\n [251, 15],\n [301, 12],\n [360, 12],\n ];\n\n return Palette.getHueRotation(hue, hueToRotations);\n },\n\n HueVibrantTertiary(hue: number) {\n const hueToRotations: Array<[number, number]> = [\n [0, 35],\n [41, 30],\n [61, 20],\n [101, 25],\n [131, 30],\n [181, 35],\n [251, 30],\n [301, 25],\n [360, 25],\n ];\n\n return Palette.getHueRotation(hue, hueToRotations);\n },\n\n HueExpressiveSecondary(hue: number) {\n const hueToRotations: Array<[number, number]> = [\n [0, 45],\n [21, 95],\n [51, 45],\n [121, 20],\n [151, 45],\n [191, 90],\n [271, 45],\n [321, 45],\n [360, 45],\n ];\n\n return Palette.getHueRotation(hue, hueToRotations);\n },\n\n HueExpressiveTertiary(hue: number) {\n const hueToRotations: Array<[number, number]> = [\n [0, 120],\n [21, 120],\n [51, 20],\n [121, 45],\n [151, 20],\n [191, 15],\n [271, 20],\n [321, 120],\n [360, 120],\n ];\n\n return Palette.getHueRotation(hue, hueToRotations);\n },\n\n wrapDegreesDouble(degrees: number): number {\n if (degrees < 0) {\n return (degrees % 360) + 360;\n }\n return degrees >= 360 ? degrees % 360 : degrees;\n },\n\n generate(seed: string, style: GenerationStyle = \"TONAL_SPOT\"): MaterialYouPalette {\n // Parse the HEX seed color string into an integer\n seed = seed.toUpperCase().slice(1, 7);\n const colorInt = Number.parseInt(\"0xff\" + seed, 16);\n\n const seedArgb = colorInt === Color.TRANSPARENT ? Palette.GOOGLE_BLUE : colorInt;\n\n const camSeed = Cam.fromInt(seedArgb),\n hue = camSeed.getHue(),\n chroma = Math.max(camSeed.getChroma(), Palette.ACCENT1_CHROMA);\n\n const { a1, a2, a3, n1, n2 } = Palette.getStyle(hue, chroma)[style];\n\n const accent1 = Shades.of(a1[0], a1[1]),\n accent2 = Shades.of(a2[0], a2[1]),\n accent3 = Shades.of(a3[0], a3[1]),\n neutral1 = Shades.of(n1[0], n1[1]),\n neutral2 = Shades.of(n2[0], n2[1]);\n\n const numberToHexColor = (colorNumber: number) => {\n return \"#\" + (colorNumber & 0xff_ff_ff).toString(16).padStart(6, \"0\");\n };\n\n const results = {\n system_accent1: accent1.map(element => numberToHexColor(element)),\n system_accent2: accent2.map(element => numberToHexColor(element)),\n system_accent3: accent3.map(element => numberToHexColor(element)),\n system_neutral1: neutral1.map(element => numberToHexColor(element)),\n system_neutral2: neutral2.map(element => numberToHexColor(element)),\n };\n\n return results;\n },\n};\n\nexport default Palette;\n","import Palette from \"./monet/palette.ts\";\n\nimport type { GenerationStyle, MaterialYouPalette } from \"./types.d.ts\";\n\nexport function generateMaterialYouPalette(seed: string, style?: GenerationStyle): MaterialYouPalette {\n return Palette.generate(seed, style);\n}\n","import { common, createEmphasize } from \"emphasize\";\nimport * as z from \"zod\";\n\nimport { formatCode } from \"../../../helpers/format-code.ts\";\nimport { join } from \"../../../utilities/path.ts\";\nimport { generateMaterialYouPalette } from \"./material-you/index.ts\";\n\nimport type { GenerationStyle } from \"./material-you/types.d.ts\";\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface MaterialYouCliPluginOptions {\n /**\n * Build command name.\n *\n * @default \"palette\"\n */\n command?: string;\n\n /**\n * Build command aliases.\n *\n * @default [\"material-you\"]\n */\n aliases?: string[];\n\n /** The default value for the `--color` option. */\n color?: string;\n\n /**\n * The default value for the `--style` option.\n *\n * @default \"TONAL_SPOT\"\n */\n style?: GenerationStyle;\n\n /**\n * The default value for the `--format` option.\n *\n * @default \"css\"\n */\n format?: \"css\" | \"json\";\n\n /**\n * The default value for the `--raw` option.\n *\n * @default false\n */\n raw?: boolean;\n}\n\n/**\n * Adds the \"palette\" command (aliased \"material-you\"): generates a Material You palette from a seed color and prints it.\n *\n * Notes:\n *\n * - \"--color\" takes a full \"#RRGGBB\" hex; anything else is rejected.\n * - \"--format css\" prints formatted custom properties (\"--clr-*\", with the seed and style recorded), \"--format json\" prints the raw\n * tone arrays. The pure black and white ends are left out of the CSS.\n * - The output is syntax highlighted unless \"--raw\" is passed, which is what you want when redirecting into a file.\n * - Nothing is written to disk; the palette goes to stdout.\n */\nexport function materialYouCliPlugin(options: MaterialYouCliPluginOptions = {}): Plugin {\n const name = options.command ?? \"palette\";\n const aliases = options.aliases ?? [\"material-you\"];\n\n return {\n name: \"material-you-cli-plugin\",\n\n cli(config) {\n const materialYouPaletteCommand = this.defineSubcommand({\n name,\n aliases,\n meta: {\n description: \"Generate and print Material You palette.\",\n example: 'staticbolt palette --color \"#ff0000\" --style SPRITZ --raw > palette.css',\n },\n\n options: {\n color: {\n aliases: [\"c\"],\n schema: options.color ? z.string().default(options.color) : z.string(),\n meta: {\n description: \"The seed color to generate the palette. only `HEX` color is supported.\",\n },\n },\n style: {\n aliases: [\"s\"],\n schema: z\n .enum([\"SPRITZ\", \"TONAL_SPOT\", \"VIBRANT\", \"EXPRESSIVE\", \"RAINBOW\", \"FRUIT_SALAD\", \"CONTENT\", \"MONOCHROMATIC\"])\n .default(options.style ?? \"TONAL_SPOT\"),\n meta: {\n description: \"The style of the palette.\",\n },\n },\n format: {\n aliases: [\"f\"],\n schema: z.enum([\"css\", \"json\"]).default(options.format ?? \"css\"),\n meta: {\n description: \"The output format.\",\n },\n },\n raw: {\n aliases: [\"r\"],\n schema: z.boolean().default(options.raw ?? false),\n coerce: this.coerce.boolean,\n meta: {\n description: \"Print without highlighting.\",\n },\n },\n },\n });\n\n materialYouPaletteCommand.onExecute(async result => {\n const { color, style, format, raw } = result.options;\n\n if (!isHexColor(color)) {\n console.error(`Invalid color: ${color}\\nOnly HEX colors \\`#RRGGBB\\` are supported.`);\n return;\n }\n\n const palette = generateMaterialYouPalette(color, style);\n\n if (format === \"json\") {\n const jsonCode = JSON.stringify(palette, null, 2);\n\n if (raw) {\n console.log(JSON.stringify(palette, null, 2));\n return;\n }\n\n console.log(createEmphasize(common).highlight(\"json\", jsonCode).value);\n\n return;\n }\n\n const shades = [0, 10, ...Array.from({ length: 19 }, (_, index) => (index + 1) * 50), 990, 1000];\n let css = `:root {--clr-seed: ${shortenHexColor(color)};--style: \"${style}\";\\n\\n/* pure */\\n--clr-white: #fff;--clr-black: #000;`;\n\n for (const [shadeName, shadesArray] of Object.entries(palette)) {\n css += `\\n\\n/* ${shadeName.replace(\"system_\", \"\")} */\\n`;\n css += shadesArray\n .map((shade, index) => {\n if (index === 0 || index === shadesArray.length - 1) return \"\";\n return `--${shadeName.replace(\"system\", \"clr\").replace(/_/g, \"-\")}-${shades[index]}: ${shortenHexColor(shade)};`;\n })\n .join(\"\");\n }\n\n css += \"}\";\n\n const virtualPath = join(config.root ?? process.cwd(), \"palette.css\");\n const [formatResult, formatError] = await formatCode(css, virtualPath, \"css\");\n if (formatError) {\n console.error(formatError);\n return;\n }\n\n css = formatResult;\n\n if (raw) {\n console.log(css);\n return;\n }\n\n console.log(createEmphasize(common).highlight(\"css\", css).value);\n });\n\n this.addCommand(materialYouPaletteCommand);\n },\n };\n}\n\nfunction isHexColor(color: string) {\n return /^#([A-Fa-f0-9]{6})$/.test(color);\n}\n\n/** Shortens a hex color code if it can be reduced to a shorthand version. */\nfunction shortenHexColor(hexColor: string): string {\n const r = hexColor[1];\n const g = hexColor[3];\n const b = hexColor[5];\n\n if (hexColor[2] === r && hexColor[4] === g && hexColor[6] === b) {\n return `#${r}${g}${b}`;\n }\n\n return hexColor;\n}\n","import { statSync } from \"node:fs\";\nimport chokidar from \"chokidar\";\nimport * as z from \"zod\";\n\nimport { loadConfigFile } from \"../../../helpers/load-config.ts\";\nimport { App } from \"../../../main.ts\";\nimport { Log } from \"../../../utilities/logger.ts\";\nimport { basename } from \"../../../utilities/path.ts\";\nimport { DEVELOPMENT_SERVER_OVERRIDES } from \"../../core-plugins/development-server/development-server-plugin.ts\";\n\nimport type { DevelopmentServerOverrides } from \"../../core-plugins/development-server/development-server-plugin.ts\";\nimport type { AppConfig, Plugin } from \"@staticbolt/core\";\n\nexport interface ServeCliPluginOptions {\n /**\n * Serve command name.\n *\n * @default \"serve\"\n */\n command?: string;\n\n /**\n * Serve command aliases.\n *\n * @default [\"dev\"]\n */\n aliases?: string[];\n}\n\n/**\n * Adds the \"serve\" command (aliased \"dev\"): runs the pipeline in development mode, which is what starts the dev server.\n *\n * Notes:\n *\n * - The command owns the run. It forces development mode onto the config and creates its own App.\n * - Serving itself belongs to developmentServerPlugin; this only starts the app in the right mode.\n * - The config file is watched. When it changes it is loaded again, the running app is closed and a new one starts from the new\n * config. A config that fails to load leaves the running app alone; a new app that fails to start is closed, so nothing is\n * served until the next save. Plugins have to be created inside the config file: only that file is evaluated again, so plugin\n * objects imported from elsewhere would be the same ones the closed app used, and those are refused.\n */\nexport function serveCliPlugin(options: ServeCliPluginOptions = {}): Plugin {\n const name = options.command ?? \"serve\";\n const aliases = options.aliases ?? [\"dev\"];\n\n return {\n name: \"serve-cli-plugin\",\n\n cli(config, configPath, projectDirectory) {\n const serveCommand = this.defineSubcommand({\n name,\n aliases,\n meta: { description: \"Dev server for staticbolt.\" },\n options: {\n host: {\n schema: z.boolean().optional(),\n coerce: this.coerce.boolean,\n meta: { description: \"Listen on every address, so the site is reachable from other devices on the network.\" },\n },\n },\n });\n\n serveCommand.onExecute(({ options }) =>\n new DevelopmentRun(config, configPath, projectDirectory, { host: options.host }).start()\n );\n\n this.addCommand(serveCommand);\n },\n };\n}\n\n/** The app running in development mode, replaced by a fresh one whenever the config file changes. */\nclass DevelopmentRun {\n #app: App;\n #config: AppConfig;\n\n readonly #configPath: string;\n readonly #configName: string;\n readonly #projectDirectory: string;\n readonly #overrides: DevelopmentServerOverrides;\n\n /** Restarts run one at a time; a change that lands during one waits its turn. */\n #restartQueue = Promise.resolve();\n\n /** The most recent change, so a queued restart can be skipped once a newer change is waiting behind it. */\n #latestChange = 0;\n\n /** When the config file was last written, as of the last time it was loaded. */\n #configModified: number | undefined;\n\n constructor(config: AppConfig, configPath: string, projectDirectory: string, overrides: DevelopmentServerOverrides) {\n config.production = false;\n\n this.#config = config;\n this.#configPath = configPath;\n this.#configName = basename(configPath);\n this.#projectDirectory = projectDirectory;\n this.#overrides = overrides;\n this.#app = this.#createApp(config);\n this.#configModified = this.#modifiedTime();\n }\n\n #createApp(config: AppConfig): App {\n const app = new App(config, this.#configPath);\n app.pluginData[DEVELOPMENT_SERVER_OVERRIDES] = this.#overrides;\n\n return app;\n }\n\n async start() {\n // A save is only picked up once the file has held still, so a half-written config is never loaded\n const watcher = chokidar.watch(this.#configPath, {\n ignoreInitial: true,\n awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 20 },\n });\n\n watcher.on(\"change\", () => this.#queueRestart()).on(\"add\", () => this.#queueRestart());\n\n // A save during the run queues behind it instead of being missed\n this.#restartQueue = this.#app.run().catch(async error => {\n Log.error(\"Failed to start the dev server:\");\n console.error(error instanceof Error && error.cause ? error.message : error);\n\n await watcher.close();\n await this.#app.close();\n process.exitCode = 1;\n });\n\n await this.#restartQueue;\n\n this.#restartIfModified();\n }\n\n #queueRestart() {\n const change = ++this.#latestChange;\n\n this.#restartQueue = this.#restartQueue.then(async () => {\n if (change === this.#latestChange) await this.#restart();\n });\n }\n\n /**\n * The app starting its own watcher makes the file system drop events for a moment (libuv rebuilds its stream), so a save that\n * happened while the app was starting is caught by looking at the file instead.\n */\n #restartIfModified() {\n if (this.#modifiedTime() !== this.#configModified) {\n this.#queueRestart();\n }\n }\n\n #modifiedTime(): number | undefined {\n return statSync(this.#configPath, { throwIfNoEntry: false })?.mtimeMs;\n }\n\n async #restart() {\n Log.info(`Config file \"${this.#configName}\" changed, restarting`);\n\n this.#configModified = this.#modifiedTime();\n\n const nextConfig = await this.#loadNextConfig();\n if (!nextConfig) return;\n\n let nextApp: App;\n try {\n nextApp = this.#createApp(nextConfig);\n } catch (error) {\n Log.error(\"Failed to create the app, keeping the current server:\");\n console.error(error);\n return;\n }\n\n try {\n await this.#app.close();\n this.#app = nextApp;\n this.#config = nextConfig;\n\n await nextApp.run();\n this.#restartIfModified();\n } catch (error) {\n Log.error(`Restart failed, nothing is served until \"${this.#configName}\" is fixed and saved again:`);\n console.error(error);\n await this.#app.close();\n }\n }\n\n /** The config to restart with, or nothing when the current server is to be kept. */\n async #loadNextConfig(): Promise<AppConfig | undefined> {\n const [nextConfig, configError] = await loadConfigFile(this.#configPath, this.#projectDirectory);\n if (configError) {\n Log.error(`Failed to load \"${this.#configName}\", keeping the current server:`);\n console.error(configError);\n return;\n }\n\n const reusedPlugins = this.#reusedPlugins(nextConfig);\n if (reusedPlugins.length > 0) {\n const names = reusedPlugins.map(plugin => `\"${plugin.name}\"`).join(\", \");\n Log.error(\n `Keeping the current server: ${names} are the same plugin objects as before. Create plugins inside \"${this.#configName}\" so a reload gets fresh ones.`\n );\n return;\n }\n\n nextConfig.production = false;\n\n return nextConfig;\n }\n\n /**\n * A plugin object belongs to one app. Plugins imported from another file come back as the same objects, since only the config\n * file itself is evaluated again.\n */\n #reusedPlugins(nextConfig: AppConfig): Plugin[] {\n const currentPlugins = new Set((this.#config.plugins ?? []).flat());\n\n return (nextConfig.plugins ?? []).flat().filter(plugin => currentPlugins.has(plugin));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,IAAa,qBAAb,MAAgC;CAC9B,AAASA,2BAAW,IAAI,IAAyB;CACjD,AAASC,4BAAY,IAAI,IAAY;CACrC,AAASC;CACT,AAASC;CAET,YAAY,KAAU,MAAc;EAClC,KAAKD,OAAO;EACZ,KAAKC,QAAQ;CACf;CAEA,MAAM,SAAS,cAAkD;EAC/D,MAAM,SAAS,KAAKH,SAAS,IAAI,aAAa,QAA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F,UAAU,KAAKR,WAAW,UAAU;EACtC,SAAS,OAAO;GACd,IAAI,MAAM,uDAAuD;GACjE,QAAQ,MAAM,KAAK;GACnB;EACF;EAEA,IAAI;GACF,MAAM,KAAKD,KAAK,MAAM;GACtB,KAAKA,OAAO;GACZ,KAAKD,UAAU;GAEf,MAAM,QAAQ,IAAI;GAClB,KAAKO,mBAAmB;EAC1B,SAAS,OAAO;GACd,IAAI,MAAM,4CAA4C,KAAKV,YAAY,4BAA4B;GACnG,QAAQ,MAAM,KAAK;GACnB,MAAM,KAAKI,KAAK,MAAM;EACxB;CACF;;CAGA,MAAMS,kBAAkD;EACtD,MAAM,CAAC,YAAY,eAAe,MAAM,eAAe,KAAKd,aAAa,KAAKE,iBAAiB;EAC/F,IAAI,aAAa;GACf,IAAI,MAAM,mBAAmB,KAAKD,YAAY,+BAA+B;GAC7E,QAAQ,MAAM,WAAW;GACzB;EACF;EAEA,MAAM,gBAAgB,KAAKc,eAAe,UAAU;EACpD,IAAI,cAAc,SAAS,GAAG;GAC5B,MAAM,QAAQ,cAAc,KAAI,WAAU,IAAI,OAAO,KAAK,EAAE,CAAC,CAAC,KAAK,IAAI;GACvE,IAAI,MACF,+BAA+B,MAAM,iEAAiE,KAAKd,YAAY,+BACzH;GACA;EACF;EAEA,WAAW,aAAa;EAExB,OAAO;CACT;;;;;CAMA,eAAe,YAAiC;EAC9C,MAAM,iBAAiB,IAAI,KAAK,KAAKG,QAAQ,WAAW,CAAC,EAAC,CAAE,KAAK,CAAC;EAElE,QAAQ,WAAW,WAAW,CAAC,EAAC,CAAE,KAAK,CAAC,CAAC,QAAO,WAAU,eAAe,IAAI,MAAM,CAAC;CACtF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["#depsMap","#visiting","#app","#root","#collectPackageMetadataDeps","#collect","#resolveSource","c","bundleFunction","traverse","normalizePackageName","generator","resolveStaticValue","resolveStaticValue","c","#queue","#workers","#waiting","#workerUrl","#concurrency","#onResult","#onFailure","#keepWorking","#wake","#draining","#failure","#work","#waitForWork","#send","#runs","#exports","#context","#options","#run","#readJson","#resolve","#compile","#require","embeddedLanguages","embeddedLanguages","#app","#loaded","#bundleAbsolutePath","#entries","#occurrences","#diagnostics","#reportedNodes","#visit","#assemble","#noteCharset","#warn","#planImport","#hasKeptImports","#resolve","#error","#load","#loadFromDisk","#charsetParams","#report","#nodesOf","placeholderRe","executeExpression","functionCache","htmlData","embeddedLanguages","htmlData","embeddedLanguages","parse","placeholderRe","z","parseYaml","sleep","#configPath","#configName","#projectDirectory","#overrides","#config","#app","#createApp","#configModified","#modifiedTime","#queueRestart","#restartQueue","#restartIfModified","#latestChange","#restart","#loadNextConfig","#reusedPlugins"],"sources":["../../src/helpers/find-dependencies.ts","../../src/plugins/analyze-output/analyze-output-plugin.ts","../../src/plugins/bundle-packages/bundle-esbuild.ts","../../src/plugins/bundle-packages/collect-specifiers.ts","../../src/plugins/bundle-packages/helpers.ts","../../src/plugins/bundle-packages/bundle-packages-plugin.ts","../../src/plugins/convert-images/convert-images-plugin.ts","../../src/plugins/copy-assets/copy-assets-plugin.ts","../../src/plugins/custom-ease/easing-functions/ease-utilities.ts","../../src/plugins/custom-ease/easing-functions/ease.ts","../../src/plugins/custom-ease/custom-ease-plugin.ts","../../src/plugins/i18n/get-locales.ts","../../src/plugins/i18n/i18n-html-plugin.ts","../../src/plugins/i18n/i18n-cli-plugin.ts","../../src/ast-utilities/babel-utils/resolve-static-value.ts","../../src/plugins/i18n/i18n-script-plugin.ts","../../src/plugins/i18n/i18n-plugin.ts","../../src/plugins/import-as-string/parse-import-as-string.ts","../../src/plugins/import-as-string/import-as-string-plugin.ts","../../src/plugins/load-sources/load-sources-plugin.ts","../../src/plugins/robots-text/robots-text-plugin.ts","../../src/plugins/service-worker/service-worker-plugin.ts","../../src/plugins/sitemap/sitemap-plugin.ts","../../src/plugins/svgo/svgo-optimize.ts","../../src/plugins/svgo/svgo-plugin.ts","../../src/ast-utilities/postcss-utils/process-css.ts","../../src/plugins/transform-css/transform-css-plugin.ts","../../src/ast-utilities/babel-utils/use-transform.ts","../../src/plugins/transform-js/transform-js-plugin.ts","../../src/plugins/web-manifest/web-manifest-plugin.ts","../../src/helpers/worker-pool.ts","../../src/plugins/write-files/write-files-plugin.ts","../../src/helpers/execute-js-in-vm.ts","../../src/plugins/html-build-time-script/lsp.ts","../../src/plugins/html-build-time-script/html-build-time-script.ts","../../src/plugins/html-bundle-script/esbuild-plugin.ts","../../src/plugins/html-bundle-script/esbuild-bundle.ts","../../src/plugins/html-bundle-script/html-bundle-script-plugin.ts","../../src/ast-utilities/postcss-utils/import-prelude.ts","../../src/parsers/css-parser.ts","../../src/plugins/core-plugins/style-metadata/style-loader.ts","../../src/helpers/style-bundler.ts","../../src/plugins/html-bundle-style/html-bundle-style-plugin.ts","../../src/plugins/html-env-only/html-environment-only-plugin.ts","../../src/plugins/html-fragment/html-fragment-plugin.ts","../../src/plugins/html-iife-script/iife.ts","../../src/plugins/html-iife-script/html-iife-script-plugin.ts","../../src/plugins/html-inline-script/html-inline-script-plugin.ts","../../src/plugins/html-inline-style/html-inline-style-plugin.ts","../../src/plugins/html-inline-svg/html-inline-svg-plugin.ts","../../src/plugins/html-inline-text/html-inline-text-plugin.ts","../../src/plugins/html-insert/html-insert-plugin.ts","../../src/plugins/html-layout/fill-placeholders.ts","../../src/plugins/html-layout/inline-layout.ts","../../src/plugins/html-layout/options.ts","../../src/plugins/html-layout/lsp.ts","../../src/plugins/html-layout/html-layout-plugin.ts","../../src/plugins/html-markdown/html-markdown-plugin.ts","../../src/plugins/html-merge-styles/html-merge-styles-plugin.ts","../../src/plugins/core-plugins/base-plugin/base-plugin.ts","../../src/plugins/html-pages/calculate-page-path.ts","../../src/plugins/html-pages/fill-placeholders.ts","../../src/plugins/html-pages/dynamic-routes.ts","../../src/plugins/html-pages/html-pages-plugin.ts","../../src/plugins/html-preload/get-file-type.ts","../../src/plugins/html-preload/html-preload-plugin.ts","../../src/ast-utilities/html-utils/parse-html-sources.ts","../../src/parsers/html-parser.ts","../../src/plugins/core-plugins/html-metadata/html-loader.ts","../../src/plugins/core-plugins/html-metadata/lsp.ts","../../src/plugins/core-plugins/html-metadata/html-metadata-plugin.ts","../../src/plugins/core-plugins/markdown-metadata/markdown-metadata-plugin.ts","../../src/ast-utilities/babel-utils/parse-script-srouces.ts","../../src/parsers/js-parser.ts","../../src/plugins/core-plugins/script-metadata/script-loader.ts","../../src/plugins/core-plugins/script-metadata/script-metadata-plugin.ts","../../src/ast-utilities/postcss-utils/parse-style-srouces.ts","../../src/plugins/core-plugins/style-metadata/style-metadata-plugin.ts","../../src/plugins/core-plugins/svg-metadata/svg-loader.ts","../../src/plugins/core-plugins/svg-metadata/svg-metadata-plugin.ts","../../src/plugins/core-plugins/web-manifest-metadata/web-manifest-loader.ts","../../src/plugins/core-plugins/web-manifest-metadata/web-manifest-metadata-plugin.ts","../../src/plugins/core-plugins/development-server/claim-port.ts","../../src/plugins/core-plugins/development-server/inject-reload-script.ts","../../src/plugins/core-plugins/development-server/order-by-dependency-depth.ts","../../src/plugins/core-plugins/development-server/development-server-plugin.ts","../../src/helpers/pirnt-debug.ts","../../src/main.ts","../../src/plugins/cli-plugins/build/build-cli-plugin.ts","../../src/plugins/cli-plugins/convert-fonts/convert-fonts-cli-plugin.ts","../../src/plugins/cli-plugins/generate-font-face/generate-font-face.ts","../../src/plugins/cli-plugins/generate-font-face/generate-font-face-cli-plugin.ts","../../src/plugins/cli-plugins/material-you/material-you/utils/color.ts","../../src/plugins/cli-plugins/material-you/material-you/utils/color-utilities.ts","../../src/plugins/cli-plugins/material-you/material-you/utils/math-utilities.ts","../../src/plugins/cli-plugins/material-you/material-you/cam/hct-solver.ts","../../src/plugins/cli-plugins/material-you/material-you/cam/cam.ts","../../src/plugins/cli-plugins/material-you/material-you/monet/shades.ts","../../src/plugins/cli-plugins/material-you/material-you/monet/palette.ts","../../src/plugins/cli-plugins/material-you/material-you/index.ts","../../src/plugins/cli-plugins/material-you/material-you-cli-plugin.ts","../../src/plugins/cli-plugins/serve/serve-cli-plugin.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\n\nimport { isValidRelativePath, splitHtmlLink } from \"../utilities/html-links.ts\";\nimport { isPackageMetadata } from \"../utilities/metadata-utilities.ts\";\nimport { dirname, extname, isAbsolute, join, normalize, relative } from \"../utilities/path.ts\";\n\nimport type { App, MetadataBase, PackageMetadata } from \"@staticbolt/core\";\n\nexport class DependenciesFinder {\n readonly #depsMap = new Map<string, Set<string>>();\n readonly #visiting = new Set<string>();\n readonly #app: App;\n readonly #root: string;\n\n constructor(app: App, root: string) {\n this.#app = app;\n this.#root = root;\n }\n\n async findDeps(metadataItem: MetadataBase): Promise<Set<string>> {\n const cached = this.#depsMap.get(metadataItem.filePath);\n if (cached) {\n return cached;\n }\n\n if (this.#app.emitExclude.has(metadataItem)) {\n return new Set();\n }\n\n if (this.#visiting.has(metadataItem.filePath)) {\n return new Set();\n }\n\n this.#visiting.add(metadataItem.filePath);\n\n const usedFiles = new Set<string>();\n\n // No need to parse packages (expensive)\n if (isPackageMetadata(metadataItem)) {\n await this.#collectPackageMetadataDeps(metadataItem, usedFiles);\n } else {\n const sources = await this.#app.requestSources(metadataItem);\n for (const { source } of sources) {\n await this.#collect(source, metadataItem.filePath, usedFiles);\n }\n }\n\n this.#visiting.delete(metadataItem.filePath);\n this.#depsMap.set(metadataItem.filePath, usedFiles);\n\n return usedFiles;\n }\n\n async #collectPackageMetadataDeps(metadataItem: PackageMetadata, usedFiles: Set<string>) {\n for (const dependency of metadataItem.directDependencies) {\n const absPath = join(this.#root, dependency);\n usedFiles.add(absPath);\n\n const dependencyMetadata = this.#app.findMetadata({ filePath: dependency });\n if (!dependencyMetadata) continue;\n\n const subDependencies = await this.findDeps(dependencyMetadata);\n for (const subDependency of subDependencies) {\n usedFiles.add(subDependency);\n }\n }\n }\n\n async #collect(source: string, fromFile: string, usedFiles: Set<string>): Promise<void> {\n const absPath = this.#resolveSource(source, fromFile);\n if (!absPath) {\n return;\n }\n\n if (extname(absPath) === \".html\") {\n return;\n }\n\n usedFiles.add(absPath);\n\n const relativePath = relative(this.#root, absPath);\n\n const dependencyMetadata = this.#app.findMetadata({ filePath: relativePath });\n if (!dependencyMetadata) return;\n\n const dependencies = await this.findDeps(dependencyMetadata);\n for (const dependency of dependencies) {\n usedFiles.add(dependency);\n }\n }\n\n /** Resolves a source path relative to its containing file and the output directory. */\n #resolveSource(source: string, filePath: string): string | void {\n if (!isValidRelativePath(source)) return;\n\n const link = normalize(splitHtmlLink(source)[0]);\n\n let resolved = isAbsolute(link)\n ? join(this.#root, link) // absolute → resolve from root\n : join(this.#root, dirname(filePath), link); // relative → resolve from containing file\n\n const extension = extname(resolved);\n\n // Folder or path to index.html\n if (!extension) {\n // Try index.html\n const candidate = join(resolved, \"index.html\");\n if (existsSync(candidate)) {\n resolved = candidate;\n }\n\n // Try directory, we don't need it\n if (existsSync(resolved)) {\n return;\n }\n }\n\n return resolved;\n }\n}\n","import { readdirSync, rmdirSync, unlinkSync } from \"node:fs\";\nimport c from \"chalk\";\nimport { globSync } from \"glob\";\n\nimport { DependenciesFinder as DependenciesFinder } from \"../../helpers/find-dependencies.ts\";\nimport { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { basename, dirname, extname, join, isPathMatch, relative } from \"../../utilities/path.ts\";\nimport { bytesToKB, humanReadableBytes } from \"../../utilities/utilities.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface AnalyzeOutputOptions {\n /**\n * Delete unused files from the output directory.\n *\n * @default false\n */\n deleteUnused?: boolean;\n\n /**\n * Log unused files.\n *\n * @default true\n */\n logUnusedFiles?: boolean;\n\n /**\n * Glob patterns to skip files when analyzing.\n *\n * @default [\"robots.txt\", \"sitemap.xml\", \"sw.js\", \"workbox-*.js\"]\n */\n exclude?: string[];\n\n /**\n * Specifies the size limit (in kilobytes) for each file type to trigger a warning. Set to `false` to disable warnings.\n *\n * @default { \".js\": 150 }\n */\n maxFileSize?: Record<string, number> | false;\n}\n\n/**\n * Analyzes the production build output and reports three things:\n *\n * - Missing: files the HTML pages reference but that are not in the output directory (errors).\n * - Unused: files in the output directory no page reaches (warnings, deleted when \"deleteUnused\" is set).\n * - Oversized: files above the per-extension limit in \"maxFileSize\" (warnings, largest first).\n *\n * Notes:\n *\n * - Runs after the build and only in production.\n * - Reachability is walked from HTML pages only, so anything reachable through another entry point counts as unused.\n * - HTML files are never listed as unused or deleted.\n * - Empty directories under the output are removed on every run, not just when deleting unused files.\n * - \"exclude\" is matched against paths relative to the output directory and applies to every report, so a file a later plugin\n * writes (a service worker, say) can be referenced without being reported missing.\n */\nexport function analyzeOutputPlugin(options: AnalyzeOutputOptions = {}): Plugin {\n const isRemoveUnused = options.deleteUnused ?? false;\n const exclude = options.exclude ?? [\"robots.txt\", \"sitemap.xml\", \"sw.js\", \"workbox-*.js\"];\n const maxFileSize = options.maxFileSize ?? { \".js\": 150 };\n const isLogUnusedFiles = options.logUnusedFiles ?? true;\n\n return {\n name: \"analyze-output\",\n\n async postBuild() {\n if (!this.production) return;\n\n const dependenciesFinder = new DependenciesFinder(this, this.outdir);\n\n // Absolute paths\n const availableFiles = new Set(globSync(this.outdir + \"/**/*\", { ignore: \"**/*.html\", nodir: true }));\n\n // Find used files staring from HTML as entry points\n const htmlEntryPoints = this.metadataList.filter(meta => isHtmlMetadata(meta));\n const usedFiles = new Set<string>();\n\n for (const metadataItem of htmlEntryPoints) {\n const dependencies = await dependenciesFinder.findDeps(metadataItem);\n\n for (const dependency of dependencies) {\n usedFiles.add(dependency);\n }\n }\n\n const isExcluded = (file: string) => isPathMatch(relative(this.outdir, file), { include: exclude, root: this.outdir });\n\n // ------ Report missing files ------\n const missingFiles = [...usedFiles.difference(availableFiles)].filter(file => !isExcluded(file));\n\n let missingFilesLog = c.bold(\"The following files are missing:\");\n for (const missing of missingFiles) {\n missingFilesLog += \"\\n\" + c.red(\"File not found: \") + c.yellow(relative(this.root, missing));\n }\n\n if (missingFiles.length > 0) {\n this.log.error(missingFilesLog);\n }\n\n // ------ Report/Remove unused files ------\n const unusedFiles = availableFiles.difference(usedFiles);\n const unusedFilesLog: string[] = [];\n\n for (const unused of unusedFiles) {\n if (extname(unused) === \".html\") continue; // Entry point\n\n if (isExcluded(unused)) continue;\n\n if (isRemoveUnused) unlinkSync(unused);\n\n unusedFilesLog.push(c.yellow(join(basename(this.outdir), relative(this.outdir, unused))));\n }\n\n const logTitle = isRemoveUnused\n ? c.bold(c.red(\"Removed\"), \"(\" + c.yellow(unusedFilesLog.length) + \")\", \"unused files from the output directory\")\n : c.bold(\"Found\", \"(\" + c.yellow(unusedFilesLog.length) + \")\", \"unused files\");\n\n if (unusedFilesLog.length > 0) {\n this.log.warn(logTitle + (isLogUnusedFiles ? \"\\n\" + unusedFilesLog.join(\"\\n\") : \"\"));\n }\n\n // ------ Remove empty directories ------\n const directories = globSync(this.outdir + \"/**/*/\");\n const sortedDirectories = directories.toSorted((a, b) => a.localeCompare(b));\n\n for (const directory of sortedDirectories) {\n let currentPath = directory;\n\n while (currentPath !== this.outdir) {\n const isEmpty = readdirSync(currentPath).length === 0;\n if (!isEmpty) break;\n\n rmdirSync(currentPath);\n currentPath = dirname(currentPath);\n }\n }\n\n // ------ check files size ------\n if (maxFileSize) {\n const extensions = Object.keys(maxFileSize).map(extension => extension.slice(1));\n const patternExtensionPart = extensions.length > 1 ? `{${extensions.join(\",\")}}` : extensions[0];\n const filesStat = globSync(`**/*.${patternExtensionPart}`, {\n ignore: exclude,\n nodir: true,\n cwd: this.outdir,\n withFileTypes: true,\n stat: true,\n });\n\n const largeFilesLogs: string[] = [];\n\n const sortedFiles = filesStat.toSorted((a, b) => (b.size ?? 0) - (a.size ?? 0));\n for (const file of sortedFiles) {\n const maxSize = maxFileSize[extname(file.name)];\n if (typeof maxSize !== \"number\") continue;\n\n if (file.size === 0) {\n continue;\n }\n\n const fileSizeKB = bytesToKB(file.size ?? 0);\n if (fileSizeKB <= maxSize) continue;\n\n largeFilesLogs.push(\n c.yellow(file.relative()) +\n ` (${c.red.bold(humanReadableBytes(file.size ?? 0))} ${c.blue(\">\")} ${c.green(humanReadableBytes(maxSize * 1024))})`\n );\n }\n\n if (largeFilesLogs.length > 0) {\n this.log.warn(c.bold(\"The following files may be large:\\n\") + largeFilesLogs.join(\"\\n\"));\n }\n }\n },\n };\n}\n","import * as esbuild from \"esbuild\";\n\nimport { valueOrError, type ValueOrError } from \"../../utilities/value-or-error.ts\";\n\nconst bundleFunction = valueOrError(esbuild.build);\n\ninterface BundleOptions {\n contents?: string;\n entryPoint?: string;\n resolveDir: string;\n packageName: string;\n outfile: string;\n production: boolean;\n minify: boolean;\n treeShaking: boolean;\n\n onPackageResolve: (\n path: string,\n importer: string\n ) => esbuild.OnResolveResult | undefined | Promise<esbuild.OnResolveResult | undefined>;\n\n onFileResolve?: (source: string, importer: string) => esbuild.OnResolveResult | undefined;\n}\n\nexport async function bundlePackage(options: BundleOptions): Promise<ValueOrError<string>> {\n const { resolveDir, packageName, outfile, onPackageResolve, production, minify, treeShaking } = options;\n\n const plugins: esbuild.Plugin[] = [\n {\n name: \"esbuild-plugin-packages-resolver\",\n setup(build) {\n // Filter only packages excluding relative imports\n build.onResolve({ filter: new RegExp(\"^[^./].*\") }, async arguments_ => {\n // skip the package that is currently being bundled\n if (arguments_.path === packageName || arguments_.importer === \"<stdin>\") {\n return;\n }\n\n return await onPackageResolve(arguments_.path, arguments_.importer);\n });\n },\n },\n ];\n\n if (options.onFileResolve) {\n plugins.push({\n name: \"esbuild-plugin-relative-imports-resolver\",\n setup(build) {\n // Filter only relative imports\n build.onResolve({ filter: /^\\./ }, arguments_ => {\n return options.onFileResolve?.(arguments_.path, arguments_.importer);\n });\n },\n });\n }\n\n const [bundleResult, bundleError] = await bundleFunction({\n stdin: options.contents ? { contents: options.contents, resolveDir } : undefined,\n entryPoints: options.entryPoint ? [options.entryPoint] : undefined,\n outfile,\n absWorkingDir: resolveDir,\n bundle: true,\n minify,\n treeShaking,\n write: false,\n legalComments: \"none\",\n packages: \"bundle\",\n platform: \"browser\",\n format: \"esm\",\n target: \"es2022\",\n define: { \"process.env.NODE_ENV\": production ? '\"production\"' : '\"development\"' },\n logLevel: \"silent\",\n plugins,\n });\n\n if (bundleError) {\n return [null, bundleError];\n }\n\n const outCode = bundleResult?.outputFiles?.[0]?.text;\n\n if (typeof outCode !== \"string\") {\n return [null, new Error(`Failed to bundle the package \"${packageName}\"`)];\n }\n\n return [outCode, null];\n}\n","import _traverse from \"@babel/traverse\";\nimport * as t from \"@babel/types\";\n\nimport type { BabelAst, NodePath } from \"@staticbolt/core\";\n\nconst traverse = typeof _traverse === \"function\" ? _traverse : _traverse.default;\n\nexport type Specifier =\n | { type: \"unknown\" }\n | { type: \"default\"; publicName?: never; name: string; newDefaultName?: string; setDefaultName: (name: string) => void }\n | { type: \"namespace\"; publicName?: never; name: string }\n | { type: \"named\"; kind: \"import\" | \"export\"; publicName: string; name: string }\n | { type: \"side-effect\"; name?: never; imported?: never };\n\nexport function collectSpecifiers(path: NodePath): Specifier[] {\n const specifiers: Specifier[] = [];\n\n // import default from \"source\";\n // import { value } from \"source\";\n // import * as value from \"source\";\n // import \"source\";\n if (path.isImportDeclaration()) {\n collectImportDeclarationSpecifiers(path, specifiers);\n return specifiers;\n }\n\n // export * from \"source\";\n if (path.isExportAllDeclaration()) {\n collectExportAllDeclarationSpecifiers(path, specifiers);\n return specifiers;\n }\n\n // export default from \"source\";\n // export { value } from \"source\";\n // export * as value from \"source\";\n if (path.isExportNamedDeclaration()) {\n collectExportNamedDeclarationSpecifiers(path, specifiers);\n return specifiers;\n }\n\n // const value = (await import(\"source\")).value;\n // const value = (await import(\"source\")).default;\n // const { value } = await import(\"source\");\n // const { default } = await import(\"source\");\n // const all = await import(\"source\");\n if (path.isCallExpression()) {\n collectDynamicImportSpecifiers(path, specifiers);\n return specifiers;\n }\n\n return specifiers;\n}\n\nexport function collectSpecifiersFromAst(ast: BabelAst): { source: string; specifiers: Specifier[] }[] {\n const result: { source: string; specifiers: Specifier[] }[] = [];\n\n traverse(ast, {\n // import default from \"source\";\n // import { value } from \"source\";\n // import * as value from \"source\";\n // import \"source\";\n ImportDeclaration(path) {\n if (!t.isStringLiteral(path.node.source)) return;\n\n const kind = path.node.importKind ?? \"value\";\n if (kind === \"type\") return;\n\n const source = path.node.source.value;\n\n if (source.startsWith(\"node:\")) {\n return;\n }\n\n const specifiers: Specifier[] = [];\n\n collectImportDeclarationSpecifiers(path, specifiers);\n\n result.push({\n get source() {\n return source;\n },\n set source(newValue) {\n if (path.node) {\n path.node.source = t.stringLiteral(newValue);\n }\n },\n specifiers,\n });\n },\n\n // export * from \"source\";\n ExportAllDeclaration(path) {\n if (!path.node.source.value) return;\n\n const kind = path.node.exportKind ?? \"value\";\n if (kind === \"type\") return;\n\n const specifiers: Specifier[] = [];\n\n collectExportAllDeclarationSpecifiers(path, specifiers);\n\n result.push({\n get source() {\n return path.node.source.value;\n },\n set source(newValue) {\n path.node.source = t.stringLiteral(newValue);\n },\n specifiers,\n });\n },\n\n // export default from \"source\";\n // export { value } from \"source\";\n // export * as value from \"source\";\n ExportNamedDeclaration(path) {\n if (!t.isStringLiteral(path.node.source)) return;\n\n const kind = path.node.exportKind ?? \"value\";\n if (kind === \"type\") return;\n\n const source = path.node.source.value;\n\n if (source.startsWith(\"node:\")) {\n return;\n }\n\n const specifiers: Specifier[] = [];\n\n collectExportNamedDeclarationSpecifiers(path, specifiers);\n\n result.push({\n get source() {\n return source;\n },\n set source(newValue) {\n path.node.source = t.stringLiteral(newValue);\n },\n specifiers,\n });\n },\n\n // const value = (await import(\"source\")).value;\n // const value = (await import(\"source\")).default;\n // const { value } = await import(\"source\");\n // const { default } = await import(\"source\");\n // const all = await import(\"source\");\n CallExpression(path) {\n if (!t.isImport(path.node.callee) || !t.isStringLiteral(path.node.arguments[0])) return;\n\n const setSource = (newValue: string) => {\n path.node.arguments[0] = t.stringLiteral(newValue);\n };\n\n const source = path.node.arguments[0].value;\n if (source.startsWith(\"node:\")) {\n return;\n }\n\n const specifiers: Specifier[] = [];\n\n collectDynamicImportSpecifiers(path, specifiers);\n result.push({\n get source() {\n return source;\n },\n set source(newValue) {\n setSource(newValue);\n },\n specifiers,\n });\n },\n });\n\n return result;\n}\n\nexport function collectImportDeclarationSpecifiers(path: NodePath<t.ImportDeclaration>, specifiers: Specifier[]) {\n const node = path.node;\n\n if (!t.isStringLiteral(node.source) || (node.importKind && node.importKind !== \"value\")) return;\n\n let hasFoundSpecifier = false;\n\n for (let index = 0; index < node.specifiers.length; index++) {\n const specifier = node.specifiers[index];\n\n // Default: import React from \"react\";\n if (t.isImportDefaultSpecifier(specifier)) {\n // setDefaultName(\"custom\") → `import { custom as React } from \"react\";`\n const setDefaultName = (newName: string) => {\n const index = node.specifiers.indexOf(specifier);\n if (index === -1) return;\n node.specifiers[index] = t.importSpecifier(t.identifier(specifier.local.name), t.identifier(newName));\n };\n\n specifiers.push({ type: \"default\", name: specifier.local.name, setDefaultName });\n\n hasFoundSpecifier = true;\n continue;\n }\n\n // Named: import { useState } from \"react\";\n if (t.isImportSpecifier(specifier)) {\n const imported = getNodeName(specifier.imported);\n if (!imported) continue;\n\n specifiers.push({ type: \"named\", kind: \"import\", name: imported, publicName: specifier.local.name });\n hasFoundSpecifier = true;\n continue;\n }\n\n // Namespace: import * as z from \"zod\";\n if (t.isImportNamespaceSpecifier(specifier)) {\n const usedNames = collectUsedNames(path, specifier.local.name);\n\n for (const name of usedNames) {\n if (name === \"default\") {\n const capturedLocalName = specifier.local.name;\n const capturedPath = path;\n\n // setDefaultName(\"custom\") → keeps `import * as z from \"zod\";` but rewrites `z.default` → `z.custom` at all usage sites\n const setDefaultName = (newName: string) => {\n const binding = capturedPath.scope.getBinding(capturedLocalName);\n if (!binding) return;\n\n for (const referencePath of binding.referencePaths) {\n const parentNode = referencePath.parentPath?.node;\n if (\n t.isMemberExpression(parentNode) &&\n t.isIdentifier(parentNode.property) &&\n parentNode.property.name === \"default\"\n ) {\n parentNode.property = t.identifier(newName);\n }\n }\n };\n specifiers.push({ type: \"default\", name: capturedLocalName, setDefaultName });\n\n hasFoundSpecifier = true;\n\n continue;\n }\n\n specifiers.push({ type: \"named\", kind: \"import\", name, publicName: name });\n hasFoundSpecifier = true;\n }\n }\n }\n\n // Side-effect: import \"react\";\n if (!hasFoundSpecifier) {\n specifiers.push({ type: \"side-effect\" });\n }\n}\n\nexport function collectExportAllDeclarationSpecifiers(path: NodePath<t.ExportAllDeclaration>, specifiers: Specifier[]) {\n if (!path.node.source.value || path.node.exportKind !== \"value\") return;\n\n specifiers.push({ type: \"namespace\", name: \"*\" });\n}\n\nexport function collectExportNamedDeclarationSpecifiers(path: NodePath<t.ExportNamedDeclaration>, specifiers: Specifier[]) {\n const node = path.node;\n\n if (!t.isStringLiteral(node.source) || node.exportKind !== \"value\") return;\n\n for (let index = 0; index < node.specifiers.length; index++) {\n const specifier = node.specifiers[index];\n\n // Default: export default React from \"react\";\n if (t.isExportDefaultSpecifier(specifier) && t.isIdentifier(specifier.exported)) {\n // setDefaultName(\"custom\") → `export { custom as React } from \"react\";`\n const setDefaultName = (newName: string) => {\n const index = node.specifiers.indexOf(specifier);\n if (index === -1) return;\n node.specifiers[index] = t.exportSpecifier(t.identifier(newName), t.identifier(specifier.exported.name));\n };\n\n specifiers.push({ type: \"default\", name: specifier.exported.name, setDefaultName });\n continue;\n }\n\n // Named: export { useState } from \"react\";\n if (t.isExportSpecifier(specifier)) {\n const exported = t.isIdentifier(specifier.exported) ? specifier.exported.name : specifier.exported.value;\n specifiers.push({ type: \"named\", kind: \"export\", name: exported, publicName: specifier.local.name });\n continue;\n }\n\n // Namespace: export * as React from \"react\";\n if (t.isExportNamespaceSpecifier(specifier)) {\n specifiers.push({\n type: \"namespace\",\n // @ts-expect-error The types are wrong\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n name: t.isIdentifier(specifier.exported) ? specifier.exported.name : specifier.exported.value,\n });\n }\n }\n}\n\nfunction collectDynamicImportSpecifiers(path: NodePath<t.CallExpression>, specifiers: Specifier[]) {\n if (!t.isImport(path.node.callee)) return;\n\n // case: dynamic import name\n if (!t.isStringLiteral(path.node.arguments[0])) {\n specifiers.push({ type: \"unknown\" });\n return;\n }\n\n const parentPath = path.parentPath;\n const hasAwait = parentPath && t.isAwaitExpression(parentPath.node);\n\n // case: not awaited cannot correctly find the specifier\n if (!hasAwait) {\n specifiers.push({ type: \"unknown\" });\n return;\n }\n\n const parentNode = parentPath.parentPath?.node;\n\n // case: const varName = (await import('path')).name;\n // equivalent to: import { name } from 'path';\n if (t.isMemberExpression(parentNode)) {\n const property = parentNode.property;\n\n const importedName = getNodeName(property);\n if (!importedName) return;\n\n // case: const varName = (await import('path')).default;\n // equivalent to: import default from 'path';\n if (importedName === \"default\") {\n const capturedMemberExpression = parentNode;\n\n // setDefaultName(\"custom\") → `(await import('path')).custom`\n const setDefaultName = (newName: string) => {\n capturedMemberExpression.property = t.identifier(newName);\n };\n\n specifiers.push({ type: \"default\", name: importedName, setDefaultName });\n return;\n }\n\n specifiers.push({ type: \"named\", kind: \"import\", name: importedName, publicName: importedName });\n\n return;\n }\n\n // case: const { named } = await import('path');\n // equivalent to: import { named } from 'path';\n if (t.isVariableDeclarator(parentNode) && t.isObjectPattern(parentNode.id)) {\n for (const property of parentNode.id.properties) {\n if (!t.isObjectProperty(property)) continue;\n\n const importedName = getNodeName(property.key);\n if (!importedName) continue;\n\n const localName = getNodeName(property.value);\n\n // case: const { default } = await import('path');\n // equivalent to: import default from 'path';\n if (importedName === \"default\") {\n // setDefaultName(\"custom\") → `const { custom: val } = await import('path')`;\n const setDefaultName = (newName: string) => {\n property.key = t.identifier(newName);\n };\n\n specifiers.push({ type: \"default\", name: localName ?? importedName, setDefaultName });\n continue;\n }\n\n specifiers.push({ type: \"named\", kind: \"import\", name: importedName, publicName: localName ?? importedName });\n }\n\n return;\n }\n\n // case: const lib = await import('path');\n // equivalent to: import * as lib from 'path';\n if (t.isVariableDeclarator(parentNode) && t.isIdentifier(parentNode.id)) {\n const usedNames = collectUsedNames(path, parentNode.id.name);\n\n for (const name of usedNames) {\n if (name === \"default\") {\n const capturedId = parentNode.id;\n const capturedPath = path;\n\n // setDefaultName(\"custom\") → keeps import as-is, rewrites `lib.default` → `lib.custom` at all usage sites\n\n const setDefaultName = (newName: string) => {\n const binding = capturedPath.scope.getBinding(capturedId.name);\n if (!binding) return;\n\n for (const referencePath of binding.referencePaths) {\n const pNode = referencePath.parentPath?.node;\n if (t.isMemberExpression(pNode) && t.isIdentifier(pNode.property) && pNode.property.name === \"default\") {\n pNode.property = t.identifier(newName);\n }\n }\n };\n\n specifiers.push({ type: \"default\", name: parentNode.id.name, setDefaultName });\n continue;\n }\n\n specifiers.push({ type: \"named\", kind: \"import\", name, publicName: name });\n }\n\n return;\n }\n\n // case: await import('path');\n // equivalent to: import 'path';\n if (!parentNode || t.isExpressionStatement(parentNode)) {\n specifiers.push({ type: \"side-effect\" });\n }\n}\n\n/**\n * Collects used names from a name space import. E.g., `import * as z from \"zod\"`\\\n * Covers most cases when importing a package using a name space.\n *\n * Covered cases:\n *\n * - Direct member expression: `z.string()`\n * - Destructuring: `const { string, object } = z;`\n * - Following aliases: `const zod = z;`\n *\n * Ignored cases:\n *\n * - Object destructuring with spread syntax: `const { string, ...rest } = z;`\n */\nfunction collectUsedNames(path: NodePath, importName: string): Set<string> {\n const usedNames = new Set<string>();\n\n const binding = path.scope.getBinding(importName);\n if (!binding) {\n return usedNames;\n }\n\n for (const referencePath of binding.referencePaths) {\n const parentPath = referencePath.parentPath;\n if (!parentPath) {\n continue;\n }\n\n const parentNode = parentPath.node;\n\n // Direct member expression: z.string()\n if (t.isMemberExpression(parentNode) && t.isIdentifier(parentNode.property)) {\n usedNames.add(parentNode.property.name); // just add the property\n continue;\n }\n\n // Destructuring: const { string, object } = z;\n if (t.isVariableDeclarator(parentNode) && t.isIdentifier(parentNode.init)) {\n const id = parentNode.id;\n\n // Destructuring: const { string, object } = z;\n if (t.isObjectPattern(id)) {\n for (const property of id.properties) {\n if (t.isRestElement(property) || !t.isIdentifier(property.key)) continue;\n usedNames.add(property.key.name);\n }\n continue;\n }\n\n // Alias: const alias = z;\n if (t.isIdentifier(id)) {\n const aliasUsed = collectUsedNames(parentPath.get(\"id\"), id.name);\n for (const n of aliasUsed) usedNames.add(n);\n }\n }\n }\n\n return usedNames;\n}\n\nfunction getNodeName(node: t.Node): string | null {\n if (t.isIdentifier(node)) {\n return node.name;\n }\n\n if (t.isStringLiteral(node)) {\n return node.value;\n }\n\n if (t.isPrivateName(node)) {\n return node.id.name;\n }\n\n return null;\n}\n","import { createRequire } from \"node:module\";\nimport nodePath from \"node:path\";\n\nimport { join, isPathMatch, replaceExtension } from \"../../utilities/path.ts\";\n\nimport type { Specifier } from \"./collect-specifiers.ts\";\n\n/**\n * Some package names may include `.js` as part of their name (e.g., `highlight.js`).\\\n * If we have a subpackage within such a package, we face a conflict:\\\n * We cannot create a folder named `highlight.js` because a file with the same name (`highlight.js`) already exists.\\\n * To resolve this, we replace `.js` with `_js` in the subpackage path only, avoiding conflicts.\\\n * Example: `highlight.js/languages/javascript.js` -> `highlight_js/languages/javascript.js`\n */\nfunction normalizePackageName(originalSource: string) {\n const parts = originalSource.split(\"/\");\n\n // we need more than one part. e.g., `highlight.js/languages/javascript.js`\n if (parts.length <= 1) return originalSource;\n\n const outParts = [];\n\n for (let index = 0; index < parts.length; index++) {\n const part = parts[index];\n const isLast = index === parts.length - 1;\n\n // skip last part: it's the file name\n if (isLast) {\n outParts.push(part);\n continue;\n }\n\n // replace .js with _js\n outParts.push(part.replace(\".js\", \"_js\"));\n }\n\n return outParts.join(\"/\");\n}\n\nexport function calcPackageOutPath(packageName: string, packagesDirectory: string) {\n const normalizedPackageName = normalizePackageName(packageName);\n const withJsExtension = replaceExtension(normalizedPackageName, \".js\");\n const underPackagesDirectory = join(packagesDirectory, withJsExtension);\n\n return underPackagesDirectory;\n}\n\n/**\n * Output path for an asset shipped by a package, keeping its own extension.\n *\n * Example: `node_modules/highlight.js/styles/default.css` -> `packages/highlight_js/styles/default.css`\n */\nexport function calcPackageAssetOutPath(nodeModulesPath: string, packagesDirectory: string) {\n const marker = \"node_modules/\";\n const markerIndex = nodeModulesPath.lastIndexOf(marker);\n const packagePath = markerIndex === -1 ? nodeModulesPath : nodeModulesPath.slice(markerIndex + marker.length);\n\n return join(packagesDirectory, normalizePackageName(packagePath));\n}\n\nexport function generateStdinString(specifiers: Specifier[], packageName: string) {\n let isDefaultImport = false;\n let newDefaultName: string | undefined;\n let hasSideEffect = false;\n let isNamespace = false;\n const named = new Set<string>();\n\n for (const specifier of specifiers) {\n if (specifier.type === \"default\") {\n isDefaultImport = true;\n newDefaultName = specifier.newDefaultName;\n }\n\n if (specifier.type === \"named\" && specifier.kind === \"import\") {\n named.add(specifier.name);\n }\n\n if (specifier.type === \"named\" && specifier.kind === \"export\") {\n named.delete(specifier.name);\n named.add(specifier.publicName);\n }\n\n if (specifier.type === \"namespace\") {\n isNamespace = true;\n }\n //\n else if (specifier.type === \"side-effect\") {\n hasSideEffect = true;\n }\n }\n\n let contents = \"\";\n\n if (hasSideEffect) {\n contents += `import '${packageName}';`;\n }\n\n if (isNamespace) {\n contents += `\\nexport * from '${packageName}';`;\n }\n\n if (isDefaultImport) {\n contents += `\\nexport { default${newDefaultName ? ` as ${newDefaultName}` : \"\"} } from '${packageName}';`;\n }\n\n // Also include named exports in dev mode (because of commonjs cannot use export *)\n if (named.size > 0 && !isNamespace) {\n contents += `\\nexport { ${Array.from(named).join(\", \")} } from '${packageName}';`;\n }\n\n return contents;\n}\n\nexport function getChunkName(packageName: string, chunks: Record<string, string[]>) {\n for (const [chunkName, packages] of Object.entries(chunks)) {\n if (matchesPackage(packageName, packages)) {\n return chunkName;\n }\n }\n}\n\nexport function matchesPackage(packageName: string, packages: string[]) {\n for (const pattern of packages) {\n // exact match\n if (pattern === packageName) {\n return true;\n }\n\n // wildcard match like \"react-dom/*\"\n if (pattern.endsWith(\"/*\")) {\n const base = pattern.slice(0, -2); // remove \"/*\"\n const isMatch = packageName === base || packageName.startsWith(base + \"/\");\n\n if (isMatch) return true;\n }\n\n // double wild cards like \"react-dom/**\"\n if (pattern.endsWith(\"/**\")) {\n const base = pattern.slice(0, -2); // remove \"**\"\n const isMatch = packageName === base || packageName.startsWith(base + \"/\");\n\n if (isMatch) return true;\n }\n }\n\n return false;\n}\n\n/** Join the package name with its entry point. Example: `join(\"react-dom\", \"./client\") // => \"react-dom/client` */\nfunction packageJoin(name: string, subPackage: string) {\n return nodePath.join(name, subPackage).replace(/\\\\/g, \"/\").replace(/\\/$/, \"\");\n}\n\nfunction getNodeModuleDirectory(packageName: string, root: string): string | null {\n try {\n const require = createRequire(root.endsWith(nodePath.sep) ? root : root + nodePath.sep);\n const entryPoint = require.resolve(packageName);\n\n const parts = entryPoint.split(nodePath.sep);\n const index = parts.lastIndexOf(\"node_modules\");\n\n if (index === -1) {\n console.error(`node_modules not found in resolved path for \"${packageName}\": ${entryPoint}`);\n return null;\n }\n\n return parts.slice(0, index + 1).join(nodePath.sep);\n } catch (error) {\n console.error(`Failed to resolve package directory for \"${packageName}\":`, error);\n return null;\n }\n}\n\nexport function getCustomPackagePath(\n root: string,\n importPath: string,\n isProduction: boolean,\n resolvePackage: Record<string, Record<string, string | { production?: string; development?: string }>>\n): string | undefined {\n const environment = isProduction ? \"production\" : \"development\";\n\n for (const [packageName, exports] of Object.entries(resolvePackage)) {\n for (const [entry, stringOrObject] of Object.entries(exports)) {\n if (packageJoin(packageName, entry) !== importPath) continue;\n\n const relativePath = typeof stringOrObject === \"string\" ? stringOrObject : stringOrObject[environment];\n if (!relativePath) continue;\n\n const nodeModulesDirectory = getNodeModuleDirectory(packageName, root);\n if (!nodeModulesDirectory) {\n console.error(`Skipping \"${packageName}\" — could not determine node_modules directory`);\n continue;\n }\n\n return join(nodeModulesDirectory, packageName, relativePath);\n }\n }\n}\n\nexport function isNodeModulesPath(path: string, root: string) {\n return isPathMatch(path, { include: [\"**/node_modules/**\"], ignore: [], root });\n}\n\n/** Directory of the package a `node_modules` path belongs to, `undefined` for paths outside `node_modules`. */\nexport function packageDirectory(path: string): string | undefined {\n return /^(.*?node_modules\\/(?:@[^/]+\\/)?[^/]+)(?:\\/|$)/.exec(path)?.[1];\n}\n\n/**\n * Returns a stable key for a specifier, ignoring publicName and function refs. Side-effects are keyed by type alone (only one per\n * source).\n */\nfunction specifierKey(s: Specifier): string {\n switch (s.type) {\n case \"default\": {\n return `default::${s.name}`;\n }\n case \"namespace\": {\n return `namespace::${s.name}`;\n }\n case \"named\": {\n return `named::${s.name}`;\n }\n case \"unknown\":\n case \"side-effect\": {\n return `side-effect`;\n }\n }\n}\n\n/**\n * Diffs two specifier arrays and returns only the entries from `collected` that are not already present in `existing`.\n *\n * @param existing - The full current set of specifiers.\n * @param collected - Newly gathered specifiers to screen for novelty.\n * @returns Specifiers in `collected` that are absent from `existing`.\n */\nexport function diffSpecifiers(existing: Specifier[], collected: Specifier[]): Specifier[] {\n const existingKeys = new Set(existing.map(element => specifierKey(element)));\n return collected.filter(s => !existingKeys.has(specifierKey(s)));\n}\n","import { isScriptType } from \"../../helpers/is-script-type.ts\";\nimport { METADATA_TYPES, type PackageMetadata } from \"../../types/metadata.ts\";\nimport { isValidRelativePath, splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { filterScriptMetadata, isHtmlMetadata, isPackageMetadata, isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, extname, isAbsolute, join, relative } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { bundlePackage } from \"./bundle-esbuild.ts\";\nimport { collectSpecifiersFromAst, type Specifier } from \"./collect-specifiers.ts\";\nimport {\n calcPackageAssetOutPath,\n calcPackageOutPath,\n diffSpecifiers,\n generateStdinString,\n getChunkName,\n getCustomPackagePath,\n isNodeModulesPath,\n matchesPackage,\n packageDirectory,\n} from \"./helpers.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface BundlePackagesOptions {\n /** Output directory for bundled `node_modules` packages, relative to the build output directory. */\n packagesDir?: string;\n\n /**\n * Bundles specific packages into a single chunk for optimized loading.\n *\n * Useful for grouping related libraries (e.g., all React dependencies) or bundling CommonJS modules for browser compatibility.\n *\n * @example\n * bundlePackagesPlugin({\n * \"react-bundle\": [\"react\", \"react-dom\", \"react-dom/client\", \"react/jsx-runtime\", \"scheduler\"],\n * });\n *\n * @key Chunk name\n * @value Array of package names to include in the bundle\n */\n chunks?: Record<string, string[]>;\n\n /**\n * Custom package resolver entries to override default resolution logic.\n *\n * @example\n * bundlePackagesPlugin({\n * resolvePackage: {\n * \"react-dom\": {\n * \"./client\": {\n * production: \"./cjs/react-dom.production.js\",\n * development: \"./cjs/react-dom.development.js\",\n * },\n * },\n * },\n * });\n *\n * @default {}\n */\n resolvePackage?: Record<string, Record<string, string | { production?: string; development?: string }>>;\n}\n\nfunction normalizePackageName(packageName: string) {\n return \"default_\" + packageName.replace(/@|-|\\/|\\./g, \"_\");\n}\n\n/**\n * Bundles every \"node_modules\" package imported anywhere in the project into its own file under \"packagesDir\" and rewrites the\n * imports to point at it. Specifiers are collected across the whole codebase first, so esbuild can tree-shake each package down\n * to what is actually used.\n *\n * Notes:\n *\n * - Runs in both modes; minification and tree-shaking are production-only.\n * - Bare imports in scripts and \"<script src>\" tags resolving into \"node_modules\" are both redirected; a script tag is counted as a\n * side-effect import.\n * - A \"<link rel=stylesheet>\" shipped by a package is moved next to the package output, keeping its path inside the package. Other\n * file types stay where they resolve, under \"node_modules\".\n * - Dots in the output path become underscores (\"highlight.js\" becomes \"highlight_js\"), so a package cannot collide with the file\n * bundled from it.\n * - \"chunks\" merges packages into one file and renames their default imports to \"default_<package>\" so they share a module scope,\n * which is what CommonJS packages need to work in the browser.\n * - A package first discovered while bundling another one is bundled right away, then re-bundled once its specifiers are known.\n */\nexport function bundlePackagesPlugin(options: BundlePackagesOptions = {}): Plugin {\n const packagesOutputDirection = options.packagesDir ?? \"./packages\";\n const resolvePackage = options.resolvePackage ?? {};\n const chunks = options.chunks ?? {};\n\n /** Maps package names to a list of collected import specifiers (named, default, side-effect, etc.) from various source files. */\n const specifiersByPackage = new Map<string, Specifier[]>();\n\n /** Maps the absolute path of a package entry point to its original source name */\n const pathPackageMap = new Map<string, string>();\n\n /** Maps a chunk name to the entry contents it was last bundled from, to tell a stale chunk from an up to date one. */\n const chunkContents = new Map<string, string>();\n\n const JS_EXTENSIONS = new Set([\".js\", \".mjs\", \".cjs\", \".jsx\", \".ts\", \".mts\", \".cts\", \".tsx\"]);\n\n const printFormattedError = PrintFormattedError.create({ function: bundlePackagesPlugin });\n\n return {\n name: \"bundle-packages\",\n\n resolveSource(source, filePath) {\n if (!isValidRelativePath(source)) return;\n\n const [link] = splitHtmlLink(source);\n\n // Sources already resolved into another package are kept as is\n const target = join(dirname(filePath), link);\n if (isNodeModulesPath(target, this.root) && packageDirectory(target) !== packageDirectory(filePath)) {\n return { source, dependencyID: undefined };\n }\n\n const resolveResult = this.resolver.resolve(source, filePath);\n if (!resolveResult) {\n return;\n }\n\n // E.g. `fs`, `path`, etc\n if (!isAbsolute(resolveResult.path)) {\n return;\n }\n\n // Only looking for packages\n if (!resolveResult.isPackage) {\n return;\n }\n\n // Only looking for JS files\n if (!JS_EXTENSIONS.has(extname(resolveResult.path))) {\n return;\n }\n\n const isInsideRoot = resolveResult.path.startsWith(this.root);\n if (!isInsideRoot) {\n this.log.warn(`Resolved package \"${resolveResult.path}\" outside of the root directory.`);\n }\n\n pathPackageMap.set(resolveResult.path, source);\n\n const absFileDirectory = join(this.root, dirname(filePath));\n const resolvedSource = relative(absFileDirectory, resolveResult.path) + resolveResult.suffix;\n\n return { source: resolvedSource, dependencyID: undefined };\n },\n\n async postTransform() {\n const root = this.root;\n\n // - Collect specifiers\n // - Rewrite import paths to point to the package output directory\n // - For chunks, rewrite default imports\n for (const inputMetadata of this.metadataList) {\n for (const { metadata } of filterScriptMetadata(inputMetadata)) {\n const sources = collectSpecifiersFromAst(metadata.ast);\n\n for (const sourceReference of sources) {\n const source = sourceReference.source;\n const sourceRootRelative = join(dirname(metadata.filePath), source);\n\n // Only sources pointing to node_modules paths.\n if (!isNodeModulesPath(sourceRootRelative, root)) continue;\n\n const packageName = pathPackageMap.get(join(root, sourceRootRelative));\n if (!packageName) {\n printFormattedError(\n `Could not resolve package name for path \"${sourceRootRelative}\"\\n` +\n `imported from \"${metadata.filePath}\").\\n` +\n `Skipping specifier collection for this import.`\n );\n continue;\n }\n\n // Set the source to where the package will be output.\n const chunkName = getChunkName(packageName, chunks);\n const importName = chunkName ?? packageName;\n\n const packageOutputPath = calcPackageOutPath(importName, packagesOutputDirection);\n const newSource = relative(dirname(metadata.filePath), packageOutputPath);\n sourceReference.source = newSource;\n\n // Merge newly found specifiers with any already collected for this package.\n const existingSpecifiers = specifiersByPackage.get(packageName) ?? [];\n specifiersByPackage.set(packageName, existingSpecifiers);\n\n const specifiers = sourceReference.specifiers;\n\n // Rewrite default specifiers for chunks\n if (chunkName) {\n const normalizedPackageName = normalizePackageName(packageName);\n for (const specifier of specifiers) {\n if (specifier.type === \"default\") {\n specifier.setDefaultName(normalizedPackageName);\n specifier.newDefaultName = normalizedPackageName;\n }\n\n existingSpecifiers.push(specifier);\n }\n\n continue;\n }\n\n // Add without default rewrite\n existingSpecifiers.push(...specifiers);\n }\n }\n\n // Example: <script src=\"../node_modules/lodash/lodash.js\"></script>\n if (isHtmlMetadata(inputMetadata)) {\n const scriptTags = inputMetadata.ast.querySelectorAll(\"script[src]\");\n\n for (const scriptTag of scriptTags) {\n const source = scriptTag.getAttribute(\"src\");\n if (!source) continue;\n\n const scriptType = scriptTag.getAttribute(\"type\");\n if (!isScriptType(scriptType)) {\n continue;\n }\n\n const sourceRootRelative = join(dirname(inputMetadata.filePath), source);\n\n // Only sources pointing to node_modules paths.\n if (!isNodeModulesPath(sourceRootRelative, root)) continue;\n\n const packageName = pathPackageMap.get(join(root, sourceRootRelative));\n if (!packageName) {\n printFormattedError(\n `Could not resolve package name for script src \"${source}\" ` +\n `(in \"${inputMetadata.filePath}\"). ` +\n `The script tag will not be included in the bundled packages.`\n );\n continue;\n }\n\n // Set the source to where the package will be output.\n const packageOutputPath = calcPackageOutPath(packageName, packagesOutputDirection);\n const newSource = relative(dirname(inputMetadata.filePath), packageOutputPath);\n scriptTag.setAttribute(\"src\", newSource);\n\n // Merge newly found specifiers with any already collected for this package.\n const existingSpecifiers = specifiersByPackage.get(packageName) ?? [];\n existingSpecifiers.push({ type: \"side-effect\" });\n specifiersByPackage.set(packageName, existingSpecifiers);\n }\n\n // Example: <link rel=\"stylesheet\" href=\"../node_modules/highlight.js/styles/default.css\" />\n const styleLinks = inputMetadata.ast.querySelectorAll('link[rel=\"stylesheet\"], link[rel=\"preload\"][as=\"style\"]');\n\n for (const styleLink of styleLinks) {\n const source = styleLink.getAttribute(\"href\");\n if (!source) continue;\n\n const sourceRootRelative = join(dirname(inputMetadata.filePath), source);\n\n // Only sources pointing to node_modules paths.\n if (!isNodeModulesPath(sourceRootRelative, root)) continue;\n\n // A package ships it, so it belongs next to the other package output rather than under `node_modules`.\n const assetOutputPath = calcPackageAssetOutPath(sourceRootRelative, packagesOutputDirection);\n const assetPath = join(root, sourceRootRelative);\n const asset = this.metadataList.find(metadata => join(root, metadata.id) === assetPath);\n\n if (asset && asset.filePath !== assetOutputPath) {\n await this.rebase(asset, join(root, assetOutputPath));\n asset.filePath = assetOutputPath;\n }\n\n styleLink.setAttribute(\"href\", relative(dirname(inputMetadata.filePath), assetOutputPath));\n }\n }\n }\n\n /**\n * Tracks packages that need to be re-bundled. During bundling, we might detect that a package imports another package whose\n * specifiers we have already collected. This means we need to recollect the specifiers from the discovered package and\n * re-bundle the current package.\n */\n const pendingReBundles: {\n dependencyName: string;\n dependencyOutputPath: string;\n importerName: string;\n importerOutputPath: string;\n }[] = [];\n\n // Bundle chunks\n for (const [chunkName, packages] of Object.entries(chunks)) {\n if (packages.length === 0) continue;\n\n let contents = \"\";\n for (const [packageName, specifiers] of specifiersByPackage) {\n if (specifiers.length === 0) continue;\n\n const isMatch = matchesPackage(packageName, packages);\n if (!isMatch) continue;\n\n contents += generateStdinString(specifiers, packageName);\n }\n\n if (!contents) continue;\n\n // On demand builds collect specifiers one page at a time, so a chunk bundled for an earlier page is missing\n // whatever the current page adds to it.\n const bundledChunk = this.findMetadata({ type: METADATA_TYPES.Package, id: chunkName });\n if (bundledChunk && chunkContents.get(chunkName) === contents) continue;\n\n const packageOutputPath = calcPackageOutPath(chunkName, packagesOutputDirection);\n\n const packageMetadata: PackageMetadata = isPackageMetadata(bundledChunk)\n ? bundledChunk\n : {\n type: METADATA_TYPES.Package,\n packageName: chunkName,\n code: \"\",\n filePath: packageOutputPath,\n id: chunkName,\n directDependencies: new Set(),\n };\n\n // Re-collected while bundling\n packageMetadata.directDependencies.clear();\n\n const [bundledCode, bundleError] = await bundlePackage({\n contents,\n resolveDir: this.root,\n outfile: packageOutputPath,\n packageName: chunkName,\n minify: this.production,\n production: this.production,\n treeShaking: this.production,\n onPackageResolve: importedPackageName => {\n const packageChunkName = getChunkName(importedPackageName, chunks);\n if (packageChunkName === chunkName) {\n // Custom resolve path\n const customPath = getCustomPackagePath(this.root, importedPackageName, this.production, resolvePackage);\n if (customPath) {\n return { path: customPath, external: false };\n }\n\n // Let esbuild include the package in the bundle if it's in the same chunk\n return;\n }\n\n const packageOrChunkName = packageChunkName ?? importedPackageName;\n const dependencyOutputPath = calcPackageOutPath(packageOrChunkName, packagesOutputDirection);\n\n packageMetadata.directDependencies.add(dependencyOutputPath);\n\n pendingReBundles.push({\n dependencyName: importedPackageName,\n dependencyOutputPath,\n importerName: chunkName,\n importerOutputPath: packageOutputPath,\n });\n\n // A new package discovered as a dependency during bundling.\n // Adding to `specifiersByPackage` will bundle it in the first pass,\n // it will then be re-bundled with the correct specifiers.\n const isNewPackage = !specifiersByPackage.has(importedPackageName);\n if (isNewPackage) {\n specifiersByPackage.set(importedPackageName, [{ type: \"unknown\" }]);\n }\n\n // Rewrite the dependency's import path\n const relativePathFromImporter = relative(dirname(packageOutputPath), dependencyOutputPath);\n\n return { path: relativePathFromImporter, external: true };\n },\n });\n\n if (bundleError) {\n printFormattedError(`Failed to bundle package \"${chunkName}\"`, bundleError);\n continue;\n }\n\n packageMetadata.code = bundledCode;\n chunkContents.set(chunkName, contents);\n\n if (!bundledChunk) {\n this.addMetadata(packageMetadata);\n }\n }\n\n // Bundle every collected package except chunks\n\n for (const [packageName, specifiers] of specifiersByPackage) {\n if (specifiers.length === 0) continue;\n\n // Already bundled\n const packageMetadataExists = this.findMetadata({ type: METADATA_TYPES.Package, id: packageName });\n if (packageMetadataExists) continue;\n\n // Already bundled as a chunk\n const chunk = getChunkName(packageName, chunks);\n if (chunk) continue;\n\n const packageOutputPath = calcPackageOutPath(packageName, packagesOutputDirection);\n\n const packageMetadata: PackageMetadata = {\n type: METADATA_TYPES.Package,\n packageName,\n code: \"\",\n filePath: packageOutputPath,\n id: packageName,\n directDependencies: new Set(),\n };\n\n let isLoadAsIs = !this.production;\n for (const [index, specifier] of Array.from(specifiers).entries()) {\n if (specifier.type !== \"unknown\") continue;\n isLoadAsIs = true;\n specifiers.splice(index, 1);\n }\n\n const contents = isLoadAsIs ? undefined : generateStdinString(specifiers, packageName);\n\n const [bundledCode, bundleError] = await bundlePackage({\n contents,\n entryPoint: isLoadAsIs ? packageName : undefined,\n resolveDir: this.root,\n outfile: packageOutputPath,\n packageName,\n minify: this.production,\n production: this.production,\n treeShaking: this.production,\n onPackageResolve: importedPackageName => {\n const packageChunkName = getChunkName(importedPackageName, chunks);\n const packageOrChunkName = packageChunkName ?? importedPackageName;\n\n const dependencyOutputPath = calcPackageOutPath(packageOrChunkName, packagesOutputDirection);\n\n packageMetadata.directDependencies.add(dependencyOutputPath);\n\n pendingReBundles.push({\n dependencyName: importedPackageName,\n dependencyOutputPath,\n importerName: packageName,\n importerOutputPath: packageOutputPath,\n });\n\n // A new package discovered as a dependency during bundling.\n // Adding to `specifiersByPackage` (live list) will bundle it in the first pass;\n // it will then be re-bundled with the correct specifiers.\n const isNewPackage = !specifiersByPackage.has(importedPackageName);\n if (isNewPackage) {\n specifiersByPackage.set(importedPackageName, [{ type: \"unknown\" }]);\n }\n\n const relativePathFromImporter = relative(dirname(packageOutputPath), dependencyOutputPath);\n\n return { path: relativePathFromImporter, external: true };\n },\n });\n\n if (bundleError) {\n printFormattedError(`Failed to bundle package \"${packageName}\"`, bundleError);\n continue;\n }\n\n packageMetadata.code = bundledCode;\n\n this.addMetadata(packageMetadata);\n }\n\n // In dev mode, we don't need to tree-shake.\n if (!this.production) return;\n\n // Re-bundle pass: handle packages imported by other packages\n\n for (const { dependencyOutputPath, dependencyName, importerName, importerOutputPath } of pendingReBundles) {\n // The bundled package to re-bundle with the new specifiers.\n const packageToBundle = this.metadataList.find(m => m.filePath === dependencyOutputPath);\n if (!isPackageMetadata(packageToBundle)) {\n printFormattedError(\n `Re-bundle failed: could not find bundled asset for \"${dependencyOutputPath}\".`,\n `The package \"${dependencyName}\" is not bundled.`\n );\n continue;\n }\n\n // The bundled package that has the new specifiers.\n const importerBundle = this.metadataList.find(m => m.filePath === importerOutputPath);\n if (!isPackageMetadata(importerBundle)) {\n printFormattedError(\n `Re-bundle failed: could not find bundled asset for \"${importerOutputPath}\".`,\n `The package \"${importerName}\" is not bundled.`\n );\n continue;\n }\n\n // Heavy task, parse the bundled package into a script metadata\n const importerScript = await this.load(importerBundle.filePath, { code: importerBundle.code, type: \"js\" });\n if (!isScriptMetadata(importerScript)) {\n printFormattedError(\n `Re-bundle failed: could not parse asset \"${importerOutputPath}\" as a script.`,\n `The package \"${importerName}\" may be missing specifiers.`\n );\n continue;\n }\n\n const sources = collectSpecifiersFromAst(importerScript.ast);\n\n const collectedSpecifiers: Specifier[] = [];\n\n for (const sourceReference of sources) {\n const source = sourceReference.source;\n const sourceRootRelative = join(dirname(importerScript.filePath), source);\n\n // Focus only on imports that resolve to the dependency's output path.\n if (sourceRootRelative === dependencyOutputPath) {\n const specifiers = sourceReference.specifiers;\n collectedSpecifiers.push(...specifiers);\n }\n }\n\n if (collectedSpecifiers.length === 0) {\n printFormattedError(\n `Re-bundle failed: could not find an import of \"${dependencyOutputPath}\" inside \"${importerOutputPath}\".`,\n `\\nThe dependency \"${dependencyName}\" may be missing specifiers.`\n );\n continue;\n }\n\n // Failed to find correct specifiers for this package.\n const isUnknownSpecifier = collectedSpecifiers.some(specifier => specifier.type === \"unknown\");\n if (isUnknownSpecifier) {\n this.log.warn(\n `Cannot tree-shake the package \"${dependencyName}\" correctly. The package \"${importerName}\" has dynamic imports with unresolved specifiers.`\n );\n continue;\n }\n\n // Merge the newly discovered specifiers with any already collected,\n // filtering out duplicates that are already present.\n const allSpecifiers: Specifier[] = specifiersByPackage.get(dependencyName) ?? [];\n const newSpecifiers = diffSpecifiers(allSpecifiers, collectedSpecifiers);\n\n // If every specifier is already covered, the existing bundle is complete — skip.\n if (newSpecifiers.length === 0) {\n continue;\n }\n\n allSpecifiers.push(...newSpecifiers);\n specifiersByPackage.set(dependencyName, allSpecifiers);\n\n // We are going to re-collect the direct dependencies during rebundling, so we need to clear them first\n packageToBundle.directDependencies.clear();\n\n // Add the new specifiers to the existing bundle\n const contents = generateStdinString(allSpecifiers, dependencyName);\n\n const [reBundledCode, reBundleError] = await bundlePackage({\n contents,\n resolveDir: this.root,\n outfile: dependencyOutputPath,\n packageName: dependencyName,\n production: this.production,\n minify: true,\n treeShaking: true,\n onPackageResolve: importedPackageName => {\n const packageChunkName = getChunkName(importedPackageName, chunks);\n const packageOrChunkName = packageChunkName ?? importedPackageName;\n\n const dependencyOutputPath = calcPackageOutPath(packageOrChunkName, packagesOutputDirection);\n packageToBundle.directDependencies.add(dependencyOutputPath);\n const relativePathFromImporter = relative(dirname(packageToBundle.filePath), dependencyOutputPath);\n\n return { path: relativePathFromImporter, external: true };\n },\n });\n\n if (reBundleError) {\n printFormattedError(`Failed to re-bundle package \"${dependencyName}\"`, reBundleError);\n continue;\n }\n\n // Replace the old bundle with the new one\n packageToBundle.code = reBundledCode;\n }\n },\n };\n}\n","import { mkdirSync } from \"node:fs\";\nimport * as t from \"@babel/types\";\nimport { HTMLElement } from \"@staticbolt/node-html-parser\";\nimport { globSync } from \"glob\";\n\nimport { isValidRelativePath, splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { filterScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { basename, dirname, join, isPathMatch, relative, replaceExtension } from \"../../utilities/path.ts\";\n\nimport type { App, Plugin } from \"@staticbolt/core\";\n\nexport type ImageFormat = \"webp\" | \"avif\" | \"png\" | \"jpeg\";\nexport type ImagePreset = \"default\" | \"photo\" | \"picture\" | \"drawing\" | \"icon\" | \"text\";\n\nexport interface ConvertImageOptions {\n /**\n * Format to convert images to.\n *\n * @default webp\n */\n format?: ImageFormat;\n\n /**\n * Image quality of the output image `(1-100)`.\n *\n * @default 100\n */\n quality?: number;\n\n /**\n * Presets for image compression (work for `WebP` format only).\n *\n * @default default\n */\n preset?: ImagePreset;\n\n /**\n * Glob patterns to include in image processing.\n *\n * @default [\"sources/assets/**\\/*.{jpg,jpeg,png}\"]\n */\n include?: string[];\n\n /**\n * Glob patterns to ignore in image processing.\n *\n * @default [ ]\n */\n exclude?: string[];\n}\n\n/**\n * Converts the images matched by \"include\" to a single target format with sharp, and rewrites every reference to them.\n *\n * References are updated wherever the sources pipeline sees them (HTML attributes, styles, scripts, web manifest); an \"image/*\"\n * type on the tag or manifest entry is rewritten too. In scripts, \"_img.<ext>\" expressions are replaced with the format string,\n * so the same code resolves to the original extension in development and to the converted one in production.\n *\n * Quality and preset can be overridden per file through the filename: \"hero-q:75-p:picture.jpg\".\n *\n * Notes:\n *\n * - Conversion happens after the build and only in production; development keeps serving the originals untouched.\n * - The output mirrors the source path relative to the project root, with only the extension replaced.\n * - Converted sources are published on \"pluginData.convertedImages\" so copy-assets does not copy the originals over them.\n * - \"preset\" is a WebP-only option and is ignored by the other formats.\n */\nexport function convertImagePlugin(options: ConvertImageOptions = {}): Plugin {\n const format = options.format ?? \"webp\";\n const include = options.include ?? [\"sources/assets/**/*.{jpg,jpeg,png}\"];\n const ignore = options.exclude ?? [];\n const preset = options.preset ?? \"default\";\n const quality = options.quality ?? 100;\n\n /** - Replaces an image relative path extension if it is included to be converted */\n function replaceImgExtension(this: App, source: string, filePath: string) {\n // absolute url or not a file path\n if (!isValidRelativePath(source)) return;\n\n const [link, suffix] = splitHtmlLink(source);\n\n const relativeToRoot = join(dirname(filePath), link);\n\n if (!isPathMatch(relativeToRoot, { include, ignore, root: this.root })) return;\n\n return {\n newSource: replaceExtension(link, \".\" + format) + suffix,\n imgPath: join(this.root, relativeToRoot),\n };\n }\n\n const supported = new Set([\"png\", \"jpg\", \"jpeg\", \"webp\", \"avif\"]);\n const convertedImages = new Set<string>();\n\n return {\n name: \"convert-images\",\n\n setup() {\n if (this.production) {\n this.pluginData.convertedImages ??= convertedImages;\n }\n },\n\n async transform(inputMetadata) {\n for (const { metadata } of filterScriptMetadata(inputMetadata)) {\n const log = this.log;\n const isProduction = this.production;\n\n t.traverse(metadata.ast, {\n enter(node, ancestors) {\n if (!t.isMemberExpression(node) || !t.isIdentifier(node.property)) return;\n if (!t.isIdentifier(node.object, { name: \"_img\" })) return;\n\n const property = node.property.name;\n if (!supported.has(property)) return;\n\n const capturedAncestor = ancestors.at(-1);\n if (!capturedAncestor) {\n log.error(\"Internal error. Couldn't find ancestor\");\n return;\n }\n\n const parentNode = capturedAncestor.node;\n\n const newNode = t.stringLiteral(isProduction ? format : property);\n\n if (capturedAncestor.index === undefined) {\n // @ts-expect-error so many wrong types\n parentNode[capturedAncestor.key] = newNode;\n return;\n }\n\n // @ts-expect-error so many wrong types\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n parentNode[capturedAncestor.key][capturedAncestor.index] = newNode;\n },\n });\n }\n\n if (!this.production) return;\n\n const sources = await this.requestSources(inputMetadata);\n for (const sourceReference of sources) {\n const source = sourceReference.source;\n\n const replaceResults = replaceImgExtension.call(this, source, inputMetadata.filePath);\n if (!replaceResults) continue;\n\n sourceReference.source = replaceResults.newSource;\n\n // HTML link with image type\n if (sourceReference.node instanceof HTMLElement) {\n const imgType = sourceReference.node.getAttribute(\"type\");\n if (imgType?.startsWith(\"image/\")) {\n sourceReference.node.setAttribute(\"type\", `image/${format}`);\n }\n }\n\n // Web Manifest entry with image type\n if (sourceReference.node && \"src\" in sourceReference.node && \"type\" in sourceReference.node) {\n sourceReference.node.type = `image/${format}`;\n }\n }\n },\n\n async postBuild() {\n if (!this.production) return;\n\n this.pluginData.convertedImages ??= convertedImages;\n\n const imageFiles = globSync(include, { ignore, nodir: true, cwd: this.root });\n\n const { default: sharp } = await import(\"sharp\");\n\n const promises = imageFiles.map(file => {\n const absImgPath = join(this.root, file);\n convertedImages.add(absImgPath);\n\n const relativeToRoot = relative(this.root, absImgPath);\n const outputFile = join(this.outdir, replaceExtension(relativeToRoot, `.${format}`));\n mkdirSync(dirname(outputFile), { recursive: true });\n\n const parsed = parseOptionFromImgPath(basename(relativeToRoot), quality, preset);\n return sharp(absImgPath).toFormat(format, parsed).toFile(outputFile);\n });\n\n await Promise.all(promises);\n },\n };\n}\n\nfunction parseOptionFromImgPath(imgPath: string, defaultQuality: number, defaultPreset: string) {\n // extract quality from filename matching \"image-q:100.png\"\n const qualityMatch = imgPath.match(/-q:(\\d{1,3})/)?.[1];\n const quality = qualityMatch === undefined ? defaultQuality : Number.parseInt(qualityMatch);\n\n // extract preset from filename matching \"image-p:default.png\"\n const presetMatch = imgPath.match(/-p:(default|photo|picture|drawing|icon|text)/)?.[1];\n const preset = (presetMatch ?? defaultPreset) as ImagePreset;\n\n return { quality, preset };\n}\n","import { copyFileSync, existsSync, mkdirSync } from \"node:fs\";\nimport { globSync } from \"glob\";\n\nimport { dirname, join } from \"../../utilities/path.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface CopyAssetsOptions {\n /**\n * Glob patterns to copy and include.\n *\n * @default [\"sources/assets/**\\/*\"]\n */\n include?: string[];\n\n /**\n * Glob patterns to ignore and exclude when copying asset files.\n *\n * @default [ ]\n */\n exclude?: string[];\n\n /**\n * Files in the public directory are copied to the root of the output directory.\n *\n * @default \"public\"\n */\n publicDirectory?: string;\n}\n\n/**\n * Copies asset files into the output directory at the end of a production build.\n *\n * Two passes: files matching \"include\" keep their path relative to the project root, while everything under \"publicDirectory\" is\n * copied to the output root with that prefix dropped (e.g. \"public/favicon.ico\" becomes \"<outdir>/favicon.ico\").\n *\n * Notes:\n *\n * - Runs after the build and only in production.\n * - Existing output files are never overwritten, and assets other plugins already emitted (converted images, optimized SVGs) are\n * skipped so the originals cannot replace them.\n * - \"exclude\" applies to both passes; the public pass also copies dotfiles.\n */\nexport function copyAssetsPlugin(options: CopyAssetsOptions = {}): Plugin {\n const include = options.include ?? [\"sources/assets/**/*\"];\n const ignore = options.exclude ?? [];\n const publicDirectory = options.publicDirectory ?? \"public\";\n\n return {\n name: \"copy-assets\",\n\n postBuild() {\n if (!this.production) return;\n\n const convertedImages = (this.pluginData.convertedImages as Set<string> | undefined) ?? new Set<string>();\n const optimizedSvgList = (this.pluginData.optimizedSvgList as Set<string> | undefined) ?? new Set<string>();\n\n const assetsFiles = globSync(include, { ignore, nodir: true, cwd: this.root });\n\n for (const file of assetsFiles) {\n const inputFile = join(this.root, file); // abs\n\n // ignore images that are converted\n if (convertedImages.has(inputFile)) continue;\n\n // optimized svg\n if (optimizedSvgList.has(inputFile)) continue;\n\n const outputFile = join(this.outdir, file);\n\n if (existsSync(outputFile)) continue;\n\n mkdirSync(dirname(outputFile), { recursive: true });\n\n copyFileSync(inputFile, outputFile);\n }\n\n const publicFiles = globSync(\"**/*\", { ignore, nodir: true, cwd: join(this.root, publicDirectory), dot: true });\n\n for (const file of publicFiles) {\n const inputFile = join(this.root, publicDirectory, file); // abs\n\n // ignore images that are converted\n if (convertedImages.has(inputFile)) continue;\n\n // optimized svg\n if (optimizedSvgList.has(inputFile)) continue;\n\n const outputFile = join(this.outdir, file);\n\n if (existsSync(outputFile)) continue;\n\n mkdirSync(dirname(outputFile), { recursive: true });\n\n copyFileSync(inputFile, outputFile);\n }\n },\n };\n}\n","import type { EaseFunction, ViewBox } from \"./types.js\";\n\n/** - Converts a path string to two dimensional array `[[M], ...[C]]` */\nexport function getPointsFromPathString(path: string, viewBox: ViewBox) {\n const x = viewBox.x;\n const y = viewBox.y;\n const height = viewBox.height;\n const width = viewBox.width;\n\n // get numbers from the string and convert them from percentage values.\n const match = path.match(/-?[0-9.]+/g);\n if (!match) throw new Error(\"invalid path\");\n\n const pathData = match.map((v, index) => (index % 2 === 0 ? Number(v) * width + x : Number(v) * height + y));\n\n const points: number[][] = [];\n\n if (pathData.length === 0) return points;\n\n points.push([pathData[0], pathData[1]]); // M points\n\n // C points\n for (let index = 2; index < pathData.length; index += 6) {\n points.push([\n pathData[index],\n pathData[index + 1],\n pathData[index + 2],\n pathData[index + 3],\n pathData[index + 4],\n pathData[index + 5],\n ]);\n }\n\n return points;\n}\n\n/** Computes the point (x, y) on the curve for a given time `t` [0 to 1] */\nfunction findPointFromT(\n p0x: number,\n p0y: number,\n c0x: number,\n c0y: number,\n c1x: number,\n c1y: number,\n p1x: number,\n p1y: number,\n t: number\n) {\n const point = { x: 0, y: 0 };\n const mt = 1 - t;\n const mt2 = mt * mt;\n const mt3 = mt2 * mt;\n\n point.x = p0x * mt3 + c0x * 3 * mt2 * t + c1x * 3 * mt * t * t + p1x * t ** 3;\n point.y = p0y * mt3 + c0y * 3 * mt2 * t + c1y * 3 * mt * t * t + p1y * t ** 3;\n\n return point;\n}\n\n/** Computes the Y-coordinate of a point on the curve given its X-coordinate. */\nfunction solvePositionYFromT(\n p0x: number,\n p0y: number,\n c0x: number,\n c0y: number,\n c1x: number,\n c1y: number,\n p1x: number,\n p1y: number,\n t: number\n): number {\n // Desired precision on the computation.\n const epsilon = 1e-6;\n\n // A binary search algorithm is used to determine the Y-coordinate value\n // corresponding to a specified position on the X-coordinate.\n let start = 0;\n let end = 1;\n let target = (start + end) / 2;\n let times = 0;\n\n while (target >= start && target <= 1) {\n const { x, y } = findPointFromT(p0x, p0y, c0x, c0y, c1x, c1y, p1x, p1y, target);\n\n // If the point cannot be found within 50 attempts, a safe loop break will be triggered.\n if (++times > 50) return y;\n\n // Return the located Y-coordinate value.\n if (Math.abs(x - t) <= epsilon) return y;\n\n if (x >= t) end = target;\n else start = target;\n\n target = (start + end) / 2;\n }\n\n return 0;\n}\n\nexport function generateEasingFunctionFromArray(curves: number[][]) {\n return (t: number) => {\n if (t === 0) return curves[0][1];\n if (t === 1) return curves.at(-1)![7];\n\n for (const [p0x, p0y, c0x, c0y, c1x, c1y, p1x, p1y] of curves) {\n if (t <= p1x) {\n return solvePositionYFromT(p0x, p0y, c0x, c0y, c1x, c1y, p1x, p1y, t);\n }\n }\n\n return 0;\n };\n}\n\n/** Converts the values in a two-dimensional array to percentage values (ranging from 0 to 1). */\nfunction convertPointsToRelativeValues(array: number[][], viewBox: ViewBox) {\n const x = viewBox.x;\n const y = viewBox.y;\n const height = viewBox.height;\n const width = viewBox.width;\n\n return array.map(curve => curve.map((v, index) => (index % 2 === 0 ? (v - x) / width : (v - y) / height)));\n}\n\n/**\n * - Convert to relative value ->\n * - Flip the Y points ->\n * - Store only Cubic curves with starting, control, and ending points (without the first M command).\n */\nexport function preparePointsForAnimation(array: number[][], viewBox: ViewBox) {\n const relativePoints = convertPointsToRelativeValues(array, viewBox);\n\n const results: number[][] = [];\n\n let x = 0;\n let y = 0;\n for (const [index, curve] of relativePoints.entries()) {\n const c1x = curve[0];\n const c1y = 1 - curve[1];\n\n if (!index) {\n x = c1x;\n y = c1y;\n continue;\n }\n\n const c2x = curve[2];\n const c2y = 1 - curve[3];\n const px = curve[4];\n const py = 1 - curve[5];\n\n results.push([x, y, c1x, c1y, c2x, c2y, px, py]);\n\n x = px;\n y = py;\n }\n\n return results;\n}\n\n/** Runs an easing function backwards. */\nexport function out(easing: EaseFunction): EaseFunction {\n return t => 1 - easing(1 - t);\n}\n\n/**\n * Makes any easing function symmetrical. The easing function will run forwards for half of the duration, then backwards for the\n * rest of the duration.\n */\nexport function inOut(easing: EaseFunction): EaseFunction {\n return t => {\n if (t < 0.5) return easing(t * 2) / 2;\n return 1 - easing((1 - t) * 2) / 2;\n };\n}\n\nexport function convertEasingFunctionToLinearFN(easingFunction: EaseFunction, samples: number) {\n const values = new Float32Array(samples);\n let count = 0;\n\n for (let index = 0; index < samples; index++) {\n const t = index / (samples - 1);\n values[count++] = easingFunction(t);\n }\n\n const valuesString = Array.from(values, string => +string.toFixed(2)).join(\",\");\n\n return `linear(${valuesString})`;\n}\n","import {\n generateEasingFunctionFromArray,\n getPointsFromPathString,\n inOut,\n out,\n preparePointsForAnimation,\n} from \"./ease-utilities.ts\";\n\nimport type { EaseFunction } from \"./types.d.ts\";\n\nfunction spring(mass = 1, stiffness = 100, damping = 10, velocity = 0, duration = 1000): EaseFunction {\n const clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max);\n return (time: number) => {\n if (time === 0 || time === 1) return time;\n\n mass = clamp(mass, 0.1, 1000);\n stiffness = clamp(stiffness, 0.1, 1000);\n damping = clamp(damping, 0.1, 1000);\n velocity = clamp(velocity, 0.1, 1000);\n\n const w0 = Math.sqrt(stiffness / mass),\n zeta = damping / (2 * Math.sqrt(stiffness * mass)),\n wd = zeta < 1 ? w0 * Math.sqrt(1 - zeta * zeta) : 0,\n a = 1,\n b = zeta < 1 ? (zeta * w0 + -velocity) / wd : -velocity + w0;\n\n let progress = duration ? (duration * time) / 1000 : time;\n\n progress =\n zeta < 1\n ? Math.exp(-progress * zeta * w0) * (a * Math.cos(wd * progress) + b * Math.sin(wd * progress))\n : (a + b * progress) * Math.exp(-progress * w0);\n\n return 1 - progress;\n };\n}\n\nfunction wobble(bounciness = 1): EaseFunction {\n const p = bounciness * Math.PI;\n return (t: number): number => 1 - Math.pow(Math.cos((t * Math.PI) / 2), 3) * Math.cos(t * p);\n}\n\nfunction bounce(t: number): number {\n const n1 = 7.5625;\n const d1 = 2.75;\n if (t < 1 / d1) return n1 * t * t;\n if (t < 2 / d1) return n1 * (t -= 1.5 / d1) * t + 0.75;\n if (t < 2.5 / d1) return n1 * (t -= 2.25 / d1) * t + 0.9375;\n return n1 * (t -= 2.625 / d1) * t + 0.984375;\n}\n\nfunction custom(path: string) {\n const viewBox = { x: 0, y: 0, width: 1, height: 1 };\n const curves = getPointsFromPathString(path, viewBox);\n const relativeCurves = preparePointsForAnimation(curves, viewBox);\n\n return generateEasingFunctionFromArray(relativeCurves);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const predefinedEasing: Record<string, string | ((...arguments_: any[]) => EaseFunction)> = {\n spring,\n custom,\n\n // IN\n \"in-circ\": \"cubic-bezier(0.55, 0, 1, 0.45)\",\n \"in-cubic\": \"cubic-bezier(0.32, 0, 0.67, 0)\",\n \"in-expo\": \"cubic-bezier(0.7, 0, 0.84, 0)\",\n \"in-sine\": \"cubic-bezier(0.12, 0, 0.39, 0)\",\n \"in-quad\": \"cubic-bezier(0.11, 0, 0.5, 0)\",\n \"in-quart\": \"cubic-bezier(0.5, 0, 0.75, 0)\",\n \"in-quint\": \"cubic-bezier(0.64, 0, 0.78, 0)\",\n \"in-back\": (c1 = 1.70158) => {\n return (t: number) => (c1 + 1) * t * t * t - c1 * t * t;\n },\n \"in-bounce\": () => (t: number) => 1 - bounce(1 - t),\n \"in-elastic\": () => (t: number) => {\n const c4 = (2 * Math.PI) / 3;\n return t === 0 ? 0 : t === 1 ? 1 : -Math.pow(2, 10 * t - 10) * Math.sin((t * 10 - 10.75) * c4);\n },\n \"in-poly\": (n: number) => (t: number) => Math.pow(t, n),\n \"in-wobble\": (bounciness: number = 1) => out(wobble(bounciness)),\n\n // OUT\n \"out-circ\": \"cubic-bezier(0, 0.55, 0.45, 1)\",\n \"out-cubic\": \"cubic-bezier(0.33, 1, 0.68, 1)\",\n \"out-expo\": \"cubic-bezier(0.16, 1, 0.3, 1)\",\n \"out-sine\": \"cubic-bezier(0.61, 1, 0.88, 1)\",\n \"out-quad\": \"cubic-bezier(0.5, 1, 0.89, 1)\",\n \"out-quart\": \"cubic-bezier(0.25, 1, 0.5, 1)\",\n \"out-quint\": \"cubic-bezier(0.22, 1, 0.36, 1)\",\n \"out-back\": (c1: number = 1.70158) => {\n return (t: number) => {\n const c3 = c1 + 1;\n return 1 + c3 * Math.pow(t - 1, 3) + c1 * Math.pow(t - 1, 2);\n };\n },\n \"out-bounce\": () => bounce,\n \"out-elastic\": () => (t: number) => {\n const c4 = (2 * Math.PI) / 3;\n return t === 0 ? 0 : t === 1 ? 1 : Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * c4) + 1;\n },\n \"out-poly\": (n: number) => (t: number) => 1 - Math.pow(1 - t, n),\n \"out-wobble\": wobble,\n\n // IN-OUT\n \"in-out-circ\": \"cubic-bezier(0.85, 0, 0.15, 1)\",\n \"in-out-cubic\": \"cubic-bezier(0.65, 0, 0.35, 1)\",\n \"in-out-expo\": \"cubic-bezier(0.87, 0, 0.13, 1)\",\n \"in-out-sine\": \"cubic-bezier(0.37, 0, 0.63, 1)\",\n \"in-out-quad\": \"cubic-bezier(0.45, 0, 0.55, 1)\",\n \"in-out-quart\": \"cubic-bezier(0.76, 0, 0.24, 1)\",\n \"in-out-quint\": \"cubic-bezier(0.83, 0, 0.17, 1)\",\n \"in-out-back\": (c1 = 1.70158) => {\n return (t: number) => {\n const c2 = c1 * 1.525;\n return t < 0.5\n ? (Math.pow(2 * t, 2) * ((c2 + 1) * 2 * t - c2)) / 2\n : (Math.pow(2 * t - 2, 2) * ((c2 + 1) * (t * 2 - 2) + c2) + 2) / 2;\n };\n },\n \"in-out-bounce\": () => (t: number) => (t < 0.5 ? (1 - bounce(1 - 2 * t)) / 2 : (1 + bounce(2 * t - 1)) / 2),\n \"in-out-elastic\": () => (t: number) => {\n const c5 = (2 * Math.PI) / 4.5;\n return t === 0\n ? 0\n : t === 1\n ? 1\n : t < 0.5\n ? -(Math.pow(2, 20 * t - 10) * Math.sin((20 * t - 11.125) * c5)) / 2\n : (Math.pow(2, -20 * t + 10) * Math.sin((20 * t - 11.125) * c5)) / 2 + 1;\n },\n \"in-out-poly\": (n: number) => (t: number) => (t < 0.5 ? Math.pow(2, n - 1) * Math.pow(t, n) : 1 - Math.pow(-2 * t + 2, n) / 2),\n \"in-out-wobble\": (bounciness: number = 1) => inOut(wobble(bounciness)),\n};\n","import * as t from \"@babel/types\";\n\nimport { filterScriptMetadata, filterStyleMetadata, isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { printFmtError } from \"../../utilities/print-formatted-error.ts\";\nimport { convertEasingFunctionToLinearFN } from \"./easing-functions/ease-utilities.ts\";\nimport { predefinedEasing } from \"./easing-functions/ease.ts\";\n\nimport type { EaseFunction } from \"./easing-functions/types.d.ts\";\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface CustomEasePluginOptions {\n /**\n * Transform JS calls like `cssLinear.outCubic()` into their CSS easing string.\n *\n * @example\n * const ease = cssLinear.outCubic();\n * // → \"cubic-bezier(0.215, 0.61, 0.355, 1)\"\n *\n * @default false\n */\n replaceInJS?: boolean;\n\n /**\n * Name of the JS function namespace used for easing calls. The plugin looks for calls like `<name>.<ease>()`.\n *\n * @example\n * const ease = cssLinear.outCubic();\n *\n * @default \"cssLinear\"\n */\n jsFunctionName?: string;\n\n /**\n * Enable replacement of custom easing functions used in CSS.\n *\n * ```css\n * :root {\n * --custom-ease: --ease-out-cubic();\n * }\n * ```\n *\n * @default true\n */\n replaceInCSS?: boolean;\n\n /**\n * Prefix used to detect custom easing functions in CSS. Any function starting with this prefix will be replaced.\n *\n * ```css\n * :root {\n * --custom-ease: --ease-out-cubic();\n * }\n * ```\n *\n * @default \"--ease-\"\n */\n cssFunctionPrefix?: string;\n\n /**\n * Also process custom easing functions inside inline `style` attributes in HTML.\n *\n * ```html\n * <div style=\"--custom-ease: --ease-out-cubic()\"></div>\n * ```\n *\n * @default false\n */\n replaceInHtmlStyleAttribute?: boolean;\n\n /**\n * Additional custom easing definitions. Values can be either:\n *\n * - A CSS easing string\n * - A function returning a JS easing function\n *\n * @example\n * const customEase = {\n * \"in-circ\": \"cubic-bezier(0.55, 0, 1, 0.45)\",\n * \"out-poly\": (n: number) => (t: number) => 1 - Math.pow(1 - t, n),\n * };\n */\n customEase?: Record<string, string | ((...arguments_: unknown[]) => EaseFunction)>;\n\n /**\n * Number of samples used when converting easing functions to CSS `linear()`.\n *\n * Represents a balance between output quality and performance.\n *\n * @default 50\n */\n samples?: number;\n}\n\nexport type { CssLinear } from \"./easing-functions/types.d.ts\";\n\n/**\n * Replaces named easing calls with plain CSS values at build time, so there is nothing to resolve at runtime. Simple curves\n * become a \"cubic-bezier()\" string, computed ones (springs, bounces, elastics) are sampled into a \"linear()\" function.\n *\n * Three places, each with its own switch: CSS declarations (on by default, \"--ease-*()\" calls), JavaScript\n * (\"cssLinear.outCubic()\", opt-in) and inline HTML \"style\" attributes (opt-in).\n *\n * Notes:\n *\n * - Runs in development and production alike.\n * - JS call names are camelCase and matched kebab-cased, so \"cssLinear.outCubic()\" resolves the \"out-cubic\" definition.\n * - Anything that does not resolve is left exactly as written: unknown names, unbalanced parentheses, or arguments that are not\n * plain numbers (in JS they must be numeric literals).\n * - \"customEase\" entries are merged over the predefined set, so reusing a name overrides it.\n * - \"samples\" trades output size for accuracy; it only affects easings that end up as \"linear()\".\n */\nexport function customEasePlugin(options: CustomEasePluginOptions = {}): Plugin {\n options.customEase ??= {};\n const customEasing = { ...predefinedEasing, ...options.customEase };\n\n const shouldReplaceInHtml = options.replaceInHtmlStyleAttribute ?? false;\n\n const shouldReplaceInJS = options.replaceInJS ?? false;\n const jsFunctionName = options.jsFunctionName ?? \"cssLinear\";\n\n const shouldReplaceInCSS = options.replaceInCSS ?? true;\n const cssFunctionPrefix = options.cssFunctionPrefix ?? \"--ease-\";\n\n const samples = options.samples ?? 50;\n\n /** The CSS easing string for one custom easing call, or `undefined` when it cannot be resolved */\n function resolveEasing(name: string, arguments_: number[] | undefined, filePath: string): string | undefined {\n if (!arguments_) return;\n\n const easeFunctionName = name.slice(cssFunctionPrefix.length);\n if (!Object.hasOwn(customEasing, easeFunctionName)) return;\n\n const easeFunctionOrString = customEasing[easeFunctionName];\n\n // CSS Cubic Bezier string\n if (typeof easeFunctionOrString === \"string\") {\n return easeFunctionOrString;\n }\n\n try {\n return convertEasingFunctionToLinearFN(easeFunctionOrString(...arguments_), samples);\n } catch {\n printFmtError(\"Error generating easing function\", { function: customEasePlugin, filePath });\n }\n }\n\n /** Replace every custom easing call in a CSS value, leaving unknown and malformed ones as they are */\n function replaceEaseCalls(value: string, filePath: string): string {\n let output = \"\";\n let cursor = 0;\n\n while (cursor < value.length) {\n const { name, matchStartIndex, matchEndIndex, args } = parseFunctionCall(value.slice(cursor), cssFunctionPrefix);\n if (matchStartIndex < 0) break;\n\n const call = value.slice(cursor + matchStartIndex, cursor + matchEndIndex);\n output += value.slice(cursor, cursor + matchStartIndex) + (resolveEasing(name, args, filePath) ?? call);\n cursor += matchEndIndex;\n }\n\n return output + value.slice(cursor);\n }\n\n return {\n name: \"custom-ease\",\n\n transform(inputMetadata) {\n if (shouldReplaceInHtml && isHtmlMetadata(inputMetadata)) {\n const elements = inputMetadata.ast.querySelectorAll(\"[style]\");\n\n for (const node of elements) {\n const style = node.getAttribute(\"style\");\n if (!style) continue;\n\n const replaced = replaceEaseCalls(style, inputMetadata.id);\n if (replaced !== style) {\n node.setAttribute(\"style\", replaced);\n }\n }\n }\n\n if (shouldReplaceInJS) {\n for (const { metadata } of filterScriptMetadata(inputMetadata)) {\n t.traverse(metadata.ast, {\n enter(node, ancestors) {\n if (!t.isCallExpression(node)) return;\n\n const callee = node.callee;\n\n if (!t.isMemberExpression(callee) || !t.isIdentifier(callee.object) || !t.isIdentifier(callee.property)) {\n return;\n }\n\n if (callee.object.name !== jsFunctionName) {\n return;\n }\n\n const functionName = callee.property.name.replace(/[A-Z]/g, match => \"-\" + match.toLowerCase());\n if (!Object.hasOwn(customEasing, functionName)) return;\n\n const easeFunctionOrString = customEasing[functionName];\n\n const capturedAncestor = ancestors.at(-1);\n if (!capturedAncestor) {\n printFmtError(\"Internal error. Couldn't find ancestor\", { node });\n return;\n }\n\n const parentNode = capturedAncestor.node;\n\n const replaceWith = (newValue: string) => {\n const newNode = t.stringLiteral(newValue);\n\n if (capturedAncestor.index === undefined) {\n // @ts-expect-error so many wrong types\n parentNode[capturedAncestor.key] = newNode;\n return;\n }\n\n // @ts-expect-error so many wrong types\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n parentNode[capturedAncestor.key][capturedAncestor.index] = newNode;\n };\n\n // CSS Cubic Bezier string\n if (typeof easeFunctionOrString === \"string\") {\n replaceWith(easeFunctionOrString);\n return;\n }\n\n const arguments_: number[] = [];\n for (const argument of node.arguments) {\n if (!t.isNumericLiteral(argument)) {\n // TODO: error all args must be numbers\n return;\n }\n\n arguments_.push(argument.value);\n }\n\n const linearFunction = convertEasingFunctionToLinearFN(easeFunctionOrString(...arguments_), samples);\n\n replaceWith(linearFunction);\n },\n });\n }\n }\n\n if (shouldReplaceInCSS) {\n for (const { metadata } of filterStyleMetadata(inputMetadata)) {\n metadata.ast.walkDecls(declaration => {\n const replaced = replaceEaseCalls(declaration.value, inputMetadata.id);\n if (replaced !== declaration.value) {\n declaration.value = replaced;\n }\n });\n }\n }\n },\n };\n}\n\ninterface ParseFunctionCallResult {\n name: string;\n matchStartIndex: number;\n matchEndIndex: number;\n /** `undefined` when the argument list is not a plain list of numbers */\n args: number[] | undefined;\n}\n\nconst NOT_FOUND: ParseFunctionCallResult = { name: \"\", matchStartIndex: -1, matchEndIndex: -1, args: [] };\n\nconst functionCallReCache = new Map<string, RegExp>();\n\n/** Parse a string representing a function call and get its arguments and name */\nfunction parseFunctionCall(code: string, functionNamePrefix: string): ParseFunctionCallResult {\n let re = functionCallReCache.get(functionNamePrefix);\n if (!re) {\n const escapedPrefix = functionNamePrefix.replace(/[$()*+.?[\\\\\\]^{|}]/g, String.raw`\\$&`);\n re = new RegExp(String.raw`(?<![\\w-])(${escapedPrefix}[\\w-]*)\\(`);\n functionCallReCache.set(functionNamePrefix, re);\n }\n\n const match = re.exec(code);\n const name = match?.[1];\n if (!match || !name) {\n return NOT_FOUND;\n }\n\n const openIndex = match.index + match[0].length - 1;\n const closeIndex = findClosingParenthesis(code, openIndex);\n if (closeIndex < 0) {\n return NOT_FOUND;\n }\n\n const result: ParseFunctionCallResult = {\n name,\n matchStartIndex: match.index,\n matchEndIndex: closeIndex + 1,\n args: [],\n };\n\n const argumentsString = code.slice(openIndex + 1, closeIndex).trim();\n if (!argumentsString) {\n return result;\n }\n\n result.args = parseNumericArguments(argumentsString);\n if (!result.args) {\n console.warn(`Failed to parse function call: ${code.slice(match.index, closeIndex + 1)}`);\n }\n\n return result;\n}\n\n/** - Split a CSS argument list into numbers, or `undefined` when any of them is not a number */\nfunction parseNumericArguments(argumentsString: string): number[] | undefined {\n const arguments_: number[] = [];\n\n for (const part of argumentsString.split(\",\")) {\n const argument = Number(part);\n\n if (part.trim() === \"\" || Number.isNaN(argument)) {\n return;\n }\n\n arguments_.push(argument);\n }\n\n return arguments_;\n}\n\n/** Index of the `)` closing the `(` at `openIndex`, or `-1` when it is never closed */\nfunction findClosingParenthesis(code: string, openIndex: number): number {\n let depth = 0;\n\n for (let index = openIndex; index < code.length; index++) {\n const char = code[index];\n\n if (char === \"(\") {\n depth++;\n continue;\n }\n\n if (char === \")\") {\n depth--;\n if (depth === 0) {\n return index;\n }\n }\n }\n\n return -1;\n}\n","import { Log } from \"../../utilities/logger.ts\";\nimport { join } from \"../../utilities/path.ts\";\nimport { readJsonFile } from \"../../utilities/read-json-file.ts\";\n\ninterface RecursiveRecord {\n [key: string]: string | RecursiveRecord;\n}\n\nexport interface GetLocalsResult {\n /** An object the key is the language and the value is a map of keysPath-value */\n localesMap: { [key: string]: Map<string, string> };\n\n /** An object the key is the language and the value is a data of the language */\n localesObj: Record<string, RecursiveRecord>;\n\n getKey(key: string, locale: string): string;\n}\n\ninterface GetLocalsOptions {\n localesPath: string;\n supportedLocales: string[];\n}\n\nexport function getLocals(options: GetLocalsOptions) {\n if (getLocals.cache) {\n return getLocals.cache;\n }\n\n const { supportedLocales, localesPath } = options;\n\n const result: GetLocalsResult = {\n localesMap: {},\n localesObj: {},\n getKey(key: string, locale: string) {\n return this.localesMap[locale]?.get(key) ?? \"\";\n },\n };\n\n for (const locale of supportedLocales) {\n const localePath = join(localesPath, locale + \".json\");\n\n const [localesData, parseError] = readJsonFile<RecursiveRecord>(localePath);\n if (parseError) {\n Log.error(`Failed to parse ${localePath}: ${parseError}`);\n continue;\n }\n\n result.localesObj[locale] = localesData;\n\n const pathValueMap = getAllPathsMap(localesData);\n result.localesMap[locale] = pathValueMap;\n }\n\n getLocals.cache = result;\n\n return result;\n}\n\ngetLocals.cache = null as GetLocalsResult | null;\n\nfunction getAllPathsMap(object: RecursiveRecord, prefix = \"\", result = new Map<string, string>()) {\n for (const key in object) {\n const path = prefix ? `${prefix}.${key}` : key;\n\n if (Object.hasOwn(object, key) && typeof object[key] === \"object\" && !Array.isArray(object[key])) {\n getAllPathsMap(object[key], path, result);\n continue;\n }\n\n result.set(path, (object as Record<string, string>)[key]);\n }\n\n return result;\n}\n","import { isValidRelativePath, splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { extname, isAbsolute, join, normalize, relative } from \"../../utilities/path.ts\";\nimport { getLocals, type GetLocalsResult } from \"./get-locales.ts\";\n\nimport type { I18nPluginOptions } from \"./i18n-plugin.ts\";\nimport type { HtmlMetadata, Plugin } from \"@staticbolt/core\";\n\nexport const propertyRe = /{{\\s+\\b(.*?)\\b(?:=(.*?))?\\s+}}/g;\n\n/**\n * The HTML half of i18nPlugin: once the page is transformed it is cloned per supported locale, and the translation markers are\n * resolved in each copy.\n *\n * Attributes:\n *\n * - \"i18n\": the key whose value becomes the element's text content.\n * - \"i18n-attr-<name>\": the key whose value becomes the \"<name>\" attribute.\n * - \"i18n-placeholder-<name>\": the value for a \"{{ name }}\" placeholder in the translation, or \"@another.key\" to reuse another\n * translation (\"@@\" escapes a literal \"@\").\n *\n * All three are removed from the output, and \"<html lang>\" is set to the locale of the copy.\n *\n * Notes:\n *\n * - The default locale keeps the original paths; every other locale is moved under its own directory (\"ar/index.html\").\n * - Links to pages are deliberately not rebased when a page moves into a locale directory, so they keep pointing inside that\n * locale; asset links are rebased as usual.\n * - The dev server strips a leading locale segment from a request and serves the same page.\n * - A missing key resolves to an empty string, and a placeholder with no value falls back to its default, then to nothing.\n */\nexport function i18nHtmlPlugin(options: Required<I18nPluginOptions>): Plugin {\n const { defaultLocale, i18nAttribute, i18nAttributePrefix, placeholderPrefix, localesDirectory, supportedLocales } = options;\n\n return {\n name: \"i18n-html-plugin\",\n\n resolveRequestPath(requestPath) {\n const [requestPathWithoutQuery] = splitHtmlLink(requestPath);\n\n const extension = extname(requestPathWithoutQuery);\n\n const isHtml = extension === \".html\" || extension === \"\";\n if (!isHtml) return;\n\n const parts = requestPath.replace(/^\\.\\//, \"\").split(\"/\");\n if (!supportedLocales.includes(parts[0])) return;\n\n const strippedRequestPath = join(...parts.slice(1));\n\n return strippedRequestPath;\n },\n\n // When rebasing for i18n (internationalization), skip links that point to HTML or Markdown files.\n // This is because all localized pages (e.g., ar/index.html) are moved to their own language-specific directories.\n // Only static asset links—such as CSS, JS, images, etc.—need to be rebased.\n rebaseSource(source, filePath, newAbsolutePath) {\n if (!isValidRelativePath(source)) return;\n\n // Only html\n if (extname(filePath) !== \".html\") {\n return;\n }\n\n const [link] = splitHtmlLink(source);\n\n // Only links pointing to directories or html files\n const extension = extname(link);\n if (extension && extension !== \".html\") {\n return;\n }\n\n const relativeNewPath = relative(this.root, newAbsolutePath);\n\n const oldPathParts = new Set(filePath.split(\"/\"));\n const newPathParts = relativeNewPath.split(\"/\");\n\n const partsDiff = newPathParts.filter(part => !oldPathParts.has(part));\n\n if (partsDiff.length === 1 && partsDiff[0] !== defaultLocale && supportedLocales.includes(partsDiff[0])) {\n return source;\n }\n },\n\n async postTransform() {\n if (supportedLocales.length === 0) {\n return;\n }\n\n const localesPath = isAbsolute(localesDirectory) ? normalize(localesDirectory) : join(this.root, localesDirectory);\n\n const locales = getLocals({ localesPath, supportedLocales });\n\n const metadataList = Array.from(this.metadataList); // not a live list\n\n for (const inputMetadata of metadataList) {\n if (!isHtmlMetadata(inputMetadata)) continue;\n\n this.removeMetadata(inputMetadata);\n\n for (const locale of supportedLocales) {\n const isDefaultLocale = locale === defaultLocale;\n\n const metadata = this.clone(inputMetadata);\n\n this.addMetadata(metadata);\n\n if (!isDefaultLocale) {\n const newPath = join(locale, metadata.filePath);\n await this.rebase(metadata, newPath);\n }\n\n processI18nInHTML({ metadata, locales, locale, placeholderPrefix, i18nAttribute, i18nAttributePrefix });\n }\n }\n },\n };\n}\n\ninterface ProcessI18nInHTMLOptions {\n metadata: HtmlMetadata;\n locales: GetLocalsResult;\n locale: string;\n\n i18nAttribute: string;\n placeholderPrefix: string;\n i18nAttributePrefix: string;\n}\n\nfunction processI18nInHTML(options: ProcessI18nInHTMLOptions) {\n const { metadata, locales, locale, placeholderPrefix, i18nAttribute, i18nAttributePrefix } = options;\n\n const rootElement = metadata.ast.querySelector(\"html\");\n if (rootElement) {\n rootElement.setAttribute(\"lang\", locale);\n }\n\n const allElements = metadata.ast.querySelectorAll(\"*\");\n for (const node of allElements) {\n if (!node.attrs) continue;\n\n const attributeValue = Object.entries(node.attrs);\n\n const i18nNameValuePair = Object.fromEntries(\n attributeValue\n .filter(([attribute]) => attribute.startsWith(placeholderPrefix))\n .map(([attribute, value]) => [attribute.replace(placeholderPrefix, \"\"), value])\n );\n\n const replacer = (_match: string, attribute: string, defaultValue: string | undefined) => {\n if (Object.hasOwn(i18nNameValuePair, attribute)) {\n const value = i18nNameValuePair[attribute];\n\n if (typeof value === \"string\") {\n if (!value.startsWith(\"@\") || value.startsWith(\"@@\")) {\n return value.replace(/^@@/, \"@\"); // unescape @\n }\n\n const localValue = locales.getKey(value.slice(1), locale);\n if (localValue) return localValue;\n }\n }\n\n if (defaultValue !== undefined) {\n return defaultValue;\n }\n\n return \"\";\n };\n\n // replace text content\n if (Object.hasOwn(node.attributes, i18nAttribute)) {\n const keysPath = node.getAttribute(i18nAttribute);\n\n node.removeAttribute(i18nAttribute);\n\n for (const attribute of Object.keys(i18nNameValuePair)) {\n node.removeAttribute(placeholderPrefix + attribute);\n }\n\n if (!keysPath) continue;\n\n const value = locales.getKey(keysPath, locale);\n // eslint-disable-next-line unicorn/no-unsafe-string-replacement\n node.textContent = value.replace(propertyRe, replacer);\n }\n\n // replace attributes\n const i18nForAttrList = attributeValue.filter(([attribute]) => attribute.startsWith(i18nAttributePrefix));\n\n for (const [attribute, keysPath] of i18nForAttrList) {\n node.removeAttribute(attribute);\n\n for (const attribute_ of Object.keys(i18nNameValuePair)) {\n node.removeAttribute(placeholderPrefix + attribute_);\n }\n\n const attributeToReplace = attribute.replace(i18nAttributePrefix, \"\");\n const value = locales.getKey(keysPath, locale);\n // eslint-disable-next-line unicorn/no-unsafe-string-replacement\n node.setAttribute(attributeToReplace, value.replace(propertyRe, replacer));\n }\n }\n}\n","import { writeFileSync } from \"node:fs\";\n\nimport { formatCode } from \"../../helpers/format-code.ts\";\nimport { Log } from \"../../utilities/logger.ts\";\nimport { isAbsolute, join, normalize, resolve } from \"../../utilities/path.ts\";\nimport { getLocals } from \"./get-locales.ts\";\nimport { propertyRe } from \"./i18n-html-plugin.ts\";\n\nimport type { I18nPluginOptions } from \"./i18n-plugin.ts\";\nimport type { Plugin } from \"@staticbolt/core\";\n\n/**\n * The CLI half of i18nPlugin: adds a \"locales\" command (aliased \"i18n\") that regenerates the editor support files from the\n * translation JSONs and writes them next to them in \"localesDirectory\".\n *\n * - \"i18n.html-data.json\": HTML custom data, so an editor completes keys for \"i18n\", \"i18n-attr-_\" and \"i18n-placeholder-_\".\n * - \"i18n.types.d.ts\": the global i18n types and the declarations of the \"i18n_*\" compile-time helpers.\n *\n * Notes:\n *\n * - Keys are taken from the default locale's file, so anything missing there is missing from the completions and the types.\n * - Nothing regenerates these during a build; run the command again after changing the translations.\n */\nexport function i18nCliPlugin(options: Required<I18nPluginOptions>): Plugin {\n const { defaultLocale, i18nAttribute, i18nAttributePrefix, placeholderPrefix, localesDirectory, supportedLocales } = options;\n\n return {\n name: \"i18n-cli-plugin\",\n\n cli(config) {\n const localesAutocompleteCommand = this.defineSubcommand({\n name: \"locales\",\n aliases: [\"i18n\"],\n meta: {\n description: \"Generate autocomplete for locales.\",\n },\n });\n\n localesAutocompleteCommand.onExecute(async () => {\n const root = resolve(config.root ?? process.cwd());\n\n const localesPath = isAbsolute(localesDirectory) ? normalize(localesDirectory) : join(root, localesDirectory);\n\n const localesData = getLocals({ localesPath, supportedLocales });\n\n // collect all possible keys\n const keys = Array.from(localesData.localesMap[defaultLocale].keys());\n\n const placeholders = new Set<string>();\n for (const locale in localesData.localesObj) {\n const placeholders = collectPlaceholders(localesData.localesObj[locale]);\n for (const placeholder of placeholders) {\n placeholders.add(placeholder);\n }\n }\n\n // html-data.json\n const htmlDataSavePath = join(localesPath, \"i18n.html-data.json\");\n\n const attributeValues = keys.map(key => ({ name: key }));\n const placeholderValues = keys.map(key => ({ name: `@${key}` }));\n\n const htmlDataString = JSON.stringify({\n version: 1.1,\n valueSets: [\n { name: \"i18n-keys\", values: attributeValues },\n { name: \"i18n-placeholder-keys\", values: placeholderValues },\n ],\n globalAttributes: [\n ...Array.from(placeholders, placeholder => ({\n name: placeholderPrefix + placeholder,\n description:\n `Replace the placeholder \\`${placeholder}\\` with a value.\\n\\n` +\n `Example: \\`\"Hi {{ ${placeholder}=DefaultValue }}\"\\` -> \\`<div ${placeholderPrefix + placeholder}=\"someValue\"></div>\\` \\n\\n` +\n `Or use an existing i18n value:\\n\\n\\`<div ${placeholderPrefix + placeholder}=\"@header.title\"></div>\\``,\n valueSet: \"i18n-placeholder-keys\",\n })),\n {\n name: i18nAttributePrefix + \"*\",\n description: `Insert i18n value for attribute. Example: \\`<div ${i18nAttributePrefix}aria-label=\"key\"></div>\\``,\n valueSet: \"i18n-keys\",\n },\n {\n name: i18nAttribute,\n description: `Insert i18n value for text content. Example: \\`<div ${i18nAttribute}=\"key\"></div>\\``,\n valueSet: \"i18n-keys\",\n },\n ],\n });\n\n const [formattedHtmlData, formattedHtmlDataError] = await formatCode(htmlDataString, localesPath, \"json\");\n if (formattedHtmlDataError) {\n Log.error(formattedHtmlDataError.message);\n return;\n }\n\n writeFileSync(htmlDataSavePath, formattedHtmlData);\n Log.success(`Generated html-data at \"${htmlDataSavePath}\"`);\n\n // types.d.ts\n const typesSavePath = join(localesPath, \"i18n.types.d.ts\");\n const typesString = generateTypes(keys, Array.from(placeholders), supportedLocales);\n\n const [formattedTypes, formattedTypesError] = await formatCode(typesString, typesSavePath, \"ts\");\n if (formattedTypesError) {\n Log.error(formattedTypesError.message);\n return;\n }\n\n writeFileSync(typesSavePath, formattedTypes ?? typesString);\n Log.success(`Generated types at \"${typesSavePath}\"`);\n });\n\n this.addCommand(localesAutocompleteCommand);\n },\n };\n}\n\nfunction generateTypes(keys: string[], placeholders: string[], langs: string[]) {\n interface NestedStringDictionary {\n [key: string]: string | NestedStringDictionary;\n }\n\n const result: NestedStringDictionary = {};\n\n for (const key of keys) {\n const parts = key.split(\".\");\n let current = result;\n\n for (let index = 0; index < parts.length; index++) {\n const part = parts[index];\n\n // last\n if (index === parts.length - 1) {\n current[part] = \"string\";\n continue;\n }\n\n // nested\n if (!Object.hasOwn(current, part)) {\n current[part] = {};\n }\n\n current = current[part] as NestedStringDictionary;\n }\n }\n\n const valuesType = JSON.stringify(result, null, 2).replace(/\"string\"/g, \"string\");\n const langsUnionType = langs.map(lang => `\"${lang}\"`).join(\" | \");\n const keysUnionType = keys.map(key => `\"${key}\"`).join(\" | \");\n const placeholderUnionType = placeholders.map(key => `\"${key}\"`).join(\" | \");\n\n const fileString = `declare global {\n type I18nLang = ${langsUnionType};\n type I18nKeysPath = ${keysUnionType};\n type I18nValuesRecord = ${valuesType};\n type I18nPlaceholder = ${placeholderUnionType}\n type I18nPlaceholderRecord = { [key in I18nPlaceholder]?: string };\n\n /** Replace a placeholder with a value. */\n const i18n_fill_template: (value: string, placeholdersObject?: I18nPlaceholderRecord) => string;\n\n /** Get all supported languages as an array. */\n const i18n_locales: () => I18nLang[];\n\n /** Get the default language. */\n const i18n_default_locale: () => I18nLang;\n\n /** Get the translation value for the given key and language. */\n const i18n_key_value: (key: I18nKeysPath, lang: I18nLang, placeholdersObject?: I18nPlaceholderRecord) => string;\n\n /** Get all translation values as a language-value record for the given key. */\n const i18n_key_values: (key: I18nKeysPath) => Record<I18nLang, string>;\n\n /** Get all translation values for the given language as a record. */\n const i18n_lang_values: (lang: I18nLang) => I18nValuesRecord;\n\n /** Get all translation values for all languages. */\n const i18n_all: () => Record<I18nLang, I18nValuesRecord>;\n}\n\nexport {};\n`;\n\n return fileString;\n}\n\ninterface RecursiveRecord {\n [key: string]: string | RecursiveRecord;\n}\n\nfunction collectPlaceholders(data: RecursiveRecord) {\n const result = new Set<string>();\n\n for (const key in data) {\n const value = data[key];\n\n if (typeof value === \"string\") {\n value.replace(propertyRe, (match: string, placeholder: string) => {\n result.add(placeholder);\n return match;\n });\n continue;\n }\n\n if (typeof value === \"object\" && !Array.isArray(value)) {\n for (const placeholder of collectPlaceholders(value)) result.add(placeholder);\n }\n }\n\n return result;\n}\n","import _generator from \"@babel/generator\";\nimport * as t from \"@babel/types\";\n\nimport type { NodePath } from \"@babel/traverse\";\n\nconst generator = typeof _generator === \"function\" ? _generator : _generator.default;\n\nexport type ResolveStaticValue =\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n | { value: Function | undefined; type: \"function\"; path: NodePath }\n | { value: string; type: \"string\"; path: NodePath }\n | { value: boolean; type: \"boolean\"; path: NodePath }\n | { value: number; type: \"number\"; path: NodePath }\n | { value: null; type: \"null\"; path: NodePath }\n | { value: ResolveStaticValue[]; type: \"array\"; path: NodePath }\n | { value: Record<string, unknown>; type: \"object\"; path: NodePath }\n | { value: undefined; type: \"undefined\"; path: NodePath };\n\n/** Get the value of an expression node */\nexport function resolveStaticValue(path: NodePath | null | undefined): ResolveStaticValue | undefined {\n if (!path) return;\n\n const node = path.node;\n\n if (t.isNullLiteral(node)) {\n return { value: null, type: \"null\", path };\n }\n\n if (t.isStringLiteral(node)) {\n return { value: node.value, type: \"string\", path };\n }\n\n if (t.isBooleanLiteral(node)) {\n return { value: node.value, type: \"boolean\", path };\n }\n\n if (t.isNumericLiteral(node)) {\n return { value: node.value, type: \"number\", path };\n }\n\n // BinaryExpression (like foo + bar) or ConditionalExpression (like foo ? bar : baz)\n if (t.isBinaryExpression(node) || t.isConditionalExpression(node)) {\n const evalResult = path.evaluate();\n if (!evalResult.confident) return;\n return { value: evalResult.value as unknown, type: typeof evalResult.value, path } as ResolveStaticValue;\n }\n\n if (t.isTemplateLiteral(node)) {\n let result = \"\";\n\n for (let index = 0; index < node.quasis.length; index++) {\n const staticPart = node.quasis[index].value.cooked ?? node.quasis[index].value.raw;\n result += staticPart;\n\n if (index < node.expressions.length) {\n const exp = node.expressions[index];\n if (!t.isExpression(exp)) continue;\n\n const expValue = resolveStaticValue(path.get(`expressions.${index}`));\n if (!expValue) continue;\n\n if (expValue.type === \"string\" || expValue.type === \"number\" || expValue.type === \"boolean\") {\n result += String(expValue.value);\n }\n }\n }\n\n return { value: result, type: \"string\", path };\n }\n\n if (t.isIdentifier(node)) {\n if (node.name === \"undefined\") return { value: undefined, type: \"undefined\", path };\n\n const binding = path.scope.getBinding(node.name);\n if (!binding || !binding.path.isVariableDeclarator()) return;\n\n const init = binding.path.node.init;\n if (!init) return;\n\n const initPath = binding.path.get(\"init\");\n return resolveStaticValue(initPath);\n }\n\n if (\n t.isArrowFunctionExpression(node) ||\n t.isFunctionExpression(node) ||\n t.isClassMethod(node) ||\n t.isClassPrivateMethod(node)\n ) {\n const parameters = node.params.map(parameter => (t.isIdentifier(parameter) ? parameter.name : \"\")).filter(Boolean);\n const isBlock = t.isBlockStatement(node.body);\n let bodyString = generator(node.body).code;\n\n bodyString = isBlock\n ? bodyString.slice(1, -1).trim() // remove `{` and `}`\n : \"return \" + bodyString; // arrow fn without block\n\n let function_;\n try {\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n function_ = new Function(...parameters, bodyString);\n } catch {\n // do nothing\n }\n\n return { value: function_, type: \"function\", path };\n }\n\n if (t.isObjectExpression(node)) {\n const value: Record<string, unknown> = {};\n\n for (let index = 0; index < node.properties.length; index++) {\n const property = node.properties[index];\n if (!t.isObjectProperty(property)) continue;\n\n const keyName = t.isStringLiteral(property.key)\n ? property.key.value\n : t.isIdentifier(property.key)\n ? property.key.name\n : null;\n if (!keyName) continue;\n\n const propertyValuePath = path.get(`properties.${index}.value`);\n const expValue = resolveStaticValue(propertyValuePath);\n\n if (expValue) value[keyName] = expValue.value;\n }\n\n return { value, type: \"object\", path };\n }\n\n if (t.isArrayExpression(node)) {\n const value = [];\n\n for (let index = 0; index < node.elements.length; index++) {\n const element = node.elements[index];\n if (!element) continue;\n\n const elementPath = path.get(`elements.${index}`);\n const elementValue = resolveStaticValue(elementPath);\n\n if (elementValue) value.push(elementValue);\n }\n\n return { value, type: \"array\", path };\n }\n\n // MemberExpression → object property or array index\n if (t.isMemberExpression(node)) {\n return resolveMemberExpression(path);\n }\n}\n\nfunction resolveMemberExpression(path: NodePath): ReturnType<typeof resolveStaticValue> {\n let current = path.node;\n let currentPath: NodePath | null = path;\n\n const parts = [];\n\n // Collect property names (e.g., [\"key\", \"nested\" , 0])\n while (t.isMemberExpression(current)) {\n const { property, computed } = current;\n\n let keyName;\n // Array index\n if (t.isNumericLiteral(property)) {\n keyName = property.value;\n }\n\n // Property name as identifier. e.g., object.key\n if (!computed && t.isIdentifier(property)) {\n keyName = property.name;\n }\n\n // Class private property name as identifier. e.g., this.#key\n if (!computed && t.isPrivateName(property)) {\n keyName = \"#\" + property.id.name;\n }\n\n // Property name as string. e.g., object[\"key\"]\n if (computed && t.isStringLiteral(property)) {\n keyName = property.value;\n }\n\n // Property name as a computed identifier (variable). e.g., object[computedKey]\n if (computed && t.isIdentifier(property)) {\n const propertyValue = resolveStaticValue(currentPath.get(\"property\"));\n keyName = typeof propertyValue === \"string\" || typeof propertyValue === \"number\" ? propertyValue : undefined;\n }\n\n if (keyName !== undefined) {\n parts.unshift(keyName);\n }\n\n current = current.object;\n currentPath = currentPath.get(\"object\");\n }\n\n // accessing a variable. e.g., object.key\n if (t.isIdentifier(current)) {\n const binding = path.scope.getBinding(current.name);\n if (!binding) return;\n\n if (t.isVariableDeclarator(binding.path.node)) {\n currentPath = binding.path.get(\"init\");\n } else if (t.isClassDeclaration(binding.path.node)) {\n currentPath = binding.path; // class static property\n } else return;\n } else if (t.isThisExpression(current)) {\n // accessing `this.key`.\n const classPath = path.find(p => p.isClassDeclaration() || p.isClassExpression());\n if (!classPath) return;\n currentPath = classPath;\n }\n\n if (!currentPath) return;\n\n // Traverse the object properties\n for (const part of parts) {\n const expression: t.Node | null | undefined = currentPath.node;\n\n // plain object\n if (t.isObjectExpression(expression)) {\n if (typeof part !== \"string\") continue;\n const propertyIndex = expression.properties.findIndex(\n property_ =>\n (t.isObjectProperty(property_) && t.isIdentifier(property_.key, { name: part })) ||\n (t.isObjectProperty(property_) && t.isStringLiteral(property_.key, { value: part }))\n );\n if (propertyIndex === -1) continue;\n\n const property = expression.properties[propertyIndex] as t.ObjectProperty;\n if (!property) continue;\n\n currentPath = currentPath.get(`properties.${propertyIndex}.value`);\n continue;\n }\n\n // array\n if (t.isArrayExpression(expression)) {\n if (typeof part !== \"number\") continue;\n const element = expression.elements[part];\n if (!element) continue;\n\n currentPath = currentPath.get(`elements.${part}`);\n continue;\n }\n\n // class\n if (t.isClassExpression(expression) || t.isClassDeclaration(expression)) {\n if (typeof part !== \"string\") continue;\n\n const valuePath = getClassPropertyValue(currentPath, part);\n if (!valuePath) return;\n\n currentPath = valuePath;\n }\n }\n\n if (!currentPath) return;\n\n return resolveStaticValue(currentPath);\n}\n\nfunction getClassPropertyValue(classPath: NodePath, propertyName: string): NodePath | undefined {\n if (!classPath.isClassDeclaration() && !classPath.isClassExpression()) return;\n\n const classBody = classPath.node.body.body;\n\n for (const [index, node] of classBody.entries()) {\n // ? If a property has both a class field initializer and an assignment in the constructor,\n // ? the initializer value takes precedence if it appears first.\n\n // Case: Constructor assignments (this.prop = ...)\n if (t.isClassMethod(node, { kind: \"constructor\" })) {\n const body = node.body.body;\n for (const [index_, bodyNode] of body.entries()) {\n if (!t.isExpressionStatement(bodyNode) || !t.isAssignmentExpression(bodyNode.expression)) continue;\n\n const { left } = bodyNode.expression;\n if (!t.isMemberExpression(left) || !t.isThisExpression(left.object)) continue;\n\n // check property name\n if (t.isIdentifier(left.property) && left.property.name !== propertyName) continue;\n if (t.isPrivateName(left.property) && left.property.id.name !== propertyName) continue;\n\n return classPath.get(`body.body.${index}.body.body.${index_}.expression.right`);\n }\n }\n\n // Case: Public/Private class field that has a value.\n if (t.isClassProperty(node) || t.isClassPrivateProperty(node)) {\n if (t.isIdentifier(node.key, { name: propertyName }) && node.value) {\n return classPath.get(`body.body.${index}.value`);\n }\n\n if (t.isPrivateName(node.key) && `#${node.key.id.name}` === propertyName && node.value) {\n return classPath.get(`body.body.${index}.value`);\n }\n\n if (t.isStringLiteral(node.key, { value: propertyName }) && node.value) {\n return classPath.get(`body.body.${index}.value`);\n }\n }\n\n // Case: Public/Private get method\n if (\n (t.isClassMethod(node, { kind: \"get\" }) && t.isIdentifier(node.key, { name: propertyName })) ||\n (t.isClassPrivateMethod(node, { kind: \"get\" }) && `#${node.key.id.name}` === propertyName)\n ) {\n for (let index_ = 0; index_ < node.body.body.length; index_++) {\n const bodyNode = node.body.body[index_];\n if (bodyNode.type !== \"ReturnStatement\") continue;\n if (!bodyNode.argument) return;\n\n if (t.isTSAsExpression(bodyNode.argument)) {\n return classPath.get(`body.body.${index.toString()}.body.body.${index_.toString()}.argument.expression`);\n }\n\n return classPath.get(`body.body.${index.toString()}.body.body.${index_.toString()}.argument`);\n }\n }\n }\n}\n","import _traverse from \"@babel/traverse\";\nimport * as t from \"@babel/types\";\n\nimport { resolveStaticValue } from \"../../ast-utilities/babel-utils/resolve-static-value.ts\";\nimport { filterScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { isAbsolute, join, normalize } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { getLocals } from \"./get-locales.ts\";\nimport { propertyRe } from \"./i18n-html-plugin.ts\";\n\nimport type { I18nPluginOptions } from \"./i18n-plugin.ts\";\nimport type { Plugin } from \"@staticbolt/core\";\n\nconst traverse = typeof _traverse === \"function\" ? _traverse : _traverse.default;\n\n/**\n * The script half of i18nPlugin: replaces the \"i18n_*\" helper calls in JavaScript with the values they resolve to, so no\n * translation machinery is left at runtime.\n *\n * - \"i18n_locales()\" and \"i18n_default_locale()\": the supported locales and the default one.\n * - \"i18n_key_value(key, lang, placeholders?)\" and \"i18n_key_values(key)\": one translation, or that key across every locale.\n * - \"i18n_lang_values(lang)\" and \"i18n_all()\": whole translation objects.\n * - \"i18n_fill_template(value, placeholders?)\": fills the \"{{ name=fallback }}\" placeholders of a string.\n *\n * Notes:\n *\n * - Arguments have to be statically resolvable strings or plain objects. Anything dynamic is reported and the call is left in the\n * code, where it will fail at runtime.\n * - Declarations for these helpers come from the \"locales\" CLI command, see i18nCliPlugin.\n * - The active locale is not one of them; read it at runtime from \"document.documentElement.lang\".\n */\nexport function i18nScriptPlugin(options: Required<I18nPluginOptions>): Plugin {\n const { defaultLocale, localesDirectory, supportedLocales } = options;\n\n const printFmtError = PrintFormattedError.create({ function: i18nScriptPlugin });\n\n return {\n name: \"i18n-script-plugin\",\n\n transform(inputMetadata) {\n const localesPath = isAbsolute(localesDirectory) ? normalize(localesDirectory) : join(this.root, localesDirectory);\n\n const locales = getLocals({ localesPath, supportedLocales });\n const langs = Object.keys(locales.localesMap);\n\n for (const { metadata } of filterScriptMetadata(inputMetadata)) {\n traverse(metadata.ast, {\n CallExpression(path) {\n if (!t.isIdentifier(path.node.callee)) return;\n const filePath = metadata.id;\n\n const node = path.node;\n\n if (path.node.callee.name === \"i18n_fill_template\") {\n const firstArgumentValue = resolveStaticValue(path.get(\"arguments.0\"));\n if (!firstArgumentValue || firstArgumentValue.type !== \"string\") {\n printFmtError(\"The first argument of `i18n_fill_template` should be a string\", { node, filePath });\n return;\n }\n\n const secondArgumentValue = resolveStaticValue(path.get(\"arguments.1\"));\n if (secondArgumentValue && secondArgumentValue.type !== \"object\") {\n printFmtError(\"The second argument of `i18n_fill_template` should be a plain object\", {\n node,\n filePath,\n });\n return;\n }\n\n const fillValues = secondArgumentValue?.value ?? {};\n const replacer = (_match: string, variableName: string, defaultValue: string | undefined) => {\n if (Object.hasOwn(fillValues, variableName)) {\n const value_ = fillValues[variableName];\n if (typeof value_ === \"string\") return value_;\n }\n if (defaultValue !== undefined) return defaultValue;\n return \"\";\n };\n\n // eslint-disable-next-line unicorn/no-unsafe-string-replacement\n const value = firstArgumentValue.value.replace(propertyRe, replacer);\n\n path.replaceWith(t.stringLiteral(value));\n return;\n }\n\n if (path.node.callee.name === \"i18n_locales\") {\n path.replaceWith(t.arrayExpression(langs.map(lang => t.stringLiteral(lang))));\n return;\n }\n\n if (path.node.callee.name === \"i18n_default_locale\") {\n path.replaceWith(t.stringLiteral(defaultLocale));\n return;\n }\n\n if (path.node.callee.name === \"i18n_all\") {\n path.replaceWith(buildObjectExpression(locales.localesObj));\n return;\n }\n\n if (path.node.callee.name === \"i18n_lang_values\") {\n const firstArgumentValue = resolveStaticValue(path.get(\"arguments.0\"));\n if (!firstArgumentValue || firstArgumentValue.type !== \"string\") {\n printFmtError(\"The first argument of `i18n_lang_values` should be a string\", { node, filePath });\n return;\n }\n const lang = firstArgumentValue.value;\n\n if (!langs.includes(lang)) {\n printFmtError(`The first argument of \"i18n_lang_values\" should be one of`, langs.join(\", \"), {\n node,\n filePath,\n });\n return;\n }\n\n const object = locales.localesObj[lang];\n if (!object) return;\n\n path.replaceWith(buildObjectExpression(object));\n return;\n }\n\n if (path.node.callee.name === \"i18n_key_value\") {\n const firstArgumentValue = resolveStaticValue(path.get(\"arguments.0\"));\n if (!firstArgumentValue || firstArgumentValue.type !== \"string\") {\n printFmtError(\"The first argument of `i18n_key_value` should be a string\", { node, filePath });\n return;\n }\n const keysPath = firstArgumentValue.value;\n\n const secondeArgumentValue = resolveStaticValue(path.get(\"arguments.1\"));\n if (!secondeArgumentValue || secondeArgumentValue.type !== \"string\") {\n printFmtError(\"The second argument of `i18n_key_value` should be a string\", { node, filePath });\n return;\n }\n const lang = secondeArgumentValue.value;\n\n if (!langs.includes(lang)) {\n printFmtError(`The first argument of \"i18n_lang_values\" should be one of`, langs.join(\", \"), {\n node,\n filePath,\n });\n return;\n }\n\n if (!locales.getKey(keysPath, lang)) {\n printFmtError(\"The first argument of `i18n_key_value` should be a valid key path\", { node, filePath });\n return;\n }\n\n const thirdArgumentValue = resolveStaticValue(path.get(\"arguments.2\"));\n if (thirdArgumentValue && thirdArgumentValue.type !== \"object\") {\n printFmtError(\"The third argument of `i18n_key_value` should be an optional plain object\", {\n node,\n filePath,\n });\n return;\n }\n const fillValues = thirdArgumentValue?.value ?? {};\n\n const replacer = (_match: string, variableName: string, defaultValue: string | undefined) => {\n if (Object.hasOwn(fillValues, variableName)) {\n const value_ = fillValues[variableName];\n if (typeof value_ === \"string\") return value_;\n }\n if (defaultValue !== undefined) return defaultValue;\n return \"\";\n };\n\n // eslint-disable-next-line unicorn/no-unsafe-string-replacement\n const value = locales.getKey(keysPath, lang).replace(propertyRe, replacer);\n\n path.replaceWith(t.stringLiteral(value));\n return;\n }\n\n if (path.node.callee.name === \"i18n_key_values\") {\n const firstArgumentValue = resolveStaticValue(path.get(\"arguments.0\"));\n if (!firstArgumentValue || firstArgumentValue.type !== \"string\") {\n printFmtError(\"The first argument of `i18n_key_values` should be a string\", { node, filePath });\n return;\n }\n const keysPath = firstArgumentValue.value;\n\n const langValueEntries = langs.map(lang => [lang, locales.getKey(keysPath, lang)]);\n\n path.replaceWith(\n t.objectExpression(\n langValueEntries.map(([lang, value]) => t.objectProperty(t.stringLiteral(lang), t.stringLiteral(value)))\n )\n );\n return;\n }\n },\n });\n }\n },\n };\n}\n\ninterface RecursiveRecord {\n [key: string]: string | RecursiveRecord;\n}\n\nfunction buildObjectExpression(object: RecursiveRecord): t.ObjectExpression {\n return t.objectExpression(\n Object.entries(object).map(([key, value]) =>\n t.objectProperty(t.stringLiteral(key), typeof value === \"string\" ? t.stringLiteral(value) : buildObjectExpression(value))\n )\n );\n}\n","import { i18nCliPlugin } from \"./i18n-cli-plugin.ts\";\nimport { i18nHtmlPlugin } from \"./i18n-html-plugin.ts\";\nimport { i18nScriptPlugin } from \"./i18n-script-plugin.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface I18nPluginOptions {\n /**\n * The default locale.\n *\n * @default \"en\"\n */\n defaultLocale?: string;\n\n /**\n * The supported locales.\n *\n * @default [\"en\"]\n */\n supportedLocales?: string[];\n\n /**\n * The path to the locales directory.\n *\n * @default \"./sources/locales\"\n */\n localesDirectory?: string;\n\n /**\n * The name of the i18n attribute.\n *\n * @default \"i18n\"\n */\n i18nAttribute?: string;\n\n /**\n * The prefix to use for i18n attributes.\n *\n * @default \"i18n-attr-\"\n */\n i18nAttributePrefix?: string;\n\n /**\n * The prefix to use for i18n attributes.\n *\n * @default \"i18n-placeholder-\"\n */\n placeholderPrefix?: string;\n}\n\n/**\n * Adds internationalization: every page is emitted once per locale with its translation markers resolved, and scripts get a set\n * of compile-time helpers. Returns the three plugins that do the work (HTML, scripts, CLI) sharing the same resolved options.\n *\n * Translations live in one JSON file per locale inside \"localesDirectory\" (\"en.json\", \"ar.json\", ...). Nested objects turn into\n * dot-notated keys, and values can carry \"{{ name=fallback }}\" placeholders.\n *\n * Notes:\n *\n * - The default locale is emitted at the original paths; the others go under a directory named after the locale.\n * - Locale files are read once and cached for the whole process, so a running dev server does not pick up edits to them.\n */\nexport function i18nPlugin(options: I18nPluginOptions = {}): Plugin[] {\n const requiredOptions: Required<I18nPluginOptions> = {\n defaultLocale: options.defaultLocale ?? \"en\",\n supportedLocales: options.supportedLocales ?? [\"en\"],\n localesDirectory: options.localesDirectory ?? \"./sources/locales\",\n placeholderPrefix: options.placeholderPrefix ?? \"i18n-placeholder-\",\n i18nAttribute: options.i18nAttribute ?? \"i18n\",\n i18nAttributePrefix: options.i18nAttributePrefix ?? \"i18n-attr-\",\n };\n\n return [i18nCliPlugin(requiredOptions), i18nHtmlPlugin(requiredOptions), i18nScriptPlugin(requiredOptions)];\n}\n","import * as t from \"@babel/types\";\n\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\n\nimport type { ImportAsStringOptions } from \"./types.ts\";\nimport type { BabelAst } from \"@staticbolt/core\";\n\ninterface Options {\n ast: BabelAst;\n filePath: string;\n}\n\ninterface ParseImportAsStringResult {\n get source(): string;\n set source(newValue: string);\n replaceWith: (newValue: string) => void;\n options: ImportAsStringOptions;\n}\n\nexport function parseImportAsString({ ast, filePath }: Options): ParseImportAsStringResult[] {\n const result: ParseImportAsStringResult[] = [];\n\n const printFmtError = PrintFormattedError.create({ function: parseImportAsString, filePath });\n\n t.traverse(ast, {\n enter(node, ancestors) {\n if (!t.isCallExpression(node)) return;\n if (!t.isIdentifier(node.callee)) return;\n if (node.callee.name !== \"import_as_string\") return;\n\n const firstArgument = node.arguments[0];\n\n const source = resolveStaticValue(firstArgument);\n if (typeof source !== \"string\") {\n printFmtError(\"The first argument of `import_as_string` should be a string\", { node });\n return;\n }\n\n const optionsObject: Required<ImportAsStringOptions> = {\n templateLiteral: false,\n process: true,\n minify: false,\n format: false,\n };\n\n const secondeArgument = node.arguments[1];\n const secondeArgumentValue = resolveStaticValue(secondeArgument);\n\n if (isPlainObject(secondeArgumentValue)) {\n const entries = Object.entries(secondeArgumentValue) as [keyof ImportAsStringOptions, unknown][];\n\n for (const [key, value] of entries) {\n if (!Object.hasOwn(optionsObject, key)) {\n printFmtError(\"Unknown option of `import_as_string`\", { node });\n continue;\n }\n\n const expectedType = typeof optionsObject[key];\n const actualType = typeof value;\n\n if (actualType !== expectedType) {\n printFmtError(`The '${key}' option should be an optional`, expectedType, { node });\n continue;\n }\n\n optionsObject[key] = value as never;\n }\n }\n\n const capturedAncestor = ancestors.at(-1);\n if (!capturedAncestor) {\n printFmtError(\"Internal error. Couldn't find ancestor\", { node });\n return;\n }\n\n const parentNode = capturedAncestor.node;\n\n const replaceWith = (newValue: string) => {\n const newNode = optionsObject.templateLiteral ? buildTemplateLiteral(newValue) : t.stringLiteral(newValue);\n\n if (capturedAncestor.index === undefined) {\n // @ts-expect-error so many wrong types\n parentNode[capturedAncestor.key] = newNode;\n return;\n }\n\n // @ts-expect-error so many wrong types\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n parentNode[capturedAncestor.key][capturedAncestor.index] = newNode;\n };\n\n result.push({\n get source() {\n return source;\n },\n set source(newValue) {\n node.arguments[0] = t.stringLiteral(newValue);\n },\n replaceWith,\n options: optionsObject,\n });\n },\n });\n\n return result;\n}\n\n/** Builds a template literal holding the value, escaping what would otherwise break out of it. */\nfunction buildTemplateLiteral(value: string): t.TemplateLiteral {\n const escaped = value\n .replace(/\\\\/g, String.raw`\\\\`)\n .replace(/`/g, String.raw`\\``)\n .replace(/\\$\\{/g, String.raw`\\${`);\n\n return t.templateLiteral([t.templateElement({ raw: escaped, cooked: value }, true)], []);\n}\n\nfunction resolveStaticValue(node: t.Node): unknown {\n if (t.isNullLiteral(node)) {\n return null;\n }\n\n if (t.isStringLiteral(node)) {\n return node.value;\n }\n\n if (t.isBooleanLiteral(node)) {\n return node.value;\n }\n\n if (t.isNumericLiteral(node)) {\n return node.value;\n }\n\n if (t.isTemplateLiteral(node)) {\n let result = \"\";\n\n for (let index = 0; index < node.quasis.length; index++) {\n const staticPart = node.quasis[index].value.cooked ?? node.quasis[index].value.raw;\n result += staticPart;\n\n if (index < node.expressions.length) {\n const exp = node.expressions[index];\n if (!t.isExpression(exp)) continue;\n\n const expValue = resolveStaticValue(exp);\n if (!expValue) continue;\n\n if (typeof expValue === \"string\" || typeof expValue === \"number\" || typeof expValue === \"boolean\") {\n result += String(expValue);\n }\n }\n }\n\n return result;\n }\n\n if (t.isObjectExpression(node)) {\n const value: Record<string, unknown> = {};\n\n for (let index = 0; index < node.properties.length; index++) {\n const property = node.properties[index];\n if (!t.isObjectProperty(property)) continue;\n\n const keyName = t.isStringLiteral(property.key)\n ? property.key.value\n : t.isIdentifier(property.key)\n ? property.key.name\n : null;\n if (!keyName) continue;\n\n const expValue = resolveStaticValue(property.value);\n\n if (expValue) {\n value[keyName] = expValue;\n }\n }\n\n return value;\n }\n\n if (t.isArrayExpression(node)) {\n const value = [];\n\n for (let index = 0; index < node.elements.length; index++) {\n const element = node.elements[index];\n if (!element) continue;\n\n const elementValue = resolveStaticValue(element);\n\n if (elementValue) {\n value.push(elementValue);\n }\n }\n\n return value;\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { DependencyTracker } from \"../../helpers/dependency-tracker.ts\";\nimport { filterScriptMetadata, isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { printFmtError } from \"../../utilities/print-formatted-error.ts\";\nimport { safeReadFileSync } from \"../../utilities/read-file.ts\";\nimport { parseImportAsString } from \"./parse-import-as-string.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\n/**\n * Replaces \"import_as_string(path, options?)\" calls in scripts with the contents of that file, inlined as a string literal at\n * build time.\n *\n * By default the file is taken from the build, so what lands in the string is the processed version, and \"minify\" and \"format\"\n * control how it is printed. With \"process: false\" the file is read straight from disk instead, untouched, and with\n * \"templateLiteral: true\" the value is inlined as a template literal rather than a quoted string.\n *\n * Notes:\n *\n * - The path and the options object have to be statically resolvable; anything dynamic is reported and the call is left in the\n * code, where it will fail at runtime.\n * - The path is resolved relative to the file doing the importing.\n * - \"minify\" and \"format\" only apply in production; in development the file is inlined as it is.\n * - An inlined file is dropped from the output unless it is an entry point in its own right.\n * - Editing an inlined file recompiles the scripts that inline it.\n */\nexport function importAsStringPlugin(): Plugin {\n const dependencies = new DependencyTracker();\n\n return {\n name: \"import-as-string\",\n\n sourcesProvider(metadata) {\n if (!isScriptMetadata(metadata)) return;\n\n return parseImportAsString({ ast: metadata.ast, filePath: metadata.filePath });\n },\n\n onFileEvent(event, id) {\n if (event === \"unlink\") {\n dependencies.delete(id);\n }\n },\n\n resolveCompileList(compileSet, event) {\n if (event !== \"change\") return;\n\n for (const id of Array.from(compileSet)) {\n const importers = dependencies.getImporters(id);\n\n for (const importer of importers) {\n compileSet.add(importer);\n }\n }\n },\n\n async transform(inputMetadata) {\n for (const { metadata } of filterScriptMetadata(inputMetadata)) {\n const currentSources = new Set<string>();\n\n const sources = parseImportAsString({ ast: metadata.ast, filePath: metadata.filePath });\n\n for (const { source, replaceWith, options } of sources) {\n const sourceRelative = join(dirname(metadata.filePath), source);\n\n // Inline as normal string\n if (!options.process) {\n const sourceAbs = join(this.root, sourceRelative);\n const [fileContent, fileContentError] = safeReadFileSync(sourceAbs, \"utf8\");\n if (fileContentError) {\n printFmtError(fileContentError, { function: importAsStringPlugin, filePath: metadata.id });\n continue;\n }\n\n currentSources.add(sourceRelative);\n\n replaceWith(fileContent);\n\n continue;\n }\n\n const sourceMetadata = this.findMetadata({ filePath: sourceRelative });\n if (!sourceMetadata) {\n this.log.error(`Failed to find metadata for \"${sourceRelative}\" found in \"${metadata.filePath}\"`);\n continue;\n }\n\n currentSources.add(sourceRelative);\n\n const format = this.production ? options.format : false;\n const minify = this.production ? options.minify : false;\n\n const metadataString = await this.stringify(sourceMetadata, { format, minify });\n if (typeof metadataString !== \"string\") {\n printFmtError(\"Failed to stringify metadata\", { function: importAsStringPlugin, filePath: metadata.id });\n continue;\n }\n\n if (!this.entryPoints.has(sourceMetadata.id)) {\n this.emitExclude.add(sourceMetadata);\n }\n\n replaceWith(metadataString);\n }\n\n dependencies.update(metadata.id, currentSources);\n }\n },\n };\n}\n\nexport type { ImportAsStringOptions, import_as_string } from \"./types.ts\";\n","import { globSync } from \"glob\";\n\nimport { isPathMatch, normalize } from \"../../utilities/path.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface LoadSourcesPluginOptions {\n include: string[];\n exclude?: string[];\n}\n\n/**\n * Registers the files matched by \"include\" as entry points: the roots the build starts from, with everything they reference\n * discovered, transformed and emitted along with them.\n *\n * Notes:\n *\n * - Patterns are matched from the project root at startup, and matching nothing is reported as an error.\n * - Matched files are watched, so creating or deleting one updates the entry point set without a restart.\n * - Any file type staticbolt can load works as an entry point, HTML, markdown, scripts and styles alike.\n */\nexport function loadSourcesPlugin(options: LoadSourcesPluginOptions): Plugin {\n const ignore = options.exclude ?? [];\n\n return {\n name: \"load-sources\",\n\n setup() {\n const entryFiles = globSync(options.include, { ignore, cwd: this.root, nodir: true });\n\n if (entryFiles.length === 0) {\n this.log.error(`No files found matching`, options.include.join(\", \"));\n return;\n }\n\n for (const entryFile of entryFiles) {\n const normalized = normalize(entryFile);\n this.entryPoints.add(normalized);\n this.watcher?.add(normalized);\n }\n },\n\n onFileEvent(event, id) {\n if (event === \"change\") return;\n\n const isIncluded = isPathMatch(id, { include: options.include, ignore, root: this.root });\n if (!isIncluded) return;\n\n if (event === \"unlink\") {\n this.entryPoints.delete(id);\n this.watcher?.unwatch(id);\n return;\n }\n\n this.entryPoints.add(id);\n this.watcher?.add(id);\n },\n };\n}\n","import { mkdirSync, writeFileSync } from \"node:fs\";\n\nimport { dirname, join } from \"../../utilities/path.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface RobotsTextOptions {\n /**\n * Generate `robots.txt`.\n *\n * @default [ ]\n */\n rules?: {\n userAgent: string;\n allow?: string[];\n disallow?: string[];\n }[];\n\n /**\n * The output file path relative to output directory.\n *\n * @default \"robots.txt\"\n */\n outfile?: string;\n\n /** The path to the sitemap file. */\n sitemapUrl?: string;\n}\n\n/**\n * Writes a \"robots.txt\" into the output directory from the rules given in the options.\n *\n * Notes:\n *\n * - Production only, and only when at least one rule is configured; with an empty \"rules\" list nothing is written.\n * - Every rule becomes a \"User-agent\" block followed by its \"Allow\" and \"Disallow\" lines, in the order they are listed.\n * - \"sitemapUrl\" appends a \"Sitemap:\" line as given, so pass the full URL.\n * - The file is written straight to disk after the build and is not part of the build graph.\n */\nexport function robotsTextPlugin(options: RobotsTextOptions = {}): Plugin {\n const rules = options.rules ?? [];\n const outFile = options.outfile ?? \"robots.txt\";\n\n return {\n name: \"robots-text\",\n\n postBuild() {\n if (!this.production || rules.length === 0) return;\n\n const lines = [];\n for (const rule of rules) {\n const userAgent = rule.userAgent ?? \"*\";\n lines.push(`User-agent: ${userAgent}`);\n\n if (rule.allow) for (const path of rule.allow) lines.push(`Allow: ${path}`);\n if (rule.disallow) for (const path of rule.disallow) lines.push(`Disallow: ${path}`);\n\n lines.push(\"\");\n }\n\n if (options.sitemapUrl) {\n lines.push(`Sitemap: ${options.sitemapUrl}`);\n }\n\n const outputFile = join(this.outdir, outFile);\n mkdirSync(dirname(outputFile), { recursive: true });\n writeFileSync(outputFile, lines.join(\"\\n\"), \"utf8\");\n },\n };\n}\n","import c from \"chalk\";\n\nimport { join } from \"../../utilities/path.ts\";\nimport { humanReadableBytes } from \"../../utilities/utilities.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface ServiceWorkerOptions {\n /**\n * Glob patterns for matching files.\n *\n * @default [\"**\\/*.{js,wasm,css,html}\"]\n */\n globPatterns?: string[];\n\n /**\n * Glob patterns for files to ignore.\n *\n * @default [\"**\\/node_modules\\/**\\/*\"]\n */\n globIgnores?: string[];\n\n /**\n * Whether to follow symbolic links when matching glob patterns.\n *\n * @default true\n */\n globFollow?: boolean;\n\n /**\n * Enforces strict mode for glob patterns.\n *\n * @default true\n */\n globStrict?: boolean;\n\n /**\n * Destination file for the generated service worker relative to the output directory.\n *\n * @default \"sw.js\"\n */\n swDest?: string;\n\n /**\n * Determines whether source maps should be generated.\n *\n * @default false\n */\n sourcemap?: boolean;\n\n /**\n * Whether to skip waiting and immediately activate the service worker.\n *\n * @default false\n */\n skipWaiting?: boolean;\n\n /**\n * Whether the service worker should claim all available clients.\n *\n * @default false\n */\n clientsClaim?: boolean;\n\n /**\n * Whether to inline the Workbox runtime.\n *\n * @default false\n */\n inlineWorkboxRuntime?: boolean;\n\n /**\n * Cleans up outdated caches during service worker activation.\n *\n * @default false\n */\n cleanupOutdatedCaches?: boolean;\n\n /**\n * Enables offline Google Analytics support.\n *\n * @default false\n */\n offlineGoogleAnalytics?: boolean;\n\n /** Cache ID used for versioning. */\n cacheId?: string;\n\n /** The default directory index for cached URLs. */\n directoryIndex?: string;\n\n /**\n * Maximum file size (in bytes) to cache.\n *\n * @default 2097152\n */\n maximumFileSizeToCacheInBytes?: number;\n\n /** Modifies URL prefixes for cached assets. */\n modifyURLPrefix?: Record<string, string>;\n}\n\n/**\n * Generates a Workbox service worker from the finished output directory, precaching every file that matches \"globPatterns\".\n *\n * The options are handed to workbox-build's \"generateSW\", with \"swDest\" resolved inside the output directory and the project's\n * browserslist used as the Babel target.\n *\n * Registering it is up to the page:\n *\n * ```ts\n * import { Workbox } from \"workbox-window\";\n *\n * if (\"serviceWorker\" in navigator && _production) {\n * const wb = new Workbox(\"/sw.js\");\n * wb.register();\n * }\n * ```\n *\n * Notes:\n *\n * - Production only, and it runs after the build, so it sees the final files, copied assets included.\n * - The precache manifest is built from the output directory; files larger than \"maximumFileSizeToCacheInBytes\" (2 MB by default)\n * are left out.\n * - The worker is written straight to disk and is not part of the build graph.\n */\nexport function serviceWorkerPlugin(options: ServiceWorkerOptions = {}): Plugin {\n return {\n name: \"service-worker\",\n\n async postBuild() {\n if (!this.production) return;\n\n this.log.info(\"Generating a service worker...\");\n\n const outdir = this.outdir;\n\n options.swDest = join(outdir, options.swDest ?? \"sw.js\");\n\n const { generateSW } = await import(\"workbox-build\");\n\n const { count, size, warnings } = await generateSW({\n globDirectory: outdir,\n babelPresetEnvTargets: this.browserslist,\n ...(options as Required<ServiceWorkerOptions>),\n });\n\n if (warnings.length > 0) {\n this.log.warn(\"Warnings encountered while generating a service worker:\\n >\", warnings.join(c.yellow(\"\\n > \")), \"\\n\");\n }\n\n this.log.info(\n \"Generated a service worker, which will precache\",\n c.yellow(count),\n \"files, totaling\",\n c.yellow(humanReadableBytes(size))\n );\n },\n };\n}\n","import { writeFileSync } from \"node:fs\";\nimport { globSync } from \"glob\";\n\nimport { dirname, join } from \"../../utilities/path.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface SitemapOptions {\n /** The URL of the sitemap. */\n sitemapUrl?: string;\n\n /**\n * The output sitemap file path relative to the output directory.\n *\n * @default \"sitemap.xml\"\n */\n outfile?: string;\n\n /**\n * Glob patterns to match HTML files to include in the sitemap.\n *\n * **NOTE**: This is relative to the output directory.\n *\n * @default [\"**\\/*.html\"]\n */\n include?: string[];\n\n /**\n * Glob patterns to ignore HTML files from the sitemap.\n *\n * **NOTE**: This is relative to the output directory.\n *\n * @default [ ]\n */\n exclude?: string[];\n}\n\n/**\n * Writes a \"sitemap.xml\" listing the HTML pages that ended up in the output directory.\n *\n * Notes:\n *\n * - Production only, and only when \"sitemapUrl\" is set; without it nothing is generated.\n * - The pages are globbed from the output directory after the build, so the list reflects what was really emitted, and \"include\"\n * and \"exclude\" are matched there as well.\n * - Each entry is the URL of the file's directory with a trailing slash: \"blog/post/index.html\" becomes \".../blog/post/\", and a\n * page that is not an \"index.html\" collapses onto the URL of its parent directory.\n * - Only \"<loc>\" is emitted, no \"lastmod\", \"changefreq\" or \"priority\".\n */\nexport function sitemapPlugin(options: SitemapOptions = {}): Plugin {\n const include = options.include ?? [\"**/*.html\"];\n const ignore = options.exclude ?? [];\n const outfile = options.outfile ?? \"sitemap.xml\";\n\n return {\n name: \"sitemap\",\n\n postBuild() {\n if (!this.production || !options.sitemapUrl) return;\n\n this.log.info(\"Generating sitemap...\");\n\n const sitemapPath = join(this.outdir, outfile);\n\n const htmlFiles = globSync(include, { ignore, cwd: this.outdir });\n\n const urls: string[] = [];\n\n for (const file of htmlFiles) {\n const fullRoute = new URL(dirname(file), options.sitemapUrl).href;\n\n let url = \" <url>\\n\";\n url += ` <loc>${fullRoute.endsWith(\"/\") ? fullRoute : fullRoute + \"/\"}</loc>\\n`;\n url += \" </url>\\n\";\n\n urls.push(url);\n }\n\n const sitemapContent =\n '\\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' +\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\\n' +\n ' xmlns:news=\"http://www.google.com/schemas/sitemap-news/0.9\"\\n' +\n ' xmlns:xhtml=\"http://www.w3.org/1999/xhtml\"\\n' +\n ' xmlns:image=\"http://www.google.com/schemas/sitemap-image/1.1\"\\n' +\n ' xmlns:video=\"http://www.google.com/schemas/sitemap-video/1.1\">\\n' +\n urls.join(\"\") +\n \"</urlset>\";\n\n writeFileSync(sitemapPath, sitemapContent.trim(), \"utf8\");\n },\n };\n}\n","import { valueOrError } from \"../../utilities/value-or-error.ts\";\n\nimport type { Config } from \"svgo\";\n\nasync function optimizeSvgUnsafe(svgCode: string, config?: Config) {\n const { optimize } = await import(\"svgo\");\n\n const result = optimize(svgCode, config);\n return result.data;\n}\n\n/** - Takes SVG string and return an optimized SVG string */\nconst optimizeSvg = valueOrError(optimizeSvgUnsafe);\n\nexport { optimizeSvg };\n","import { mkdirSync, writeFileSync } from \"node:fs\";\nimport { globSync } from \"glob\";\n\nimport { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { safeReadFileSync } from \"../../utilities/read-file.ts\";\nimport { optimizeSvg } from \"./svgo-optimize.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\nimport type { Config } from \"svgo\";\n\nexport interface svgoOptions {\n /**\n * Include SVG files to optimize and write to output directory.\n *\n * @default [\"sources/assets/**\\/*.svg\"]\n */\n include?: string[];\n\n /**\n * Ignore and exclude SVG files from optimization.\n *\n * @default [ ]\n */\n exclude?: string[];\n\n /**\n * Whether to optimize SVG tags in HTML.\n *\n * @default true\n */\n optimizeInHtml?: boolean;\n\n /** SVGO configuration. */\n svgoConfig?: Config;\n}\n\n/**\n * Optimizes SVGs with svgo, both the inline \"<svg>\" tags of a page and the files matched by \"include\", which are optimized and\n * written to the output directory.\n *\n * Notes:\n *\n * - Production only.\n * - Results are cached per SVG string, so an icon repeated across many pages goes through svgo once per build.\n * - Files it wrote are published on \"pluginData.optimizedSvgList\" so copy-assets does not put the originals over them.\n * - The default config is svgo's \"preset-default\" with id cleanup, hidden-element removal and unknown-attribute removal turned off,\n * so ids and hooks the rest of the page relies on survive. Passing \"svgoConfig\" replaces that default entirely.\n * - SVGs inlined in CSS are out of reach; use a PostCSS plugin such as cssnano for those.\n */\nexport function svgoPlugin(options: svgoOptions = {}): Plugin {\n const include = options.include ?? [\"sources/assets/**/*.{svg,svga,svgz}\"];\n const ignore = options.exclude ?? [];\n options.optimizeInHtml ??= true;\n\n const svgoConfig = options.svgoConfig ?? {\n multipass: true,\n plugins: [\n {\n name: \"preset-default\",\n params: {\n overrides: {\n cleanupIds: false,\n removeUnknownsAndDefaults: { unknownAttrs: false },\n removeHiddenElems: false,\n },\n },\n },\n ],\n };\n\n const printFmtError = PrintFormattedError.create({ function: svgoPlugin });\n\n // Raw SVG string -> optimized result. The same icons are inlined on many pages (and pages can be\n // re-transformed), so each distinct SVG only goes through svgo once per build.\n const optimizeCache = new Map<string, string>();\n\n return {\n name: \"svgo\",\n\n setup() {\n this.pluginData.optimizedSvgList ??= new Set<string>();\n },\n\n async transform(metadata) {\n if (!this.production) return;\n\n if (options.optimizeInHtml && isHtmlMetadata(metadata)) {\n const filePath = metadata.filePath;\n\n const elements = metadata.ast.querySelectorAll(\"svg\");\n for (const node of elements) {\n const svgString = node.toString();\n\n let svg = optimizeCache.get(svgString);\n\n if (svg === undefined) {\n const [optimized, error] = await optimizeSvg(svgString, svgoConfig);\n if (error) {\n printFmtError(\"Failed to optimize svg using `svgo`\", error, { filePath, node });\n continue;\n }\n\n svg = optimized;\n optimizeCache.set(svgString, svg);\n // Already-optimized output is stable, so re-transformed pages hit the cache immediately.\n optimizeCache.set(svg, svg);\n }\n\n node.replaceWith(svg);\n }\n\n return;\n }\n },\n\n async postBuild() {\n if (!this.production) return;\n\n const svgFiles = globSync(include, { ignore, cwd: this.root });\n if (svgFiles.length === 0) return;\n\n for (const filePath of svgFiles) {\n const svgFileAbs = join(this.root, filePath);\n\n const [svgString, readError] = safeReadFileSync(svgFileAbs, \"utf8\");\n if (readError) {\n printFmtError(\"Failed to read svg file:\", readError, { filePath });\n continue;\n }\n\n const [optimizedSvg, error] = await optimizeSvg(svgString, svgoConfig);\n if (error) {\n printFmtError(\"Failed to optimize svg using `svgo`\", { filePath });\n continue;\n }\n\n const svgOutPath = join(this.outdir, filePath);\n mkdirSync(dirname(svgOutPath), { recursive: true });\n writeFileSync(svgOutPath, optimizedSvg);\n\n const optimizedSvgList = this.pluginData.optimizedSvgList as Set<string>;\n optimizedSvgList.add(svgFileAbs);\n }\n },\n };\n}\n","import postcss from \"postcss\";\n\nimport { valueOrError } from \"../../utilities/value-or-error.ts\";\n\nimport type { PostcssAst } from \"@staticbolt/core\";\n\nasync function processCssUnsafe(\n css: PostcssAst | string,\n plugins?: readonly postcss.AcceptedPlugin[],\n options?: postcss.ProcessOptions\n) {\n return await postcss(plugins).process(css, options ?? {});\n}\n\n/**\n * Parse CSS string and return the root node\n *\n * @mutate cssRoot\n */\nconst processCss = valueOrError(processCssUnsafe);\n\nexport { processCss };\n","import postcssrc from \"postcss-load-config\";\n\nimport { processCss } from \"../../ast-utilities/postcss-utils/process-css.ts\";\nimport { filterStyleMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { join, resolve } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { valueOrError } from \"../../utilities/value-or-error.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\nimport type postcss from \"postcss\";\n\nconst loadPostcssConfig = valueOrError(postcssrc);\n\nexport interface TransformCssOptions {\n /** Postcss plugins. */\n plugins?: readonly postcss.AcceptedPlugin[];\n\n /**\n * Whether to load postcss config file.\n *\n * @default false\n */\n loadConfig?: boolean;\n}\n\n/**\n * Runs PostCSS plugins over every stylesheet in the build, the \"<style>\" tags of a page included.\n *\n * Notes:\n *\n * - The plugins given in the options run first, followed by the ones from the PostCSS config file when \"loadConfig\" is on.\n * - That config is read once at startup, with the build mode and the project's browserslist as its context.\n * - With no plugins at all the pass is skipped.\n * - A plugin error is reported for the stylesheet it happened in and the build carries on.\n */\nexport function transformCssPlugin(options: TransformCssOptions = {}): Plugin {\n const plugins = options.plugins ?? [];\n const isLoadConfig = options.loadConfig ?? false;\n\n let postcssConfig: postcssrc.Result = { file: \"\", options: {}, plugins: [] };\n let allPlugins: postcss.AcceptedPlugin[] = [...plugins];\n\n const printFmtError = PrintFormattedError.create({ function: transformCssPlugin });\n\n return {\n name: \"transform-css\",\n\n async setup() {\n if (!isLoadConfig) return;\n\n const environment = this.production ? \"production\" : \"development\";\n const virtualCssFile = join(this.root, \"virtual.css\");\n\n const pluginsConfigContext = {\n browserslist: this.browserslist,\n cwd: this.root,\n env: environment,\n } as postcssrc.ConfigContext;\n\n const [loadedPlugins, loadPluginsError] = await loadPostcssConfig(pluginsConfigContext, virtualCssFile);\n if (loadPluginsError !== null) {\n printFmtError(loadPluginsError);\n return;\n }\n\n postcssConfig = loadedPlugins;\n allPlugins = [...plugins, ...postcssConfig.plugins];\n },\n\n async transform(inputMetadata) {\n if (allPlugins.length === 0) return;\n\n for (const { metadata, tag } of filterStyleMetadata(inputMetadata)) {\n const cssRoot = metadata.ast;\n\n const [, processError] = await processCss(cssRoot, allPlugins, { from: resolve(this.root, metadata.filePath) });\n if (processError !== null) {\n printFmtError(processError, { node: tag, filePath: metadata.id });\n }\n }\n },\n };\n}\n","import * as babel from \"@babel/core\";\n\nimport { valueOrError } from \"../../utilities/value-or-error.ts\";\n\nimport type { BabelAst } from \"@staticbolt/core\";\n\nconst babelTransform = valueOrError(babel.transformFromAstSync);\n\nexport interface UseBabelTransformOptions {\n ast: BabelAst;\n root: string;\n filePath: string;\n plugins?: babel.PluginItem[];\n presets?: babel.PluginItem[];\n}\n\nexport function useBabelTransform({ ast, root, filePath, plugins, presets }: UseBabelTransformOptions) {\n return babelTransform(ast, undefined, {\n minified: false,\n filename: filePath,\n cwd: root,\n root,\n presets,\n plugins,\n cloneInputAst: false,\n babelrc: false,\n configFile: false,\n ast: false,\n code: false,\n });\n}\n","import * as babel from \"@babel/core\";\nimport babelPresetEnv from \"@babel/preset-env\";\nimport babelTypeScriptPreset from \"@babel/preset-typescript\";\nimport transformDefine from \"babel-plugin-transform-define\";\n\nimport { useBabelTransform } from \"../../ast-utilities/babel-utils/use-transform.ts\";\nimport { filterScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { extname, join, replaceExtension } from \"../../utilities/path.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface TransformJsPluginOptions {\n presets?: babel.PluginItem[];\n plugins?: babel.PluginItem[];\n}\n\n/**\n * Runs Babel over every script in the build, TypeScript and JSX included.\n *\n * Presets are applied in order: TypeScript (all extensions, JSX enabled), preset-env against the project's browserslist, then the\n * project's own Babel config, then whatever the options add.\n *\n * Notes:\n *\n * - \"_production\" is substituted with the build mode, so a check like \"if (_production)\" is resolved at build time.\n * - Module syntax is preserved; \".ts\", \".jsx\" and \".tsx\" files only change their output path to \".js\".\n * - The result is resolved and loaded again, so imports a Babel plugin introduces still become part of the build.\n */\nexport function transformJsPlugin(options: TransformJsPluginOptions = {}): Plugin {\n const presets: babel.PluginItem[] = [];\n\n const plugins: babel.PluginItem[] = [...(options.plugins ?? [])];\n\n return {\n name: \"transform-js\",\n\n setup() {\n const virtualJsFile = join(this.root, \"virtual.js\");\n const babelConfig = babel.loadPartialConfig({ filename: virtualJsFile, cwd: this.root });\n // const babelConfig = babel.loadPartialConfigSync({ filename: virtualJsFile, cwd: this.root });\n\n presets.push(\n [babelTypeScriptPreset, { allExtensions: true, isTSX: true }],\n [babelPresetEnv, { targets: this.browserslist, modules: false }],\n ...(babelConfig?.options.presets ?? []),\n ...(options.presets ?? [])\n );\n\n plugins.push([transformDefine, { _production: this.production }], ...(babelConfig?.options.plugins ?? []));\n },\n\n async transform(inputMetadata) {\n for (const { metadata } of filterScriptMetadata(inputMetadata)) {\n metadata.ast.program.sourceType = metadata.module ? \"module\" : \"script\";\n\n const [, transformError] = useBabelTransform({\n ast: metadata.ast,\n root: this.root,\n filePath: join(this.root, metadata.filePath),\n plugins,\n presets,\n });\n\n if (transformError) {\n this.log.error(transformError.message);\n return;\n }\n\n if ([\".ts\", \".jsx\", \".tsx\"].includes(extname(metadata.filePath))) {\n metadata.filePath = replaceExtension(metadata.filePath, \".js\");\n }\n\n // Plugins may add imports/exports and introduce new dependencies\n\n const metadataList = await this.resolveAndLoad(metadata);\n\n // Remove current one (first one)\n metadataList.shift();\n\n // Merge\n this.addMetadata(metadataList);\n\n // Transform until this point\n await this.transformAndSync(metadataList);\n }\n },\n };\n}\n","import { isValidRelativePath, splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isWebManifestMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join, normalize, relative } from \"../../utilities/path.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface WebManifestOptions {\n /**\n * The file path to the manifest file relative to the root directory.\n *\n * @default \"./sources/assets/manifest.json\"\n */\n manifestPath?: string;\n\n /**\n * The output file path relative to the output directory.\n *\n * @default \"./manifest.json\"\n */\n outfile?: string;\n}\n\n/**\n * Emits the web app manifest at \"outfile\" and repoints the links to it.\n *\n * Notes:\n *\n * - Only the file at \"manifestPath\" counts as the manifest; links to any other JSON are left alone.\n * - It is rebased once the transforms are done, so the paths inside it (icons, screenshots) keep resolving from the new location.\n * - The links are rewritten in production only; while serving, the manifest stays at its source path.\n */\nexport function webManifestPlugin(options: WebManifestOptions = {}): Plugin {\n const manifestPath = normalize(options.manifestPath ?? \"./sources/assets/manifest.json\");\n const outfile = normalize(options.outfile ?? \"./manifest.json\");\n\n return {\n name: \"web-manifest\",\n\n transformSource(source, filePath, _, dependencyID) {\n if (!this.production || dependencyID !== manifestPath || !isValidRelativePath(source)) return;\n\n const [, suffix] = splitHtmlLink(source);\n\n return relative(dirname(filePath), outfile) + suffix;\n },\n\n async postTransform() {\n if (!this.production) return;\n\n for (const metadata of this.metadataList) {\n if (!isWebManifestMetadata(metadata)) continue;\n\n await this.rebase(metadata, join(this.root, outfile));\n }\n },\n };\n}\n","import { availableParallelism } from \"node:os\";\nimport { Worker } from \"node:worker_threads\";\n\n/**\n * Past a handful of workers the jobs fight each other for memory bandwidth more than they gain from another core, and every one\n * of them carries its own copy of whatever the worker loads. Machines with cores to spare get told a number.\n */\nconst DEFAULT_CONCURRENCY = 8;\n\nexport interface WorkerPoolOptions<Job, Result> {\n /** The worker module to spawn. Whatever it does with a job, and whatever it sends back, is between it and the caller. */\n workerUrl: URL;\n\n /** How many workers may run at once. Defaults to one per core, up to eight. */\n concurrency?: number;\n\n /** Called with what the worker sent back for a job. */\n onResult: (job: Job, result: Result) => void;\n\n /** Called for a job no worker was left to run. */\n onFailure: (job: Job, message: string) => void;\n}\n\n/**\n * Runs jobs across a pool of worker threads.\n *\n * Jobs can be added while the rest of the program is still going: a worker is taken on as there is work for it and each pulls\n * from the queue as it frees up, so a job starts the moment it lands rather than waiting for the whole batch. `drain` waits for\n * what is left over and takes the workers down.\n *\n * A job is posted to the worker as it is and the reply is handed back as it is. The pool never looks inside either, so what a job\n * means is entirely the caller's business.\n */\nexport class WorkerPool<Job, Result> {\n readonly #queue: Job[] = [];\n readonly #workers: Promise<void>[] = [];\n readonly #waiting: (() => void)[] = [];\n\n readonly #workerUrl: URL;\n readonly #concurrency: number;\n readonly #onResult: WorkerPoolOptions<Job, Result>[\"onResult\"];\n readonly #onFailure: WorkerPoolOptions<Job, Result>[\"onFailure\"];\n\n #draining = false;\n\n /** Why the workers gave out, when they did. Reported against the jobs that were left over. */\n #failure: string | undefined;\n\n constructor({ workerUrl, concurrency, onResult, onFailure }: WorkerPoolOptions<Job, Result>) {\n this.#workerUrl = workerUrl;\n this.#concurrency = Math.max(1, concurrency ?? Math.min(DEFAULT_CONCURRENCY, availableParallelism() - 1));\n this.#onResult = onResult;\n this.#onFailure = onFailure;\n }\n\n /** Queues a job, taking on another worker if there is still room for one. */\n add(job: Job): void {\n this.#queue.push(job);\n\n if (this.#workers.length < this.#concurrency) {\n this.#workers.push(this.#keepWorking());\n }\n\n this.#wake();\n }\n\n /** Waits for the queue to empty, then takes the workers down. Whatever nothing was left to run is reported. */\n async drain(): Promise<void> {\n if (this.#workers.length === 0) return;\n\n this.#draining = true;\n this.#wake();\n\n await Promise.all(this.#workers);\n\n this.#workers.length = 0;\n this.#draining = false;\n\n for (const job of this.#queue) {\n this.#onFailure(job, this.#failure ?? \"No worker left to run the job\");\n }\n\n this.#queue.length = 0;\n this.#failure = undefined;\n }\n\n /**\n * Holds a worker for as long as there is work for it, and never rejects.\n *\n * Nothing awaits these until `drain`, and a promise left rejected until then takes the process down as an unhandled rejection.\n * A worker that cannot even start says so here, and `drain` reports it against every job it never got to.\n */\n async #keepWorking(): Promise<void> {\n try {\n await this.#work();\n } catch (error) {\n this.#failure ??= error instanceof Error ? error.message : String(error);\n }\n }\n\n /** One worker, taking the next job whenever it comes free and sitting out the gaps until the caller stops feeding it. */\n async #work(): Promise<void> {\n const worker = new Worker(this.#workerUrl);\n\n worker.on(\"error\", () => {});\n\n try {\n while (true) {\n if (this.#queue.length === 0) {\n if (this.#draining) return;\n await this.#waitForWork();\n continue;\n }\n\n const job = this.#queue.shift() as Job;\n\n let result: Result;\n\n try {\n result = await this.#send(worker, job);\n } catch {\n this.#queue.unshift(job);\n this.#wake();\n return;\n }\n\n this.#onResult(job, result);\n }\n } finally {\n await worker.terminate();\n }\n }\n\n /** One round trip. A worker is only ever given its next job once the one before it came back. */\n #send(worker: Worker, job: Job): Promise<Result> {\n return new Promise((resolve, reject) => {\n const onMessage = (result: Result) => {\n detach();\n resolve(result);\n };\n\n const onError = (error: Error) => {\n detach();\n reject(error);\n };\n\n const onExit = (code: number) => {\n detach();\n reject(new Error(`Worker stopped with exit code ${code}`));\n };\n\n function detach() {\n worker.off(\"message\", onMessage);\n worker.off(\"error\", onError);\n worker.off(\"exit\", onExit);\n }\n\n worker.on(\"message\", onMessage);\n worker.on(\"error\", onError);\n worker.on(\"exit\", onExit);\n\n worker.postMessage(job);\n });\n }\n\n /** Parks a worker until there is something to take, or until the pool is closing and it can stop. */\n #waitForWork(): Promise<void> {\n return new Promise(resolve => {\n this.#waiting.push(resolve);\n });\n }\n\n /** Wakes every parked worker at once. The ones that find nothing left to take park themselves again. */\n #wake(): void {\n const parked = [...this.#waiting];\n this.#waiting.length = 0;\n\n for (const resolve of parked) resolve();\n }\n}\n","import { cpSync, mkdirSync, rmSync, writeFileSync } from \"node:fs\";\n\nimport { WorkerPool } from \"../../helpers/worker-pool.ts\";\nimport { isBinaryAssetMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join, isPathMatch, relative } from \"../../utilities/path.ts\";\n\nimport type { DeferredJob, DeferredJobResult } from \"./deferred-worker.ts\";\nimport type { App, DeferredPass, MetadataBase, Plugin } from \"@staticbolt/core\";\n\nexport interface WriteFilesOptions {\n /** Remove the output directory before emitting files. */\n clean?: boolean;\n\n /**\n * Glob patterns to match files to write.\n *\n * @default [\"**\\/*\"]\n */\n include?: string[];\n\n /**\n * Glob patterns to ignore files from writing.\n *\n * @default [ ]\n */\n exclude?: string[];\n\n /**\n * How many worker threads may minify or format output files at once.\n *\n * @default One per core, up to eight\n */\n concurrency?: number;\n\n minify?: {\n /**\n * Whether to minify output.\n *\n * @default false\n */\n enabled?: boolean;\n\n /**\n * Glob patterns to match files to minify.\n *\n * @default [\"**\\/*\"]\n */\n include?: string[];\n\n /**\n * Glob patterns to ignore files from minifying.\n *\n * @default [ ]\n */\n exclude?: string[];\n };\n\n format?: {\n /**\n * Whether to format output.\n *\n * @default false\n */\n enabled?: boolean;\n\n /**\n * Glob patterns to match files to format.\n *\n * @default [\"**\\/*\"]\n */\n include?: string[];\n\n /**\n * Glob patterns to ignore files from formatting.\n *\n * @default [ ]\n */\n exclude?: string[];\n };\n}\n\n/**\n * Emits the build: everything that survived the pipeline is stringified and written under the output directory, with binary\n * assets copied over as they are.\n *\n * Notes:\n *\n * - Production only. The dev server serves from memory and writes nothing.\n * - \"clean\" removes the output directory before the build starts.\n * - \"include\" and \"exclude\" are matched against the source path, and anything a plugin excluded from emitting is skipped.\n * - \"minify\" and \"format\" carry their own patterns; turning both on for the same file logs a warning.\n * - A file whose path would land outside the output directory is reported and skipped.\n * - Formatting and minifying are the slow part of printing a file, so any plugin willing to hand its final pass over gets taken up\n * on it: the file is written as it came out and its pass goes to a pool of worker threads chewing through them while the files\n * behind it are still being written. The pool is drained before this hook returns, so the output directory is settled by the\n * time anything else runs.\n */\nexport function writeFilesPlugin(options: WriteFilesOptions): Plugin {\n const include = options.include ?? [\"**/*\"];\n const ignore = options.exclude ?? [];\n\n /** Runs the passes the plugins handed over, kept around from the first file that needs one until the write is done. */\n let deferredPool: WorkerPool<DeferredJob, DeferredJobResult> | undefined;\n\n options.minify ??= {};\n options.minify.enabled ??= false;\n options.minify.include ??= [\"**/*\"];\n options.minify.exclude ??= [];\n const minify = options.minify as Required<Exclude<WriteFilesOptions[\"minify\"], undefined>>;\n\n options.format ??= {};\n options.format.enabled ??= false;\n options.format.include ??= [\"**/*\"];\n options.format.exclude ??= [];\n const format = options.format as Required<Exclude<WriteFilesOptions[\"format\"], undefined>>;\n\n function shouldMinifyFile(filePath: string, root: string): boolean {\n return minify.enabled && isPathMatch(filePath, { include: minify.include, ignore: minify.exclude, root });\n }\n\n function shouldFormatFile(filePath: string, root: string): boolean {\n return format.enabled && isPathMatch(filePath, { include: format.include, ignore: format.exclude, root });\n }\n\n /** Made on the first file that needs one, so a build with nothing to format or minify never starts a worker. */\n function poolFor(app: App): WorkerPool<DeferredJob, DeferredJobResult> {\n const report = (job: DeferredJob, message: string) => {\n app.log.error(`Failed to process \"${relative(app.outdir, job.path)}\": ${message}`);\n };\n\n deferredPool ??= new WorkerPool<DeferredJob, DeferredJobResult>({\n workerUrl: resolveWorkerUrl(),\n concurrency: options.concurrency,\n onResult: (job, { error }) => {\n if (error) report(job, error);\n },\n onFailure: report,\n });\n\n return deferredPool;\n }\n\n /** Writes one file, handing its final pass to the pool whenever a plugin offers one. */\n async function emit(app: App, metadata: MetadataBase): Promise<void> {\n if (app.emitExclude.has(metadata)) return;\n\n const isIncluded = isPathMatch(metadata.id, { include, ignore, root: app.root });\n if (!isIncluded) return;\n\n if (metadata.filePath.startsWith(\"../\")) {\n app.log.error(`file path \"${metadata.filePath}\" is outside of the output directory \"${app.outdir}\". Skipping...`);\n return;\n }\n\n const shouldMinify = shouldMinifyFile(metadata.id, app.root);\n const shouldFormat = shouldFormatFile(metadata.id, app.root);\n\n if (shouldMinify && shouldFormat) {\n app.log.warn(`\"minify\" and \"format\" are enabled for \"${metadata.id}\" but only one can be used.`);\n }\n\n if (isBinaryAssetMetadata(metadata)) {\n const copyFrom = join(app.root, metadata.id);\n const copyTo = join(app.outdir, metadata.filePath);\n cpSync(copyFrom, copyTo, { recursive: true });\n return;\n }\n\n // stringify\n let deferredPass: DeferredPass | undefined;\n\n const code = await app.stringify(metadata, {\n format: shouldFormat,\n minify: shouldMinify,\n defer: pass => {\n deferredPass = pass;\n },\n });\n\n if (typeof code !== \"string\") {\n app.log.error(`Failed to stringify \"${metadata.id}\"`);\n return;\n }\n\n if (!code) {\n app.log.warn(`Writing empty file \"${metadata.filePath}\"`);\n }\n\n // write\n const outputFile = join(app.outdir, metadata.filePath);\n mkdirSync(dirname(outputFile), { recursive: true });\n writeFileSync(outputFile, code, \"utf8\");\n\n if (deferredPass) {\n poolFor(app).add({ path: outputFile, pass: deferredPass });\n }\n }\n\n return {\n name: \"emit-files\",\n\n setup() {\n if (!this.production) return;\n\n if (options.clean) {\n rmSync(this.outdir, { recursive: true, force: true });\n }\n },\n\n async write() {\n if (!this.production) return;\n\n try {\n for (const metadata of this.metadataList) {\n await emit(this, metadata);\n }\n } finally {\n // Worker threads hold the process open, so the pool has to come down even if a file took the write out with it.\n await deferredPool?.drain();\n }\n },\n };\n}\n\nlet workerUrl: URL | undefined;\n\n/** Resolved through the package's own exports, so it holds up wherever this plugin ended up relative to its worker. */\nfunction resolveWorkerUrl(): URL {\n workerUrl ??= new URL(import.meta.resolve(\"@staticbolt/core/deferred-worker\"));\n return workerUrl;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport vm from \"node:vm\";\nimport * as babel from \"@babel/core\";\nimport transformModulesCommonjs from \"@babel/plugin-transform-modules-commonjs\";\nimport * as t from \"@babel/types\";\n\nimport { dirname, extname, join } from \"../utilities/path.ts\";\nimport { valueOrError } from \"../utilities/value-or-error.ts\";\n\nimport type { JSDOM } from \"jsdom\";\n\ninterface ExecuteJsInVmOptions {\n /** The root directory of the project, where JSON imports are read from */\n root: string;\n\n /** The module to run, as a path relative to the root */\n entryFile: string;\n\n /** The source of a module, the entry file and everything it imports. Nothing means the module does not exist */\n getCode(filePath: string): string | void | Promise<string | void>;\n\n /** Globals for the scripts, applied on top of the built-in ones */\n context?: Record<string, unknown>;\n\n /** Called with every project file the VM loads, including the entry file and JSON imports, but not `node:` built-ins */\n onModuleLoad?(filePath: string): void;\n\n /** When given, `document` and `window` come from a jsdom instance of this html */\n html?: string;\n}\n\ninterface ExecuteJsInVmResult {\n exports: { [k: string]: unknown };\n dom: JSDOM | undefined;\n}\n\n/** Runs an ES module graph inside a `node:vm` context and hands back what the entry module exported. */\nasync function executeJsInVmUnsafe(options: ExecuteJsInVmOptions): Promise<ExecuteJsInVmResult> {\n const { dom, context } = await createSandbox(options.html, options.context);\n\n const runner = new ModuleRunner(context, options);\n const exports = await runner.import(options.entryFile);\n\n return { exports: { ...exports }, dom };\n}\n\n/** A jsdom window when there is html to work on, a bare object with the essentials otherwise. */\nasync function createSandbox(html: string | undefined, globals: Record<string, unknown> = {}) {\n let dom: JSDOM | undefined;\n\n if (html) {\n const { JSDOM, VirtualConsole } = await import(\"jsdom\");\n dom = new JSDOM(html, { virtualConsole: new VirtualConsole(), url: \"http://localhost/\" });\n }\n\n const window = dom ? dom.window : {};\n if (!dom) {\n Object.assign(window, { setTimeout, setInterval, clearInterval, clearTimeout, fetch, URL });\n }\n\n Object.assign(window, { console }, globals);\n\n return { dom, context: vm.createContext(window) };\n}\n\ntype ModuleExports = Record<string, unknown>;\n\n/** What a module body gets to see of the module system. The names are what `toModuleBody` rewrites the syntax to. */\ninterface ModuleScope {\n require(specifier: string): ModuleExports;\n __import(specifier: string): Promise<ModuleExports>;\n __meta: { url: string; resolve(url: string): string };\n exports: ModuleExports;\n}\n\ntype ModuleBody = (scope: ModuleScope) => Promise<void>;\n\nconst BASE_META_URL = \"http://localhost:3000\";\n\n/**\n * Runs modules the way ES modules run: each one once, its static imports before it in source order, top-level `await` included. A\n * module that imports one of its own importers (a cycle) gets its exports as far as they are.\n *\n * Modules are rewritten to CommonJS and run as functions in the context, which keeps them collectable once the run is over.\n */\nclass ModuleRunner {\n /** Resolves to the module's exports once it has run. Registered before the module starts, so it only ever runs once. */\n readonly #runs = new Map<string, Promise<ModuleExports>>();\n\n /** The exports of every module that has started, which is what a cycle gets to see. */\n readonly #exports = new Map<string, ModuleExports>();\n\n readonly #context: vm.Context;\n readonly #options: ExecuteJsInVmOptions;\n\n constructor(context: vm.Context, options: ExecuteJsInVmOptions) {\n this.#context = context;\n this.#options = options;\n }\n\n /**\n * Runs the module unless it already has, and resolves to its exports. `importers` is the chain of static imports that led here,\n * empty for the entry and for dynamic imports.\n */\n import(id: string, importers: ReadonlySet<string> = new Set()): Promise<ModuleExports> {\n let run = this.#runs.get(id);\n\n if (!run) {\n run = this.#run(id, importers);\n this.#runs.set(id, run);\n }\n\n return run;\n }\n\n async #run(id: string, importers: ReadonlySet<string>): Promise<ModuleExports> {\n const exports: ModuleExports = {};\n this.#exports.set(id, exports);\n\n if (id.startsWith(\"node:\")) {\n return Object.assign(exports, (await import(id)) as ModuleExports);\n }\n\n this.#options.onModuleLoad?.(id);\n\n if (extname(id) === \".json\") {\n exports.default = this.#readJson(id);\n return exports;\n }\n\n const source = await this.#options.getCode(id);\n if (!source) {\n throw new Error(`[executeJsInVM] can't find the script '${id}'`);\n }\n\n const { code, imports } = await toModuleBody(source, id);\n\n // A static import that is already on the chain is an importer of this module: a cycle, not waited on\n const chain = new Set(importers).add(id);\n for (const specifier of imports) {\n const importId = this.#resolve(specifier, id);\n if (!chain.has(importId)) {\n await this.import(importId, chain);\n }\n }\n\n const body = this.#compile(code, id);\n\n await body({\n require: specifier => this.#require(specifier, id),\n __import: specifier => this.import(this.#resolve(specifier, id)),\n __meta: createImportMeta(id),\n exports,\n });\n\n return exports;\n }\n\n /** Creates the function in the context, so its globals are the sandbox's. */\n #compile(code: string, id: string): ModuleBody {\n const script = new vm.Script(`\"use strict\"; (async function ({ require, __import, __meta, exports }) {\\n${code}\\n})`, {\n filename: id,\n lineOffset: -1,\n });\n\n return script.runInContext(this.#context) as ModuleBody;\n }\n\n #require(specifier: string, importer: string): ModuleExports {\n const exports = this.#exports.get(this.#resolve(specifier, importer));\n if (!exports) {\n throw new Error(`[executeJsInVM] '${specifier}' has not run before '${importer}'`);\n }\n\n return exports;\n }\n\n #resolve(specifier: string, importer: string): string {\n return specifier.startsWith(\"node:\") ? specifier : join(dirname(importer), specifier);\n }\n\n #readJson(id: string): unknown {\n const jsonPath = join(this.#options.root, id);\n if (!existsSync(jsonPath)) {\n throw new Error(`[executeJsInVM] can't find the file '${id}'`);\n }\n\n return JSON.parse(readFileSync(jsonPath, \"utf8\"));\n }\n}\n\nfunction createImportMeta(id: string): ModuleScope[\"__meta\"] {\n if (extname(id) === \".html\") {\n id = dirname(id) + \"/\";\n }\n\n const url = new URL(id, BASE_META_URL).href;\n\n return {\n url,\n resolve: specifier => new URL(specifier, url).href,\n };\n}\n\ninterface ModuleBodySource {\n code: string;\n imports: string[];\n}\n\n/**\n * The same module runs once per page that uses it, so its rewrite is kept by source. The oldest entries go once there are more\n * than `MODULE_BODY_CACHE_SIZE`, which keeps a long editing session from piling up dead ones.\n */\nconst moduleBodyCache = new Map<string, ModuleBodySource>();\nconst MODULE_BODY_CACHE_SIZE = 256;\n\n/**\n * Rewrites an ES module into the body of a `ModuleBody`: imports and exports become `require` and `exports`, `import.meta`\n * becomes `__meta` and `import()` becomes `__import()`. Also lists what the module imports statically.\n */\nasync function toModuleBody(source: string, id: string): Promise<ModuleBodySource> {\n const cached = moduleBodyCache.get(source);\n if (cached) {\n return cached;\n }\n\n const imports: string[] = [];\n\n const result = await babel.transformAsync(source, {\n filename: id,\n sourceType: \"module\",\n babelrc: false,\n configFile: false,\n compact: false,\n sourceMaps: false,\n plugins: [collectImportsAndRewriteMeta(imports), [transformModulesCommonjs, { importInterop: \"none\", strictMode: false }]],\n });\n\n if (!result?.code) {\n throw new Error(`[executeJsInVM] failed to transform '${id}'`);\n }\n\n const moduleBody = { code: result.code, imports };\n moduleBodyCache.set(source, moduleBody);\n\n if (moduleBodyCache.size > MODULE_BODY_CACHE_SIZE) {\n moduleBodyCache.delete(moduleBodyCache.keys().next().value!);\n }\n\n return moduleBody;\n}\n\n/** Lists the static import sources into `imports`, and turns `import.meta` into `__meta` and `import()` into `__import()`. */\nfunction collectImportsAndRewriteMeta(imports: string[]): babel.PluginObj {\n return {\n visitor: {\n ImportDeclaration(path) {\n imports.push(path.node.source.value);\n },\n\n ExportNamedDeclaration(path) {\n if (path.node.source) {\n imports.push(path.node.source.value);\n }\n },\n\n ExportAllDeclaration(path) {\n imports.push(path.node.source.value);\n },\n\n MetaProperty(path) {\n if (path.node.meta.name === \"import\") {\n path.replaceWith(t.identifier(\"__meta\"));\n }\n },\n\n CallExpression(path) {\n if (t.isImport(path.node.callee)) {\n path.node.callee = t.identifier(\"__import\");\n }\n },\n },\n };\n}\n\nconst executeJsInVM = valueOrError(executeJsInVmUnsafe);\n\nexport { executeJsInVM };\n","import { isTypeScriptScript } from \"../../helpers/lsp-checks.ts\";\n\nimport type { DocumentInfo, ElementInfo, EmbeddedLanguage } from \"@staticbolt/core\";\n\n/** The attribute names the plugin was set up with. */\nexport interface BuildTimeNames {\n /** Marks a script as running at build time. */\n build: string;\n\n /** Gives the script a full DOM instead of the page's tree. */\n fullDom: string;\n\n /** Holds a JSON object of extra globals for the script. */\n context: string;\n}\n\n/** What the sandbox gives every build-time script; these shadow the DOM globals of the same name. */\nconst GLOBALS = `declare const StaticBolt: import(\"@staticbolt/core\").App;\ndeclare const window: typeof globalThis;\ndeclare const __filepath: string;\ndeclare const __id: string;`;\n\n/** The page's tree is the parser's, not the DOM's: its node types take the DOM names, so the code reads as it runs. */\nconst PARSER_TYPES = [\"Document\", \"HTMLElement\", \"Node\", \"TextNode\", \"CommentNode\", \"NodeType\"]\n .map(name => `type ${name} = import(\"@staticbolt/node-html-parser\").${name};`)\n .join(\"\\n\");\n\n/**\n * The bodies of the build-time scripts marked `type=\"application/x-typescript\"`, served as TypeScript that sees the sandbox\n * globals: completion, hover and type errors. Claimed before the core plugin, later in the config, sees the browser in them.\n */\nexport function embeddedLanguages(names: BuildTimeNames): EmbeddedLanguage[] {\n return [\n {\n name: \"build-time\",\n filter: () => true,\n // Each script runs on its own, so each is a module of its own\n findRegions: document =>\n buildTimeScripts(document, names).flatMap(script =>\n script.contentRange ? { ...script.contentRange, isModule: true } : []\n ),\n isColouredByEditor: true,\n prelude: document => prelude(buildTimeScripts(document, names), names),\n },\n ];\n}\n\n/** The build-time scripts of a document that are marked as TypeScript. */\nfunction buildTimeScripts(document: DocumentInfo, names: BuildTimeNames): ElementInfo[] {\n return document.select(\"script\").filter(script => script.has(names.build) && isTypeScriptScript(script));\n}\n\n/**\n * The declarations for a document's build-time scripts: the sandbox globals, and `document` as the parser's tree or, with a full\n * DOM, the DOM's.\n */\nfunction prelude(scripts: ElementInfo[], names: BuildTimeNames): string {\n const hasFullDom = scripts.some(script => script.has(names.fullDom));\n const lines = [GLOBALS];\n\n if (!hasFullDom) {\n lines.push(PARSER_TYPES);\n }\n\n lines.push(\"declare const document: Document;\");\n\n return lines.join(\"\\n\");\n}\n","import { DependencyTracker } from \"../../helpers/dependency-tracker.ts\";\nimport { executeJsInVM } from \"../../helpers/execute-js-in-vm.ts\";\nimport { isScriptType } from \"../../helpers/is-script-type.ts\";\nimport { checkFileExists, checkJsonObject, isEmptyElement, isJavaScript } from \"../../helpers/lsp-checks.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata, isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { embeddedLanguages } from \"./lsp.ts\";\n\nimport type { Plugin, ScriptMetadata } from \"@staticbolt/core\";\n\nexport interface HtmlBuildTimeScriptOptions {\n /**\n * The name of the attribute on the script tag that marks it for execution.\n *\n * @default \"build-time\"\n */\n buildAttribute?: string;\n\n /**\n * The name of the attribute on the script tag that enables full DOM context using `jsdom`, otherwise `node-html-parser` is\n * used.\n *\n * @default \"full-dom\"\n */\n fullDomAttribute?: string;\n\n /**\n * The name of the attribute on the script tag that holds a JSON object, whose entries are exposed as globals to the script\n * during execution.\n *\n * @default \"context\"\n */\n contextAttribute?: string;\n}\n\n/**\n * Executes script tags marked with \"build-time\" during the build and keeps whatever they did to the page. The tag itself never\n * reaches the output.\n *\n * Attributes (names configurable via HtmlBuildTimeScriptOptions):\n *\n * - \"build-time\": execute this tag, inline or through \"src\".\n * - \"full-dom\": run against a jsdom document instead of the lighter node-html-parser AST.\n * - \"context\": a JSON object whose entries become globals for that script.\n *\n * Scripts run in \"node:vm\" with \"document\", \"window\", \"StaticBolt\" (the app), \"__filepath\" and \"__id\" in scope. \"context\" entries\n * are applied last, so they can shadow those names; if the JSON fails to parse the script still runs without them.\n *\n * Notes:\n *\n * - \"full-dom\" needs a fully constructed page (a head and a body), so place this plugin last when using it.\n * - Failures are per tag: the error is logged and the rest of the page carries on.\n * - In development the files each page executed are tracked, so editing one of them recompiles the pages that used it.\n */\nexport function htmlBuildTimeScript(options: HtmlBuildTimeScriptOptions = {}): Plugin {\n const buildAttribute = options.buildAttribute ?? \"build-time\";\n const fullDomAttribute = options.fullDomAttribute ?? \"full-dom\";\n const contextAttribute = options.contextAttribute ?? \"context\";\n const query = `script[${buildAttribute}]`;\n\n const printFmtError = PrintFormattedError.create({ function: htmlBuildTimeScript });\n\n /** Page → the files its build-time scripts executed. Used to recompile the page when one of them changes. */\n const dependencies = new DependencyTracker();\n\n return {\n name: \"html-build-time-script\",\n\n async postTransform() {\n // Only the dev server consumes this, and building it is not free\n const isTracking = !this.production;\n const executedSources = new Map<string, Set<string>>();\n\n for (const metadata of this.metadataList) {\n if (!isHtmlMetadata(metadata)) {\n continue;\n }\n\n // Is the page is fully constructed\n const isReady = metadata.ast.querySelector(\"body\") && metadata.ast.querySelector(\"head\");\n\n const scripts = metadata.ast.querySelectorAll(query);\n if (scripts.length === 0) continue;\n\n const pageSources = isTracking ? (executedSources.get(metadata.id) ?? new Set<string>()) : undefined;\n if (pageSources) {\n executedSources.set(metadata.id, pageSources);\n }\n\n for (const node of scripts) {\n const shouldUseFullDom = node.hasAttribute(fullDomAttribute);\n\n const scriptType = node.getAttribute(\"type\");\n if (!isScriptType(scriptType)) {\n continue;\n }\n\n if (shouldUseFullDom && !isReady) {\n printFmtError(\"Script cannot be executed until the page is fully constructed.\", { node });\n continue;\n }\n\n let scriptMetadata: ScriptMetadata;\n\n // Script with content\n const metadataID = node.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (metadataID) {\n const inlinedMetadata = metadata.scriptsMetadataList.get(metadataID);\n if (!inlinedMetadata) {\n printFmtError(\"Failed to execute script tag. Missing metadata\", { node });\n continue;\n }\n\n scriptMetadata = inlinedMetadata;\n }\n // Script with src attribute\n else {\n const source = node.getAttribute(\"src\");\n if (!source) {\n printFmtError(\"Failed to execute script tag. Missing src attribute\", { node });\n continue;\n }\n\n const [link] = splitHtmlLink(source);\n const sourceRelative = join(dirname(metadata.filePath), link);\n\n const fileMetadata = this.findMetadata({ filePath: sourceRelative });\n if (!isScriptMetadata(fileMetadata)) {\n printFmtError(`Failed to execute script tag. Missing metadata \"${sourceRelative}\"`, { node });\n continue;\n }\n\n scriptMetadata = fileMetadata;\n }\n\n const getCode = async (targetPath: string) => {\n // Entry point\n if (targetPath === scriptMetadata.filePath) {\n return await this.stringify(scriptMetadata);\n }\n\n // External file\n const foundMetadata = this.findMetadata({ filePath: targetPath });\n if (foundMetadata) {\n return await this.stringify(foundMetadata);\n }\n };\n\n const contextAttributeValue = node.getAttribute(contextAttribute);\n\n let extraContext: Record<string, unknown> = {};\n if (contextAttributeValue) {\n try {\n extraContext = JSON.parse(contextAttributeValue) as Record<string, unknown>;\n } catch (error) {\n printFmtError(\"Failed to parse context attribute\\n\", contextAttributeValue, error as Error, { node });\n }\n }\n\n const [executeResult, error] = await executeJsInVM({\n root: this.root,\n entryFile: scriptMetadata.filePath,\n html: shouldUseFullDom ? await this.stringify(metadata) : undefined,\n context: {\n document: shouldUseFullDom ? undefined : metadata.ast,\n window: globalThis,\n StaticBolt: this,\n __filepath: metadata.filePath,\n __id: metadata.id,\n ...extraContext,\n },\n getCode,\n // The VM reports output paths, while the dev server invalidates by source id\n onModuleLoad: pageSources\n ? sourcePath => pageSources.add(this.findMetadata({ filePath: sourcePath })?.id ?? sourcePath)\n : undefined,\n });\n\n if (error) {\n printFmtError(\"Failed to execute script tag\", error, { node });\n continue;\n }\n\n if (shouldUseFullDom && executeResult.dom) {\n const output = executeResult.dom.serialize();\n metadata.ast.root.set_content(output);\n }\n }\n\n // remove script tags after executing\n for (const node of metadata.ast.querySelectorAll(query)) {\n node.remove();\n }\n }\n\n for (const [id, sources] of executedSources) {\n dependencies.update(id, sources);\n }\n },\n\n onFileEvent(event, id) {\n if (event === \"unlink\") {\n dependencies.delete(id);\n }\n },\n\n resolveCompileList(compileSet, event) {\n if (event !== \"change\") return;\n\n for (const id of Array.from(compileSet)) {\n for (const importer of dependencies.getImporters(id)) {\n compileSet.add(importer);\n }\n }\n },\n\n lspEmbeddedLanguages() {\n return embeddedLanguages({ build: buildAttribute, fullDom: fullDomAttribute, context: contextAttribute });\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: \"script\",\n description:\n `Adds the \\`${buildAttribute}\\`, \\`${fullDomAttribute}\\` and \\`${contextAttribute}\\` attributes,` +\n \" which execute the script during the build and keep whatever it did to the page. The tag itself never reaches the output.\",\n attributes: [\n {\n name: buildAttribute,\n description:\n \"This attribute is used to mark the script as build-time script.\" +\n '\\n\\nWith `type=\"application/x-typescript\"` the staticbolt language server serves the script with the sandbox' +\n \" globals (`StaticBolt`, `document`, `window`, `__filepath`, `__id`) in place of the browser's.\",\n valueSet: \"v\",\n },\n {\n name: fullDomAttribute,\n description:\n \"Opt into a full DOM context using `jsdom`. When not present, the lighter `@staticbolt/node-html-parser` is used instead.\",\n valueSet: \"v\",\n },\n {\n name: contextAttribute,\n description: \"Pass global context object as JSON to be available in the script during execution.\",\n },\n ],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const scripts = document.select(\"script\");\n\n for (const element of scripts) {\n const build = element.attribute(buildAttribute);\n if (!build) continue;\n\n if (!isJavaScript(element)) {\n report.warn(build.nameRange, `\"${buildAttribute}\" does nothing on a script that is not JavaScript`);\n continue;\n }\n\n const context = element.attribute(contextAttribute);\n if (context) {\n checkJsonObject(context, report);\n }\n\n const source = element.attribute(\"src\");\n if (!source?.value && isEmptyElement(element, document)) {\n report.error(build.nameRange, `\"${buildAttribute}\" needs a \"src\" or some code in the script to run`);\n continue;\n }\n\n if (source) {\n checkFileExists(source, document, report);\n }\n }\n },\n };\n}\n","import { Log } from \"../../utilities/logger.ts\";\nimport { isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join, isPathMatch, relative } from \"../../utilities/path.ts\";\n\nimport type { App, ScriptMetadata } from \"@staticbolt/core\";\nimport type { Plugin } from \"esbuild\";\n\ntype CheckExternal = (strings: string) => boolean;\n\nexport function loaderPlugin(this: App, outFile: string, isExternalCheck: CheckExternal): Plugin {\n const root = this.root;\n const outFileAbs = join(root, outFile);\n\n // eslint-disable-next-line unicorn/no-this-assignment, @typescript-eslint/no-this-alias\n const app = this;\n\n return {\n name: \"resolve-loader\",\n\n setup(build) {\n // Intercepts relative JS imports so they can be routed through the app metadata system\n // instead of being resolved from disk by esbuild directly.\n build.onResolve({ filter: /\\.(js|mjs|cjs)$/ }, arguments_ => {\n if (!arguments_.path.startsWith(\".\")) return;\n\n const absSource = join(arguments_.resolveDir, arguments_.path);\n const source = relative(root, absSource);\n\n // Modules marked as external are excluded from the bundle. The path is made relative\n // to the output file so the bundled output can reference it correctly at runtime.\n if (isExternalCheck(source)) {\n const relativeToOutFile = relative(dirname(outFile), source);\n return { path: relativeToOutFile, external: true };\n }\n\n // Let esbuild resolve node_modules directly rather than routing them through\n // the loader namespace, since we have no metadata for those files.\n if (isPathMatch(source, { include: [\"**/node_modules/**\"], ignore: [], root })) {\n return { path: absSource };\n }\n\n const scriptMetadata = app.findMetadata({ filePath: source });\n if (!isScriptMetadata(scriptMetadata)) {\n Log.error(`[htmlBundleScriptPlugin:onResolve] Script metadata for the path \"${source}\" not found`);\n return;\n }\n\n // Route through the loader namespace so onLoad can rebase and stringify\n // the script using app metadata rather than reading it from disk.\n return { path: absSource, namespace: \"loader\", pluginData: scriptMetadata };\n });\n\n // Handles every script that was routed into the loader namespace by onResolve.\n // Clones and rebases each one relative to the output file before stringifying.\n build.onLoad({ filter: /\\.(js|mjs|cjs)$/, namespace: \"loader\" }, async arguments_ => {\n const scriptMetadata = arguments_.pluginData as ScriptMetadata | undefined;\n if (!scriptMetadata) {\n Log.error(`[htmlBundleScriptPlugin:onLoad] Script metadata for the path \"${arguments_.path}\" not found.\"`);\n return;\n }\n\n const clone = app.clone(scriptMetadata);\n await app.rebase(clone, outFileAbs);\n const contents = await app.stringify(clone);\n\n return { contents, resolveDir: dirname(outFileAbs), loader: \"js\" };\n });\n },\n };\n}\n","import * as esbuild from \"esbuild\";\n\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { valueOrError, type ValueOrError } from \"../../utilities/value-or-error.ts\";\nimport { loaderPlugin } from \"./esbuild-plugin.ts\";\n\nimport type { App } from \"@staticbolt/core\";\n\nconst bundleFunction = valueOrError(esbuild.build);\n\ninterface Options {\n contents: string;\n entryPoint: string;\n outfile: string;\n iife: boolean;\n isExternalCheck: (strings: string) => boolean;\n}\n\nexport async function bundleScriptWithEsbuild(this: App, options: Options): Promise<ValueOrError<string>> {\n const { contents, entryPoint, outfile, iife, isExternalCheck } = options;\n\n const root = this.root;\n\n const [bundleResult, error] = await bundleFunction({\n stdin: {\n contents,\n sourcefile: join(root, entryPoint),\n resolveDir: join(root, dirname(entryPoint)),\n },\n outfile,\n absWorkingDir: root,\n bundle: true,\n minify: false,\n treeShaking: true,\n write: false,\n platform: \"browser\",\n packages: \"bundle\",\n format: iife ? \"iife\" : \"esm\",\n target: \"es2022\",\n legalComments: \"none\",\n logLevel: \"silent\",\n charset: \"utf8\",\n plugins: [loaderPlugin.call(this, outfile, isExternalCheck)],\n });\n\n if (error) {\n return [null, error];\n }\n\n const outCode = bundleResult?.outputFiles?.[0].text;\n\n if (typeof outCode !== \"string\") {\n return [null, new Error(`Failed to bundle the script tag \"${entryPoint}\"`)];\n }\n\n return [outCode, null];\n}\n","import { isScriptType } from \"../../helpers/is-script-type.ts\";\nimport { checkFileExists, isEmptyElement, isJavaScript } from \"../../helpers/lsp-checks.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { isHtmlMetadata, isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join, isPathMatch, normalize, parsePatterns, relative, replaceExtension } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { bundleScriptWithEsbuild } from \"./esbuild-bundle.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlBundleScriptOptions {\n /**\n * Glob patterns for modules that should be treated as external (excluded from bundling).\n *\n * Applied when the `externalsAttribute` is not set on the script tag.\n *\n * @default [ ]\n */\n externals?: string[];\n\n /**\n * Glob patterns that exempt modules from being treated as external, even if they match `externals`.\n *\n * Applied when the `externalsExcludeAttribute` is not set on the script tag.\n *\n * @default [ ]\n */\n externalsExclude?: string[];\n\n /**\n * The HTML attribute name that enables bundling on a script tag.\n *\n * @default \"bundle\"\n */\n bundleAttribute?: string;\n\n /**\n * The HTML attribute name that specifies the output file path for the bundled script.\n *\n * The attribute value is always resolved relative to the output directory, regardless of where the HTML file lives.\n *\n * @default \"bundle-out\"\n */\n bundleOutAttribute?: string;\n\n /**\n * The HTML attribute name that specifies which modules to treat as external.\n *\n * Accepts a semicolon-separated list of glob patterns.\n *\n * @default \"bundle-externals\"\n */\n externalsAttribute?: string;\n\n /**\n * The HTML attribute name that specifies which modules to exempt from being external.\n *\n * Accepts a semicolon-separated list of glob patterns.\n *\n * @default \"bundle-externals-exclude\"\n */\n externalsExcludeAttribute?: string;\n\n /**\n * The HTML attribute name that switches the bundle output format from ESM to IIFE.\n *\n * The attribute is a boolean flag; its value is ignored.\n *\n * @default \"iife\"\n */\n iifeAttribute?: string;\n}\n\n/**\n * Bundles script tags in HTML files with esbuild. Opt-in per tag.\n *\n * Attributes (names configurable via HtmlBundleScriptOptions):\n *\n * - \"bundle\": bundle this tag.\n * - \"bundle-out\": output path, resolved from the output directory, not from the HTML file.\n * - \"bundle-externals\" / \"bundle-externals-exclude\": semicolon-separated globs, override the plugin defaults for this tag.\n * - \"iife\": emit an IIFE instead of ESM.\n *\n * Without \"bundle-out\", an inline script is bundled in place and a \"src\" script is written to \"{filename}.bundle.js\" next to the\n * original. With it, \"src\" is pointed at the output path and inline content is cleared.\n *\n * Notes:\n *\n * - Bundling only runs in production; in dev the attributes are just stripped. They never reach the output either way.\n * - If the target output path is already bundled, the work is skipped and \"src\" is simply pointed at it.\n * - \"iife\" only changes the esbuild format; the tag's \"type\" is untouched, so remove \"type=module\" yourself if needed.\n */\nexport function htmlBundleScriptPlugin(options: HtmlBundleScriptOptions = {}): Plugin {\n const defaultExternal = options.externals ?? [\"**/node_modules/**\"];\n const defaultExternalExclude = options.externalsExclude ?? [];\n\n const bundleAttribute = options.bundleAttribute ?? \"bundle\";\n const bundleOutAttribute = options.bundleOutAttribute ?? \"bundle-out\";\n const externalsAttribute = options.externalsAttribute ?? \"bundle-externals\";\n const externalsExcludeAttribute = options.externalsExcludeAttribute ?? \"bundle-externals-exclude\";\n const iifeAttribute = options.iifeAttribute ?? \"iife\";\n\n const query = `script[${bundleAttribute}]`;\n\n const printFmtError = PrintFormattedError.create({ function: htmlBundleScriptPlugin });\n\n return {\n name: \"html-bundle-script\",\n\n // Note: the bundle-out attribute is intentionally NOT registered via sourcesProvider.\n // Its value is relative to the output root, while the sources resolve/rebase pipeline\n // assumes file-relative paths and would corrupt it.\n\n async transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const filePath = metadata.filePath;\n\n const scripts = metadata.ast.querySelectorAll(query);\n\n for (const node of scripts) {\n const bundleOutValue = node.getAttribute(bundleOutAttribute);\n // bundle-out is always resolved from the output root, e.g. \"./accordion.js\" lands at \"<outdir>/accordion.js\".\n const bundleOut = bundleOutValue ? normalize(bundleOutValue.replace(/^\\/+/, \"\")) : null;\n const externalsAttributeValue = node.getAttribute(externalsAttribute);\n const externalsExcludeAttributeValue = node.getAttribute(externalsExcludeAttribute);\n const isIife = node.hasAttribute(iifeAttribute);\n\n node.removeAttribute(bundleAttribute);\n node.removeAttribute(bundleOutAttribute);\n node.removeAttribute(externalsAttribute);\n node.removeAttribute(externalsExcludeAttribute);\n node.removeAttribute(iifeAttribute);\n\n const scriptType = node.getAttribute(\"type\");\n if (!isScriptType(scriptType)) continue;\n\n if (!this.production) continue;\n\n // Resolve whether the script is src-based or inline.\n const scriptSource = node.getAttribute(\"src\");\n const scriptMetadataID = node.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n const scriptMetadata = scriptMetadataID ? metadata.scriptsMetadataList.get(scriptMetadataID) : undefined;\n const hasContent = !scriptSource && Boolean(scriptMetadata);\n\n if (!scriptSource && !hasContent) {\n printFmtError('The script tag does not have a \"src\" attribute or code content', { node, filePath });\n continue;\n }\n\n // An inline script with no explicit output path stays inlined after bundling.\n const isInlined = !bundleOut && hasContent;\n\n // Resolve externals from the tag attributes, falling back to plugin-level defaults.\n const externals = parsePatterns(externalsAttributeValue) ?? defaultExternal;\n const externalsIgnore = parsePatterns(externalsExcludeAttributeValue) ?? defaultExternalExclude;\n\n let entryPoint = \"\";\n let outfile = \"\";\n let contents = \"\";\n\n // hasContent and scriptSource are mutually exclusive: hasContent requires !scriptSource.\n if (hasContent) {\n // Default output path is the HTML file itself when staying inline,\n // or the bundleOut path when writing to a separate file.\n outfile = bundleOut ?? filePath;\n\n // The bundled result will replace the tag content in place.\n if (isInlined) {\n entryPoint = metadata.filePath;\n contents = await this.stringify(scriptMetadata!);\n }\n\n // The bundled result is written to a separate file; clear the inline content.\n else {\n node.textContent = \"\";\n\n // Already bundled\n const existingMetadata = this.findMetadata({ filePath: outfile });\n if (existingMetadata) {\n this.log.info(`The entry point \"${entryPoint}\" is already bundled in \"${outfile}\", skipping...`);\n\n // Remove the old inline metadata entry and point the tag to the bundled file.\n if (scriptMetadataID) {\n metadata.scriptsMetadataList.delete(scriptMetadataID);\n }\n\n node.setAttribute(\"src\", relative(dirname(filePath), outfile));\n continue;\n }\n\n // entryPoint is the output file because the content will be rebased to it.\n entryPoint = outfile;\n\n // Rebase imports to be relative to the output file location.\n const clone = this.clone(scriptMetadata!);\n await this.rebase(clone, join(this.root, outfile));\n\n contents = await this.stringify(clone);\n }\n }\n\n // No content, so the script is src-based.\n else if (scriptSource) {\n // Default output path is \"{original-filename}.bundle.js\" next to the original file when no explicit path is given.\n outfile = bundleOut ?? normalize(replaceExtension(join(dirname(filePath), scriptSource), \".bundle.js\"));\n\n // entryPoint is the output file because the content will be rebased to it.\n entryPoint = outfile;\n\n if (this.findMetadata({ filePath: outfile })) {\n this.log.debug(`The entry point \"${entryPoint}\" is already bundled in \"${outfile}\", skipping...`);\n node.setAttribute(\"src\", relative(dirname(filePath), outfile));\n continue;\n }\n\n const sourceScriptMetadata = this.findMetadata({ filePath: join(dirname(filePath), scriptSource) });\n if (!isScriptMetadata(sourceScriptMetadata)) {\n printFmtError(`Script metadata for the path \"${entryPoint}\" not found`, { node, filePath });\n continue;\n }\n\n // Rebase imports to be relative to the output file location.\n const clone = this.clone(sourceScriptMetadata);\n await this.rebase(clone, join(this.root, outfile));\n\n contents = await this.stringify(clone);\n }\n\n // Build the external-check predicate from the resolved patterns.\n const isExternalCheck = (string: string) => {\n return isPathMatch(string, { include: externals, ignore: externalsIgnore, root: this.root });\n };\n\n const [bundleString, bundleError] = await bundleScriptWithEsbuild.call(this, {\n contents,\n entryPoint,\n outfile,\n iife: isIife,\n isExternalCheck,\n });\n\n if (bundleError) {\n printFmtError(`Failed to bundle the entry point \"${entryPoint}\"`, bundleError, { node, filePath });\n continue;\n }\n\n // Load the bundled output back as script metadata so the build system tracks it.\n const newMetadataPath = normalize(isInlined ? filePath : outfile);\n const newScriptMetadata = await this.load(newMetadataPath, { code: bundleString, type: \"js\" });\n if (!isScriptMetadata(newScriptMetadata)) {\n printFmtError(\"Failed to load the bundled script\", { node, filePath });\n continue;\n }\n\n if (isInlined) {\n if (!scriptMetadataID) {\n printFmtError(\"Missing script metadata ID\", { node, filePath });\n continue;\n }\n\n // Replace the old inline metadata entry with the bundled version.\n metadata.scriptsMetadataList.set(scriptMetadataID, newScriptMetadata);\n newScriptMetadata.module = scriptType === \"module\";\n continue;\n }\n\n // Remove the old inline metadata entry and point the tag to the bundled file.\n if (scriptMetadataID) {\n metadata.scriptsMetadataList.delete(scriptMetadataID);\n }\n\n node.setAttribute(\"src\", relative(dirname(filePath), outfile));\n node.textContent = \"\";\n\n this.addMetadata(newScriptMetadata);\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: \"script\",\n description: `Adds the \\`${bundleAttribute}\\` attribute and its options, which bundle the script and its imports with esbuild at build time.`,\n attributes: [\n {\n name: bundleAttribute,\n description: \"Enable script bundling.\",\n valueSet: \"v\",\n },\n {\n name: bundleOutAttribute,\n description:\n \"Specify the output path for bundled scripts relative to the output directory, regardless of the HTML file's location.\" +\n \"\\nIf the script has a `src` attribute, the output path will default to `{filename}.bundle.js` next to the original file.\" +\n \"\\nIf the script has no `src` attribute, the default behavior is to keep the script inline.\",\n },\n {\n name: externalsAttribute,\n description:\n \"Glob patterns list to treat as external during bundling. (semicolon-separated)\" +\n `\\n\\nDefaults to \"${defaultExternal.join(\";\")}\".`,\n },\n {\n name: externalsExcludeAttribute,\n description:\n \"Glob patterns that exempt files from being treated as external, even if they match `externals`. (semicolon-separated)\" +\n `\\n\\nDefaults to \"${defaultExternalExclude.join(\";\")}\".`,\n },\n {\n name: iifeAttribute,\n description:\n \"Emit the bundle as an IIFE instead of ESM.\" +\n \"\\n\\nOnly changes the output format; the tag's `type` attribute is left as it is.\",\n valueSet: \"v\",\n },\n ],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const scripts = document.select(\"script\");\n\n for (const element of scripts) {\n const bundle = element.attribute(bundleAttribute);\n if (!bundle) continue;\n\n if (!isJavaScript(element)) {\n report.warn(bundle.nameRange, `\"${bundleAttribute}\" does nothing on a script that is not JavaScript`);\n continue;\n }\n\n const source = element.attribute(\"src\");\n if (!source?.value && isEmptyElement(element, document)) {\n report.error(bundle.nameRange, `\"${bundleAttribute}\" needs a \"src\" or some code in the script to bundle`);\n continue;\n }\n\n if (source) {\n checkFileExists(source, document, report);\n }\n }\n },\n };\n}\n","/** What an `@import` wraps the imported sheet in. `layer` is `\"\"` for an anonymous `layer`. */\nexport interface ImportConditions {\n layer?: string;\n supports?: string;\n media?: string;\n}\n\nexport interface ImportPrelude extends ImportConditions {\n /** The URL as written, without quotes or `url()` and with escapes resolved. */\n url: string;\n\n /** Offsets of the URL inside the params, so it can be swapped in place. */\n urlStart: number;\n urlEnd: number;\n\n /** The `url(...)` or quoted string token as written. */\n urlToken: string;\n}\n\nconst isSpace = (char: string | undefined) => char === \" \" || char === \"\\t\" || char === \"\\n\" || char === \"\\r\" || char === \"\\f\";\n\nfunction skipSpace(text: string, index: number): number {\n while (index < text.length && isSpace(text[index])) index++;\n return index;\n}\n\nfunction skipSpaceAndComments(text: string, index: number): number {\n for (;;) {\n index = skipSpace(text, index);\n if (!text.startsWith(\"/*\", index)) return index;\n\n const end = text.indexOf(\"*/\", index + 2);\n if (end === -1) return text.length;\n\n index = end + 2;\n }\n}\n\n/** Index just past the closing quote of the string starting at `index`, or `-1` when it never closes. */\nfunction skipString(text: string, index: number): number {\n const quote = text[index];\n\n for (let current = index + 1; current < text.length; current++) {\n const char = text[current];\n if (char === \"\\\\\") {\n current++;\n continue;\n }\n\n if (char === quote) return current + 1;\n if (char === \"\\n\") return -1;\n }\n\n return -1;\n}\n\n/** Index just past the `)` matching the `(` at `index`, or `-1` when it never closes. */\nfunction skipParens(text: string, index: number): number {\n let depth = 0;\n\n for (let current = index; current < text.length; current++) {\n const char = text[current];\n\n if (char === '\"' || char === \"'\") {\n const end = skipString(text, current);\n if (end === -1) return -1;\n\n current = end - 1;\n continue;\n }\n\n if (char === \"(\") depth++;\n else if (char === \")\" && --depth === 0) return current + 1;\n }\n\n return -1;\n}\n\nconst escapeRe = /\\\\(?:([\\da-f]{1,6})\\s?|(.))/gi;\n\nfunction unescapeCss(value: string): string {\n if (!value.includes(\"\\\\\")) return value;\n\n return value.replace(escapeRe, (_, hex: string | undefined, char: string) =>\n hex ? String.fromCodePoint(Number.parseInt(hex, 16)) : char\n );\n}\n\n/**\n * Parses the params of an `@import` rule: the URL followed by its `layer`, `supports()` and media conditions.\n *\n * Returns `undefined` when no URL can be found or a condition is given twice.\n */\nexport function parseImportPrelude(text: string): ImportPrelude | undefined {\n const tokenStart = skipSpaceAndComments(text, 0);\n\n let urlStart: number;\n let urlEnd: number;\n let tokenEnd: number;\n\n const first = text[tokenStart];\n\n if (first === '\"' || first === \"'\") {\n tokenEnd = skipString(text, tokenStart);\n if (tokenEnd === -1) return;\n\n urlStart = tokenStart + 1;\n urlEnd = tokenEnd - 1;\n }\n //\n else if (text.slice(tokenStart, tokenStart + 4).toLowerCase() === \"url(\") {\n const contentStart = skipSpace(text, tokenStart + 4);\n const quote = text[contentStart];\n let close: number;\n\n if (quote === '\"' || quote === \"'\") {\n const stringEnd = skipString(text, contentStart);\n if (stringEnd === -1) return;\n\n close = skipSpace(text, stringEnd);\n if (text[close] !== \")\") return;\n\n urlStart = contentStart + 1;\n urlEnd = stringEnd - 1;\n }\n //\n else {\n close = text.indexOf(\")\", contentStart);\n if (close === -1) return;\n\n urlStart = contentStart;\n urlEnd = close;\n while (urlEnd > urlStart && isSpace(text[urlEnd - 1])) urlEnd--;\n }\n\n tokenEnd = close + 1;\n }\n //\n else {\n return;\n }\n\n const prelude: ImportPrelude = {\n url: unescapeCss(text.slice(urlStart, urlEnd)),\n urlStart,\n urlEnd,\n urlToken: text.slice(tokenStart, tokenEnd),\n };\n\n let position = tokenEnd;\n\n for (;;) {\n position = skipSpaceAndComments(text, position);\n if (position >= text.length) break;\n\n const rest = text.slice(position);\n\n if (/^layer(?=\\(|\\s|$)/i.test(rest)) {\n if (prelude.layer !== undefined) return;\n\n if (rest[5] === \"(\") {\n const end = skipParens(text, position + 5);\n if (end === -1) return;\n\n prelude.layer = text.slice(position + 6, end - 1).trim();\n position = end;\n } else {\n prelude.layer = \"\";\n position += 5;\n }\n\n continue;\n }\n\n if (/^supports\\(/i.test(rest)) {\n if (prelude.supports !== undefined) return;\n\n const end = skipParens(text, position + 8);\n if (end === -1) return;\n\n prelude.supports = text.slice(position + 9, end - 1).trim();\n position = end;\n continue;\n }\n\n prelude.media = rest.trim();\n break;\n }\n\n return prelude;\n}\n\nexport function hasConditions({ layer, supports, media }: ImportConditions): boolean {\n return layer !== undefined || supports !== undefined || media !== undefined;\n}\n\n/** Prints conditions back the way an `@import` prelude takes them: `layer(name) supports(condition) media`. */\nexport function formatImportConditions({ layer, supports, media }: ImportConditions): string {\n const parts: string[] = [];\n\n if (layer !== undefined) parts.push(layer ? `layer(${layer})` : \"layer\");\n if (supports !== undefined) parts.push(`supports(${supports})`);\n if (media !== undefined) parts.push(media);\n\n return parts.join(\" \");\n}\n","import postcss from \"postcss\";\n\nimport { valueOrError } from \"../utilities/value-or-error.ts\";\n\nfunction parseCssUnsafe(css: string, options?: postcss.ProcessOptions) {\n return postcss.parse(css, options ?? {});\n}\n\n/** Parse CSS string and return the root node */\nconst parseCss = valueOrError(parseCssUnsafe);\n\nexport { parseCss };\n","import { parseCss } from \"../../../parsers/css-parser.ts\";\nimport { METADATA_TYPES, type StyleMetadata } from \"../../../types/metadata.ts\";\nimport { join } from \"../../../utilities/path.ts\";\n\nimport type { ValueOrError } from \"../../../utilities/value-or-error.ts\";\nimport type { App } from \"@staticbolt/core\";\n\nexport function styleLoader(this: App, relativePath: string, code: string): ValueOrError<StyleMetadata> {\n const absFilePath = join(this.root, relativePath);\n\n const [cssRoot, parseError] = parseCss(code, { from: absFilePath });\n if (parseError) {\n return [null, parseError];\n }\n\n const cssMetadata: StyleMetadata = {\n type: METADATA_TYPES.CSS,\n ast: cssRoot,\n filePath: relativePath,\n id: relativePath,\n directDependencies: new Set(),\n };\n\n return [cssMetadata, null];\n}\n","import postcss from \"postcss\";\n\nimport {\n formatImportConditions,\n hasConditions,\n parseImportPrelude,\n type ImportConditions,\n type ImportPrelude,\n} from \"../ast-utilities/postcss-utils/import-prelude.ts\";\nimport { styleLoader } from \"../plugins/core-plugins/style-metadata/style-loader.ts\";\nimport { METADATA_TYPES } from \"../types/metadata.ts\";\nimport { splitHtmlLink } from \"../utilities/html-links.ts\";\nimport { isStyleMetadata } from \"../utilities/metadata-utilities.ts\";\nimport { join, relative } from \"../utilities/path.ts\";\n\nimport type { App, StyleMetadata } from \"@staticbolt/core\";\nimport type { AtRule, ChildNode } from \"postcss\";\n\nexport interface StyleBundleDiagnostic {\n level: \"error\" | \"warning\";\n message: string;\n\n /** The rule the message is about, in the file it was written in. */\n node: AtRule;\n\n /** The file the rule was written in, relative to the project root. */\n filePath: string;\n}\n\n/** One stylesheet pulled into the bundle, under the conditions of every `@import` on the way to it. */\ninterface Occurrence {\n metadata: StyleMetadata;\n absolutePath: string;\n\n /** Conditions of the imports leading here, outermost first; levels without conditions are left out. */\n chain: ImportConditions[];\n\n /** Same file under the same conditions is the same occurrence. */\n key: string;\n\n /** The `@import` that pulled the file in; the entry has none. */\n importNode?: AtRule;\n\n /** Top-level nodes of the copy that ends up in the bundle, by their index in the file. Made on first use. */\n nodes?: ChildNode[];\n}\n\n/** A piece of the bundle in output order, as a position in an occurrence rather than a node, so nothing is taken before cloning. */\ntype Entry =\n | { kind: \"charset\"; occurrence: Occurrence; index: number }\n | { kind: \"layer\"; occurrence: Occurrence; index: number }\n | { kind: \"import\"; occurrence: Occurrence; index: number; prelude: ImportPrelude; chain: ImportConditions[] }\n | { kind: \"nodes\"; occurrence: Occurrence; indices: number[] };\n\n/** What becomes of an `@import`. */\ntype ImportPlan =\n | { action: \"inline\"; child: Occurrence }\n | { action: \"keep\"; prelude: ImportPrelude; chain: ImportConditions[] }\n | { action: \"drop\" }\n | { action: \"leave\" };\n\nconst externalUrlRe = /^(?:[a-z][\\d+.a-z-]*:|\\/\\/)/i;\n\n/**\n * Inlines the `@import` tree of a stylesheet in place, the way a browser would have loaded it:\n *\n * - Imported files come from the build when they are part of it, so what other plugins did to them is kept, and from disk\n * otherwise. Their `url()` references are rebased onto the bundle's final location.\n * - `layer()`, `supports()` and media conditions wrap the imported rules; nested imports nest their conditions.\n * - A file imported more than once under the same conditions is kept where it was imported last, which is where a browser's cascade\n * ends up. Cyclic imports are cut.\n * - Imports that cannot be inlined (other origins, `data:`, files that fail to resolve or load) are kept and hoisted to the top\n * with their conditions folded in, after `@charset` and any `@layer` statements that came before them.\n * - Misplaced imports (after other rules) are reported and left alone, like a browser ignores them.\n */\nexport class StyleBundler {\n readonly #app: App;\n\n /** Stylesheets outside the build, loaded from disk once and cloned per use. `undefined` marks a file that failed to load. */\n readonly #loaded = new Map<string, StyleMetadata | undefined>();\n\n constructor(app: App) {\n this.#app = app;\n }\n\n /**\n * Bundles `metadata.ast` in place.\n *\n * @param bundleAbsolutePath Where the bundle ends up, which imported `url()` references are rebased onto.\n */\n async bundle(metadata: StyleMetadata, bundleAbsolutePath: string): Promise<StyleBundleDiagnostic[]> {\n const run = new BundleRun(this.#app, this.#loaded, bundleAbsolutePath);\n return await run.bundle(metadata);\n }\n}\n\nclass BundleRun {\n readonly #app: App;\n readonly #loaded: Map<string, StyleMetadata | undefined>;\n readonly #bundleAbsolutePath: string;\n\n readonly #entries: Entry[] = [];\n readonly #occurrences: Occurrence[] = [];\n readonly #diagnostics: StyleBundleDiagnostic[] = [];\n readonly #reportedNodes = new Set<AtRule>();\n\n #charsetParams: string | undefined;\n #hasKeptImports = false;\n\n constructor(app: App, loaded: Map<string, StyleMetadata | undefined>, bundleAbsolutePath: string) {\n this.#app = app;\n this.#loaded = loaded;\n this.#bundleAbsolutePath = bundleAbsolutePath;\n }\n\n async bundle(metadata: StyleMetadata): Promise<StyleBundleDiagnostic[]> {\n const absolutePath = join(this.#app.root, metadata.filePath);\n const entry: Occurrence = { metadata, absolutePath, chain: [], key: absolutePath, nodes: metadata.ast.nodes.slice() };\n\n await this.#visit(entry, new Set([absolutePath]));\n await this.#assemble(entry);\n\n return this.#diagnostics;\n }\n\n // --- Planning: walk the import tree on the build's own ASTs and lay the bundle out as entries ---\n\n async #visit(occurrence: Occurrence, ancestors: Set<string>) {\n const nodes = occurrence.metadata.ast.nodes;\n const filePath = occurrence.metadata.id;\n\n /** Indices of consecutive nodes that stay as they are, flushed as one entry whenever something else comes between them. */\n let run: number[] = [];\n\n const flushRun = () => {\n if (run.length === 0) return;\n this.#entries.push({ kind: \"nodes\", occurrence, indices: run });\n run = [];\n };\n\n /** Only comments, `@charset`, `@layer` statements and other imports may come before an `@import`. */\n let isInPrefix = true;\n\n for (const [index, node] of nodes.entries()) {\n if (node.type === \"comment\") {\n run.push(index);\n continue;\n }\n\n const atRule = node.type === \"atrule\" ? node : undefined;\n const name = atRule?.name.toLowerCase();\n\n if (atRule && name === \"charset\") {\n if (index === 0) {\n this.#noteCharset(atRule, filePath);\n this.#entries.push({ kind: \"charset\", occurrence, index });\n } else {\n this.#warn(atRule, filePath, \"@charset must precede all other statements\");\n }\n\n continue;\n }\n\n if (atRule && name === \"layer\" && isInPrefix && !atRule.nodes) {\n if (occurrence.chain.length === 0) {\n flushRun();\n this.#entries.push({ kind: \"layer\", occurrence, index });\n } else {\n run.push(index);\n }\n\n continue;\n }\n\n if (!atRule || name !== \"import\") {\n isInPrefix = false;\n run.push(index);\n continue;\n }\n\n const plan = await this.#planImport(atRule, occurrence, ancestors, isInPrefix);\n\n switch (plan.action) {\n case \"leave\": {\n run.push(index);\n break;\n }\n\n case \"drop\": {\n break;\n }\n\n case \"keep\": {\n flushRun();\n this.#entries.push({ kind: \"import\", occurrence, index, prelude: plan.prelude, chain: plan.chain });\n this.#hasKeptImports = true;\n break;\n }\n\n case \"inline\": {\n flushRun();\n this.#occurrences.push(plan.child);\n await this.#visit(plan.child, new Set(ancestors).add(plan.child.absolutePath));\n break;\n }\n }\n }\n\n flushRun();\n }\n\n /**\n * Decides what becomes of an `@import`: inlined, kept as an import (hoisted with its conditions folded in, so the browser\n * fetches it the way it did before), dropped (a cycle) or left where it is as a regular node (not valid where it stands).\n */\n async #planImport(node: AtRule, occurrence: Occurrence, ancestors: Set<string>, isInPrefix: boolean): Promise<ImportPlan> {\n const filePath = occurrence.metadata.id;\n\n const prelude = parseImportPrelude(node.params);\n if (!prelude) {\n this.#warn(node, filePath, `Unable to find the URL in '${node.toString()}'`);\n return { action: \"leave\" };\n }\n\n if (node.nodes) {\n this.#warn(node, filePath, \"It looks like the @import statement was not ended correctly: child nodes are attached to it\");\n return { action: \"leave\" };\n }\n\n if (!isInPrefix) {\n this.#warn(node, filePath, \"@import must precede all other statements (besides @charset and empty @layer)\");\n return { action: \"leave\" };\n }\n\n const chain = hasConditions(prelude) ? [...occurrence.chain, prelude] : occurrence.chain;\n const keep: ImportPlan = { action: \"keep\", prelude, chain };\n\n if (externalUrlRe.test(prelude.url)) {\n return keep;\n }\n\n const absolutePath = this.#resolve(prelude.url, occurrence.absolutePath);\n if (!absolutePath) {\n this.#error(node, filePath, `Failed to resolve \"${prelude.url}\"`);\n return keep;\n }\n\n if (ancestors.has(absolutePath)) {\n return { action: \"drop\" };\n }\n\n const metadata = await this.#load(absolutePath);\n if (!metadata) {\n this.#error(node, filePath, `Failed to load \"${prelude.url}\" as a stylesheet`);\n return keep;\n }\n\n const key = [absolutePath, ...chain.map(level => formatImportConditions(level))].join(\"\\0\");\n\n return { action: \"inline\", child: { metadata, absolutePath, chain, key, importNode: node } };\n }\n\n #resolve(url: string, importerAbsolutePath: string): string | undefined {\n const [link] = splitHtmlLink(url);\n\n // Root-relative, as a browser would resolve it against the site root\n if (link.startsWith(\"/\")) {\n return this.#app.resolver.findFile(join(this.#app.root, link));\n }\n\n const resolved = this.#app.resolver.resolve(link, importerAbsolutePath);\n if (!resolved?.exists) return;\n\n return resolved.path;\n }\n\n async #load(absolutePath: string): Promise<StyleMetadata | undefined> {\n const relativePath = relative(this.#app.root, absolutePath);\n\n const inBuild =\n this.#app.findMetadata<StyleMetadata>({ type: METADATA_TYPES.CSS, filePath: relativePath }) ??\n this.#app.findMetadata<StyleMetadata>({ type: METADATA_TYPES.CSS, id: relativePath });\n\n if (inBuild) return inBuild;\n\n if (!this.#loaded.has(absolutePath)) {\n this.#loaded.set(absolutePath, await this.#loadFromDisk(absolutePath, relativePath));\n }\n\n return this.#loaded.get(absolutePath);\n }\n\n async #loadFromDisk(absolutePath: string, relativePath: string): Promise<StyleMetadata | undefined> {\n const content = await this.#app.read(absolutePath);\n if (content === undefined) return;\n\n // The pipeline has nothing to load from an empty file; here it is simply a sheet with no rules\n if (content.trim() === \"\") {\n return styleLoader.call(this.#app, relativePath, content)[0] ?? undefined;\n }\n\n const metadata = await this.#app.load(relativePath, { code: content });\n if (isStyleMetadata(metadata)) return metadata;\n }\n\n #noteCharset(node: AtRule, filePath: string) {\n if (this.#charsetParams === undefined) {\n this.#charsetParams = node.params;\n return;\n }\n\n if (node.params.toLowerCase() !== this.#charsetParams.toLowerCase()) {\n this.#warn(node, filePath, `Incompatible @charset statements: ${node.params} is dropped for ${this.#charsetParams}`);\n }\n }\n\n #warn(node: AtRule, filePath: string, message: string) {\n this.#report(\"warning\", node, filePath, message);\n }\n\n #error(node: AtRule, filePath: string, message: string) {\n this.#report(\"error\", node, filePath, message);\n }\n\n #report(level: StyleBundleDiagnostic[\"level\"], node: AtRule, filePath: string, message: string) {\n if (this.#reportedNodes.has(node)) return;\n this.#reportedNodes.add(node);\n this.#diagnostics.push({ level, message, node, filePath });\n }\n\n // --- Assembly: clone what is kept, rebase it, and rebuild the entry root from the entries ---\n\n async #assemble(entry: Occurrence) {\n const root = entry.metadata.ast;\n\n const lastByKey = new Map<string, Occurrence>();\n for (const occurrence of this.#occurrences) {\n lastByKey.set(occurrence.key, occurrence);\n }\n\n let charset: AtRule | undefined;\n const prefix: ChildNode[] = [];\n const body: ChildNode[] = [];\n const started = new Set<Occurrence>();\n\n for (const item of this.#entries) {\n const { occurrence } = item;\n\n if (occurrence !== entry && lastByKey.get(occurrence.key) !== occurrence) continue;\n\n const nodes = await this.#nodesOf(occurrence);\n\n switch (item.kind) {\n case \"charset\": {\n charset ??= nodes[item.index] as AtRule;\n break;\n }\n\n case \"layer\": {\n (this.#hasKeptImports ? prefix : body).push(nodes[item.index]);\n break;\n }\n\n case \"import\": {\n const node = nodes[item.index] as AtRule;\n node.params = keptImportPrelude(node.params, item.prelude, item.chain);\n prefix.push(node);\n break;\n }\n\n case \"nodes\": {\n const run = item.indices.map(index => nodes[index]);\n\n // The first piece of a file sits where its `@import` was, so it takes over the whitespace before it\n if (occurrence.importNode && !started.has(occurrence)) {\n const isBundleStart = !charset && prefix.length === 0 && body.length === 0;\n run[0].raws.before = isBundleStart ? \"\" : occurrence.importNode.raws.before || \"\\n\";\n }\n\n started.add(occurrence);\n body.push(...wrapInConditions(run, occurrence.chain));\n break;\n }\n }\n }\n\n if (charset) prefix.unshift(charset);\n\n root.removeAll();\n root.append([...prefix, ...body]);\n }\n\n async #nodesOf(occurrence: Occurrence): Promise<ChildNode[]> {\n if (occurrence.nodes) return occurrence.nodes;\n\n const clone = this.#app.clone(occurrence.metadata);\n await this.#app.rebase(clone, this.#bundleAbsolutePath);\n\n occurrence.nodes = clone.ast.nodes.slice();\n return occurrence.nodes;\n }\n}\n\n/** Nests `nodes` in `@media`, `@supports` and `@layer` rules for every level of the chain, outermost level outermost. */\nfunction wrapInConditions(nodes: ChildNode[], chain: ImportConditions[]): ChildNode[] {\n if (chain.length === 0) return nodes;\n\n const before = nodes[0].raws.before;\n nodes[0].raws.before = \"\\n\";\n\n let wrapped = nodes;\n\n for (let level = chain.length - 1; level >= 0; level--) {\n const { layer, supports, media } = chain[level];\n\n const wrappers: AtRule[] = [];\n if (layer !== undefined) wrappers.push(postcss.atRule({ name: \"layer\", params: layer }));\n if (supports !== undefined) wrappers.push(postcss.atRule({ name: \"supports\", params: `(${supports})` }));\n if (media !== undefined) wrappers.push(postcss.atRule({ name: \"media\", params: media }));\n\n for (const wrapper of wrappers) {\n wrapper.raws = { before: \"\\n\", between: \" \", after: \"\\n\" };\n wrapper.append(wrapped);\n wrapped = [wrapper];\n }\n }\n\n wrapped[0].raws.before = before;\n\n return wrapped;\n}\n\n/**\n * The prelude of an import kept in the bundle, with the conditions of the imports leading to it folded in. A single level fits in\n * one prelude; more than one nests `data:` stylesheets, each importing the next under its own conditions, outermost first.\n */\nfunction keptImportPrelude(text: string, prelude: ImportPrelude, chain: ImportConditions[]): string {\n if (chain.length === 0 || (chain.length === 1 && chain[0] === prelude)) return text;\n\n // Rebasing may have rewritten the URL since the prelude was parsed\n const urlToken = parseImportPrelude(text)?.urlToken ?? prelude.urlToken;\n\n let result = `${urlToken} ${formatImportConditions(chain.at(-1)!)}`;\n\n for (let level = chain.length - 2; level >= 0; level--) {\n // eslint-disable-next-line unicorn/prefer-uint8array-base64 -- `Uint8Array#toBase64` is not available on the Node versions supported\n const stylesheet = Buffer.from(`@import ${result};`).toString(\"base64\");\n result = `'data:text/css;base64,${stylesheet}' ${formatImportConditions(chain[level])}`;\n }\n\n return result;\n}\n","import { StyleBundler } from \"../../helpers/style-bundler.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata, isStyleMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { printFmtError } from \"../../utilities/print-formatted-error.ts\";\n\nimport type { Plugin, StyleMetadata } from \"@staticbolt/core\";\n\nexport interface HtmlBundleStyleOptions {\n /**\n * The HTML attribute name that enables bundling on a link[stylesheet] or style tag.\n *\n * @default \"bundle\"\n */\n bundleAttribute?: string;\n}\n\n/**\n * Inlines the \"@import\" tree of a stylesheet, so the tag ends up self-contained. Opt-in per tag through the \"bundle\" attribute\n * (configurable via HtmlBundleStyleOptions) on a \"<link rel=stylesheet>\" or a \"<style>\" tag.\n *\n * Bundling happens in place: a \"<style>\" tag gets the resolved CSS as its content, and a linked file is rewritten with its\n * imports inlined while \"href\" stays as it is.\n *\n * Notes:\n *\n * - Production only. In development nothing runs and the \"bundle\" attribute is left on the tag.\n * - \"<link rel=preload as=style>\" is always bundled, with or without the attribute, since a preloaded stylesheet has to carry\n * everything it needs.\n * - A linked stylesheet is bundled once even when several pages link to it; they share the same file.\n * - Imports resolve the way every other source does: relative paths, path aliases and packages, through the build's resolver.\n * - Imported files are pulled from the build (so transforms other plugins made are included) and only read from disk when they are\n * not part of it. They stay in the output as separate files, now unreferenced. Their \"url()\" references are rebased onto the\n * bundle's location.\n * - Conditions (\"layer\", \"supports()\", media) wrap the imported rules, a file imported twice under the same conditions is kept\n * where it was imported last, as in a browser, and imports from other origins are hoisted to the top.\n */\nexport function htmlBundleStylePlugin(options: HtmlBundleStyleOptions = {}): Plugin {\n const bundleAttribute = options.bundleAttribute ?? \"bundle\";\n const query = `link[rel=\"stylesheet\"][${bundleAttribute}], link[rel=\"preload\"][as=\"style\"], style[${bundleAttribute}]`;\n\n const alreadyBundledIds = new Set<string>();\n\n let bundler: StyleBundler;\n\n return {\n name: \"html-bundle-style\",\n\n setup() {\n bundler = new StyleBundler(this);\n },\n\n async transform(metadata) {\n if (!this.production) return;\n if (!isHtmlMetadata(metadata)) return;\n\n const elements = metadata.ast.querySelectorAll(query);\n\n for (const node of elements) {\n node.removeAttribute(bundleAttribute);\n\n const isLinkTag = node.tagName.toLowerCase() === \"link\";\n\n const styleMetadata: StyleMetadata | undefined = (() => {\n if (isLinkTag) {\n const href = node.getAttribute(\"href\");\n if (!href) return;\n\n const [link] = splitHtmlLink(href);\n const source = join(dirname(metadata.filePath), link);\n\n const getStyleMetadata = this.findMetadata({ filePath: source });\n if (!isStyleMetadata(getStyleMetadata)) return;\n\n return getStyleMetadata;\n }\n\n // style tag\n const metadataID = node.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!metadataID) return;\n\n return metadata.stylesMetadataList.get(metadataID);\n })();\n\n if (!styleMetadata) {\n printFmtError(`Could not find style metadata.`, { function: htmlBundleStylePlugin, node, filePath: metadata.id });\n continue;\n }\n\n if (isLinkTag) {\n if (alreadyBundledIds.has(styleMetadata.id)) {\n continue;\n }\n\n alreadyBundledIds.add(styleMetadata.id);\n }\n\n const bundleAbsolutePath = join(this.root, isLinkTag ? styleMetadata.filePath : metadata.filePath);\n\n const diagnostics = await bundler.bundle(styleMetadata, bundleAbsolutePath);\n\n for (const { level, message, node: importNode, filePath } of diagnostics) {\n printFmtError(message, { function: htmlBundleStylePlugin, node: importNode, filePath, level });\n }\n }\n },\n\n lspHtmlData() {\n const description = `Adds the \\`${bundleAttribute}\\` attribute, which inlines the stylesheet's \\`@import\\` tree at build time.`;\n const attributes = [{ name: bundleAttribute, description: \"Enable style bundling.\", valueSet: \"v\" }];\n\n return {\n version: 1.1,\n tags: [\n { name: \"link\", description, attributes },\n { name: \"style\", description, attributes },\n ],\n };\n },\n };\n}\n","import { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlEnvOnlyOptions {\n /**\n * The HTML attribute name that marks a tag as development-only.\n *\n * Tags with this attribute are removed at build time and kept (with the attribute stripped) during dev serve.\n *\n * @default \"dev-only\"\n */\n devOnlyAttribute?: string;\n\n /**\n * The HTML attribute name that marks a tag as production-only.\n *\n * Tags with this attribute are removed during dev serve and kept (with the attribute stripped) at build time.\n *\n * @default \"production-only\"\n */\n productionOnlyAttribute?: string;\n}\n\n/**\n * Removes the HTML tags that do not belong in the current environment.\n *\n * Attributes (names configurable via HtmlEnvOnlyOptions):\n *\n * - \"dev-only\": kept while serving, removed from the production build.\n * - \"production-only\": kept in the production build, removed while serving.\n *\n * Notes:\n *\n * - Works on any element, and removal takes the element's whole subtree with it.\n * - Where the tag survives, the marker attribute is stripped from the output.\n */\nexport function htmlEnvOnlyPlugin(options: HtmlEnvOnlyOptions = {}): Plugin {\n const developmentOnlyAttribute = options.devOnlyAttribute ?? \"dev-only\";\n const productionOnlyAttribute = options.productionOnlyAttribute ?? \"production-only\";\n\n return {\n name: \"html-env-only\",\n\n transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n // eslint-disable-next-line unicorn/require-css-escape\n const developmentOnlyElements = metadata.ast.querySelectorAll(`[${developmentOnlyAttribute}]`);\n for (const node of developmentOnlyElements) {\n if (this.production) node.remove();\n else node.removeAttribute(developmentOnlyAttribute);\n }\n\n // eslint-disable-next-line unicorn/require-css-escape\n const productionOnlyElements = metadata.ast.querySelectorAll(`[${productionOnlyAttribute}]`);\n for (const node of productionOnlyElements) {\n if (this.production) node.removeAttribute(productionOnlyAttribute);\n else node.remove();\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n globalAttributes: [\n {\n name: developmentOnlyAttribute,\n description: \"Keep this tag during dev serve only; it is removed at build time.\",\n valueSet: \"v\",\n },\n {\n name: productionOnlyAttribute,\n description: \"Keep this tag at build time only; it is removed during dev serve.\",\n valueSet: \"v\",\n },\n ],\n };\n },\n };\n}\n","import { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlFragmentOptions {\n /**\n * The tag name used for the fragment custom element.\n *\n * @default \"fragment\"\n */\n tagName?: string;\n}\n\n/**\n * Replaces every \"<fragment>\" element (tag name configurable via HtmlFragmentOptions) with its own content, so the wrapper leaves\n * no trace in the output. Handy for grouping markup a layout or an insert has to treat as one node.\n *\n * Notes:\n *\n * - Runs in development and production alike.\n * - The content is re-parsed from the element's inner HTML and trimmed, so surrounding whitespace is dropped.\n * - Fragments nest: the page is rescanned after each replacement, so a fragment inside another one is unwrapped as well.\n */\nexport function htmlFragmentPlugin(options: HtmlFragmentOptions = {}): Plugin {\n const tag = options.tagName ?? \"fragment\";\n\n return {\n name: \"html-fragment\",\n\n transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n // The content is re-parsed on replace, so a nested fragment ends up as a node the previous\n // query never saw. Re-query after every replacement until none is left.\n let node = metadata.ast.querySelector(tag);\n\n while (node?.parentNode) {\n node.replaceWith(node.innerHTML.trim());\n node = metadata.ast.querySelector(tag);\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: tag,\n description: \"At build time, this tag is replaced with its contents.\",\n attributes: [],\n },\n ],\n };\n },\n };\n}\n","import * as t from \"@babel/types\";\n\nimport type { ValueOrError } from \"../../utilities/value-or-error.ts\";\nimport type { BabelAst } from \"@staticbolt/core\";\n\nfunction isTopLevelIIFE(ast: BabelAst): boolean {\n const body = ast.program.body;\n\n if (body.length !== 1) {\n return false;\n }\n\n const statement = body[0];\n if (statement.type !== \"ExpressionStatement\") {\n return false;\n }\n\n const expression = statement.expression;\n if (expression.type !== \"CallExpression\") {\n return false;\n }\n\n const callee = expression.callee;\n\n return callee.type === \"ArrowFunctionExpression\" || callee.type === \"FunctionExpression\";\n}\n\n/**\n * Returns true if an export declaration is an empty re-export (`export {}`). These are typically emitted by TypeScript and carry\n * no runtime meaning.\n */\nfunction isEmptyExport(node: t.Statement): node is t.ExportNamedDeclaration {\n return (\n node.type === \"ExportNamedDeclaration\" && node.specifiers.length === 0 && node.declaration == null && node.source == null\n );\n}\n\nfunction isStaticImport(node: t.Statement): node is t.ImportDeclaration {\n return node.type === \"ImportDeclaration\";\n}\n\nfunction isExport(node: t.Statement): node is t.ExportNamedDeclaration | t.ExportDefaultDeclaration | t.ExportAllDeclaration {\n return (\n node.type === \"ExportNamedDeclaration\" || node.type === \"ExportDefaultDeclaration\" || node.type === \"ExportAllDeclaration\"\n );\n}\n\n/**\n * Wraps all statements of a Babel `File` AST in an IIFE:\n *\n * (function () { <statements> })();\n *\n * Rules:\n *\n * - Static `import` declarations → throws `IIFEWrapError`\n * - Non-empty `export` declarations → throws `IIFEWrapError`\n * - Empty `export {}` statements → silently removed\n * - Dynamic `import()` expressions inside the body → allowed (they're not declarations)\n */\nexport function wrapWithIIFE(ast: BabelAst): ValueOrError<t.File> {\n const body = ast.program.body;\n\n if (isTopLevelIIFE(ast)) {\n return [null, new Error(\"The script is already wrapped in an IIFE\")];\n }\n\n for (const node of body) {\n if (isStaticImport(node)) {\n return [null, new Error(\"Static import declarations are not allowed in IIFE-wrapped scripts\")];\n }\n\n if (isExport(node) && !isEmptyExport(node)) {\n return [null, new Error(`Export declarations are not allowed in IIFE-wrapped scripts`)];\n }\n }\n\n // Strip empty `export {}` statements, keep everything else\n const filteredBody = body.filter(node => !isEmptyExport(node));\n\n // (() => { ...filteredBody })()\n ast.program.body = [t.expressionStatement(t.callExpression(t.arrowFunctionExpression([], t.blockStatement(filteredBody)), []))];\n\n return [ast, null];\n}\n","import { isScriptType } from \"../../helpers/is-script-type.ts\";\nimport { isJavaScript } from \"../../helpers/lsp-checks.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { wrapWithIIFE } from \"./iife.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlIifeScriptOptions {\n /**\n * The attribute name that enables IIFE.\n *\n * @default \"iife\"\n */\n iifeAttribute?: string;\n}\n\n/**\n * Wraps the body of a script tag marked with \"iife\" (attribute configurable via HtmlIifeScriptOptions) in an immediately invoked\n * function expression, so its declarations stay out of the global scope.\n *\n * Notes:\n *\n * - The attribute is stripped in both modes, but the wrapping only happens in production.\n * - Inline scripts only: a tag with a \"src\" attribute is reported as an error and left alone.\n * - Meant for classic scripts. A module already has its own scope, so wrapping one buys nothing.\n */\nexport function htmlIifeScriptPlugin(options: HtmlIifeScriptOptions = {}): Plugin {\n const iifeAttribute = options.iifeAttribute ?? \"iife\";\n const query = `script[${iifeAttribute}]`;\n\n return {\n name: \"html-iife-script\",\n\n transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const scriptTags = metadata.ast.querySelectorAll(query);\n\n for (const scriptTag of scriptTags) {\n scriptTag.removeAttribute(iifeAttribute);\n\n if (!this.production) continue;\n\n const scriptType = scriptTag.getAttribute(\"type\");\n if (!isScriptType(scriptType)) {\n continue;\n }\n\n const printFmtError = PrintFormattedError.create({\n function: htmlIifeScriptPlugin,\n filePath: metadata.id,\n node: scriptTag,\n lang: \"html\",\n });\n\n const sourceAttribute = scriptTag.getAttribute(\"src\");\n if (sourceAttribute) {\n printFmtError(\"IIFE only works with inline scripts.\");\n continue;\n }\n\n if (scriptType === \"module\") {\n printFmtError(\"IIFE should only be used with global scripts. A module already has its own scope.\", {\n level: \"warning\",\n });\n }\n\n const metadataID = scriptTag.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!metadataID) {\n printFmtError(\"Missing metadata ID.\");\n continue;\n }\n\n const scriptMetadata = metadata.scriptsMetadataList.get(metadataID);\n if (!scriptMetadata) {\n printFmtError(\"Missing script metadata.\");\n continue;\n }\n\n // wrap in IIFE (Immediately Invoked Function Expression)\n const [, wrapError] = wrapWithIIFE(scriptMetadata.ast); // mutates ast\n if (wrapError) {\n printFmtError(\"Error wrapping script in IIFE\", wrapError);\n }\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: \"script\",\n description: `Adds the \\`${iifeAttribute}\\` attribute, which wraps an inline script's body in an immediately invoked function expression at build time.`,\n attributes: [\n {\n name: iifeAttribute,\n description:\n \"Enabling this will wrap the script content in an IIFE (Immediately Invoked Function Expression).\" +\n \"\\n\\nWorks only with inline global scripts.\",\n valueSet: \"v\",\n },\n ],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const scripts = document.select(\"script\");\n\n for (const element of scripts) {\n const iife = element.attribute(iifeAttribute);\n if (!iife) continue;\n\n if (!isJavaScript(element)) {\n report.warn(iife.nameRange, `\"${iifeAttribute}\" does nothing on a script that is not JavaScript`);\n continue;\n }\n\n if (element.attribute(\"type\")?.value === \"module\") {\n report.warn(iife.nameRange, `\"${iifeAttribute}\" is for global scripts, a module already has its own scope`);\n }\n }\n },\n };\n}\n","import { isScriptType } from \"../../helpers/is-script-type.ts\";\nimport { checkFileExists, isEmptyElement, isJavaScript } from \"../../helpers/lsp-checks.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { type ScriptMetadata } from \"../../types/metadata.ts\";\nimport { splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata, isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { downloadContent, hashContent, isURL } from \"../../utilities/utilities.ts\";\n\nimport type { ValueOrError } from \"../../utilities/value-or-error.ts\";\nimport type { App, Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlInlineScriptOptions {\n /**\n * The attribute name that enables inlining.\n *\n * @default \"inline\"\n */\n inlineAttribute?: string;\n}\n\n/**\n * Replaces a script tag marked with \"inline\" (attribute configurable via HtmlInlineScriptOptions) with the code it points at, so\n * the page ships one request fewer. The \"src\" attribute is dropped and the code becomes the tag's content.\n *\n * The source can be a local file or a remote URL; a URL is downloaded at build time, cached per page directory and URL, and kept\n * out of the output.\n *\n * Notes:\n *\n * - The attribute is stripped in both modes, but the inlining only happens in production.\n * - The tag must have a \"src\" and no content of its own; anything else is reported as an error and left alone.\n * - A local file has to be part of the build already, otherwise its metadata is not found and nothing is inlined.\n * - The inlined copy is rebased onto the HTML file, so its relative imports keep resolving, and the original file stays in the\n * output unless something removes it.\n * - The tag's \"type\" decides whether the inlined code is treated as a module, not the original file.\n */\nexport function htmlInlineScriptPlugin(options: HtmlInlineScriptOptions = {}): Plugin {\n const inlineAttribute = options.inlineAttribute ?? \"inline\";\n const query = `script[${inlineAttribute}]`;\n\n return {\n name: \"html-inline-script\",\n\n async transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const scriptTags = metadata.ast.querySelectorAll(query);\n\n for (const scriptTag of scriptTags) {\n scriptTag.removeAttribute(inlineAttribute);\n\n if (!this.production) {\n continue;\n }\n\n const scriptType = scriptTag.getAttribute(\"type\");\n if (!isScriptType(scriptType)) {\n continue;\n }\n\n const printFmtError = PrintFormattedError.create({\n function: htmlInlineScriptPlugin,\n filePath: metadata.id,\n node: scriptTag,\n lang: \"html\",\n });\n\n const sourceAttribute = scriptTag.getAttribute(\"src\");\n if (!sourceAttribute) {\n printFmtError(\"Missing src attribute\");\n continue;\n }\n\n const scriptContent = scriptTag.textContent.trim();\n if (scriptContent) {\n printFmtError(\"Script tag is not empty\");\n continue;\n }\n\n const [scriptMetadata, loadError] = await loadScriptMetadata.call(this, sourceAttribute, metadata.filePath);\n if (loadError) {\n printFmtError(\"Error loading script\", loadError);\n continue;\n }\n\n // clone and rebase\n const scriptMetadataClone = this.clone(scriptMetadata);\n await this.rebase(scriptMetadataClone, join(this.root, metadata.filePath));\n\n const isModule = scriptTag.getAttribute(\"type\") === \"module\";\n scriptMetadataClone.module = isModule;\n\n // add script tag ast\n const metadataID = hashContent((isModule ? \"module:\" : \"script:\") + (await this.stringify(scriptMetadataClone)));\n scriptTag.setAttribute(CUSTOM_ATTRIBUTES.MetadataID, metadataID);\n metadata.scriptsMetadataList.set(metadataID, scriptMetadataClone);\n\n scriptTag.removeAttribute(\"src\");\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: \"script\",\n description: `Adds the \\`${inlineAttribute}\\` attribute, which inlines the script the \\`src\\` points at into the page at build time.`,\n attributes: [\n {\n name: inlineAttribute,\n description:\n \"Enable inlining external scripts directly into the HTML at build time. It supports local files, remote URLs.\" +\n \"\\n\\nThe tag must have a `src` and no content of its own. Inlining only happens in production builds.\",\n valueSet: \"v\",\n },\n ],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const scripts = document.select(\"script\");\n\n for (const element of scripts) {\n const inline = element.attribute(inlineAttribute);\n if (!inline) continue;\n\n if (!isJavaScript(element)) {\n report.warn(inline.nameRange, `\"${inlineAttribute}\" does nothing on a script that is not JavaScript`);\n continue;\n }\n\n const source = element.attribute(\"src\");\n if (!source?.value) {\n report.error(inline.nameRange, `\"${inlineAttribute}\" needs a \"src\" pointing at the script to inline`);\n continue;\n }\n\n if (!isEmptyElement(element, document)) {\n report.error(inline.nameRange, `\"${inlineAttribute}\" needs an empty script tag, the content comes from \"src\"`);\n }\n\n checkFileExists(source, document, report);\n }\n },\n };\n}\n\nasync function loadScriptMetadata(this: App, source: string, filePath: string): Promise<ValueOrError<ScriptMetadata>> {\n // Download and load as a script metadata\n if (isURL(source)) {\n const urlHash = await crypto.subtle.digest(\"SHA-1\", new TextEncoder().encode(source));\n const hashHex = Array.from(new Uint8Array(urlHash), b => b.toString(16).padStart(2, \"0\")).join(\"\");\n const downloadedFilePath = join(dirname(filePath), `downloaded/${hashHex}.js`);\n\n // Already downloaded and loaded\n for (const metadata of this.metadataList) {\n if (isScriptMetadata(metadata) && metadata.filePath === downloadedFilePath) {\n return [metadata, null];\n }\n }\n\n const [downloaded, downloadError] = await downloadContent(source);\n if (downloadError) {\n return [null, downloadError];\n }\n\n const scriptMetadata = await this.load(downloadedFilePath, { code: downloaded, type: \"js\" });\n if (!isScriptMetadata(scriptMetadata)) {\n return [null, new Error(\"Downloaded file is not a script\")];\n }\n\n // No need to transform or resolve a downloaded script\n this.addMetadata(scriptMetadata);\n this.emitExclude.add(scriptMetadata);\n\n return [scriptMetadata, null];\n }\n\n const [link] = splitHtmlLink(source);\n const sourcePath = join(dirname(filePath), link);\n\n // Already loaded and found\n const metadata = this.findMetadata({ filePath: sourcePath });\n if (isScriptMetadata(metadata)) {\n return [metadata, null];\n }\n\n return [null, new Error(\"Failed to find script metadata\")];\n}\n","import { checkFileExists } from \"../../helpers/lsp-checks.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { type StyleMetadata } from \"../../types/metadata.ts\";\nimport { splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata, isStyleMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { downloadContent, hashContent, isURL } from \"../../utilities/utilities.ts\";\n\nimport type { ValueOrError } from \"../../utilities/value-or-error.ts\";\nimport type { App, Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlInlineStyleOptions {\n /**\n * The attribute name that enables inlining.\n *\n * @default \"inline\"\n */\n inlineAttribute?: string;\n}\n\n/**\n * Turns a \"<link rel=stylesheet>\" marked with \"inline\" (attribute configurable via HtmlInlineStyleOptions) into a \"<style>\" tag\n * holding the stylesheet itself, so the page ships one request fewer.\n *\n * The \"href\" can point at a local file or a remote URL; a URL is downloaded at build time, cached per page directory and URL, and\n * kept out of the output.\n *\n * Notes:\n *\n * - The attribute is stripped in both modes, but the inlining only happens in production.\n * - The link's remaining attributes are copied onto the \"<style>\" tag; \"href\" and \"rel\" are dropped.\n * - A local file has to be part of the build already, otherwise its metadata is not found and nothing is inlined.\n * - The inlined copy is rebased onto the HTML file, so relative \"url()\" and \"@import\" paths keep resolving, and the original file\n * stays in the output unless something removes it.\n */\nexport function htmlInlineStylePlugin(options: HtmlInlineStyleOptions = {}): Plugin {\n const inlineAttribute = options.inlineAttribute ?? \"inline\";\n const query = `link[rel=\"stylesheet\"][${inlineAttribute}]`;\n\n return {\n name: \"html-inline-style\",\n\n async transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const linkTags = metadata.ast.querySelectorAll(query);\n\n for (const linkTag of linkTags) {\n linkTag.removeAttribute(inlineAttribute);\n\n if (!this.production) {\n continue;\n }\n\n const printFmtError = PrintFormattedError.create({\n function: htmlInlineStylePlugin,\n filePath: metadata.id,\n lang: \"html\",\n });\n\n const sourceAttribute = linkTag.getAttribute(\"href\");\n if (!sourceAttribute) {\n printFmtError(\"Missing href attribute\", { node: linkTag });\n continue;\n }\n\n const [styleMetadata, loadError] = await loadStyleMetadata.call(this, sourceAttribute, metadata.filePath);\n if (loadError) {\n printFmtError(\"Error loading style\", loadError, { node: linkTag });\n continue;\n }\n\n // clone and rebase\n const styleMetadataClone = this.clone(styleMetadata);\n await this.rebase(styleMetadataClone, join(this.root, metadata.filePath));\n\n // add script tag ast\n const metadataID = hashContent(await this.stringify(styleMetadataClone));\n linkTag.setAttribute(CUSTOM_ATTRIBUTES.MetadataID, metadataID);\n metadata.stylesMetadataList.set(metadataID, styleMetadataClone);\n\n linkTag.removeAttribute(\"href\");\n linkTag.removeAttribute(\"rel\");\n\n const attributesString = Object.entries(linkTag.attrs)\n .map(([name, value]) => `${name}=\"${value}\"`)\n .join(\" \");\n\n linkTag.replaceWith(`<style ${attributesString}></style>`);\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: \"link\",\n description: `Adds the \\`${inlineAttribute}\\` attribute, which turns a stylesheet link into a \\`<style>\\` tag holding the stylesheet itself at build time.`,\n attributes: [\n {\n name: inlineAttribute,\n description:\n \"Enable inlining external stylesheets directly into the HTML at build time. It supports both local files and remote URLs.\",\n valueSet: \"v\",\n },\n ],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const links = document.select(\"link\");\n\n for (const element of links) {\n const inline = element.attribute(inlineAttribute);\n if (!inline) continue;\n\n if (element.attribute(\"rel\")?.value !== \"stylesheet\") {\n report.warn(inline.nameRange, `\"${inlineAttribute}\" only works on a link with rel=\"stylesheet\"`);\n continue;\n }\n\n const source = element.attribute(\"href\");\n if (!source?.value) {\n report.error(inline.nameRange, `\"${inlineAttribute}\" needs an \"href\" pointing at the stylesheet to inline`);\n continue;\n }\n\n checkFileExists(source, document, report);\n }\n },\n };\n}\n\nasync function loadStyleMetadata(this: App, source: string, filePath: string): Promise<ValueOrError<StyleMetadata>> {\n // Download and load as a style metadata\n if (isURL(source)) {\n const urlHash = await crypto.subtle.digest(\"SHA-1\", new TextEncoder().encode(source));\n const hashHex = Array.from(new Uint8Array(urlHash), b => b.toString(16).padStart(2, \"0\")).join(\"\");\n const downloadedFilePath = join(dirname(filePath), `downloaded/${hashHex}.css`);\n\n // Already downloaded and loaded\n for (const metadata of this.metadataList) {\n if (isStyleMetadata(metadata) && metadata.filePath === downloadedFilePath) {\n return [metadata, null];\n }\n }\n\n const [downloaded, downloadError] = await downloadContent(source);\n if (downloadError) {\n return [null, downloadError];\n }\n\n const styleMetadata = await this.load(downloadedFilePath, { code: downloaded, type: \"css\" });\n if (!isStyleMetadata(styleMetadata)) {\n return [null, new Error(\"Downloaded file is not CSS\")];\n }\n\n this.addMetadata(styleMetadata);\n this.emitExclude.add(styleMetadata);\n\n return [styleMetadata, null];\n }\n\n // Load locally\n const [link] = splitHtmlLink(source);\n const sourcePath = join(dirname(filePath), link);\n\n const metadata = this.findMetadata({ filePath: sourcePath });\n if (!isStyleMetadata(metadata)) {\n return [null, new Error(\"Failed to find style metadata\")];\n }\n\n return [metadata, null];\n}\n","import { checkFileExists } from \"../../helpers/lsp-checks.ts\";\nimport { type SvgMetadata } from \"../../types/metadata.ts\";\nimport { splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata, isSvgMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { downloadContent, isURL } from \"../../utilities/utilities.ts\";\n\nimport type { ValueOrError } from \"../../utilities/value-or-error.ts\";\nimport type { App, Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlInlineSvgOptions {\n /**\n * The attribute name that enables inlining.\n *\n * @default \"inline\"\n */\n inlineAttribute?: string;\n}\n\n/**\n * Replaces an \"<svg inline src=...>\" placeholder (attribute configurable via HtmlInlineSvgOptions) with the actual SVG element\n * from the file, so it can be styled and scripted like any other markup.\n *\n * The \"src\" can point at a local file or a remote URL; a URL is downloaded at build time, cached per page directory and URL, and\n * kept out of the output.\n *\n * Notes:\n *\n * - Runs in development and production alike.\n * - Every attribute left on the placeholder is copied onto the inlined element and overrides what the file declares, \"viewBox\" and\n * \"fill\" included.\n * - A local file has to be part of the build already, otherwise its metadata is not found and the placeholder is left as it is.\n * - Only the \"<svg>\" element of the file is taken; anything around it in the file is dropped.\n */\nexport function HtmlInlineSvgPlugin(options: HtmlInlineSvgOptions = {}): Plugin {\n const inlineAttribute = options.inlineAttribute ?? \"inline\";\n const query = `svg[${inlineAttribute}]`;\n const sourceAttribute = \"src\";\n\n const printFmtError = PrintFormattedError.create({ function: HtmlInlineSvgPlugin });\n\n const svgMetadataList: SvgMetadata[] = [];\n\n return {\n name: \"html-inline-svg\",\n\n setup() {\n this.pluginData.svgMetadataList ??= svgMetadataList;\n },\n\n async transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const filePath = metadata.filePath;\n const elements = metadata.ast.querySelectorAll(query);\n\n for (const node of elements) {\n const source = node.getAttribute(sourceAttribute);\n if (!source) {\n printFmtError(`The svg element is missing the \"${inlineAttribute}\" attribute`, { node, filePath });\n continue;\n }\n\n const [svgMetadata, loadError] = await loadSvgMetadata.call(this, source, filePath);\n if (loadError) {\n printFmtError(\"Error loading svg metadata\", loadError, { node, filePath });\n continue;\n }\n\n const svgMetadataClone = this.clone(svgMetadata);\n\n const svgElement = svgMetadataClone.ast.querySelector(\"svg\");\n if (!svgElement) {\n printFmtError(`Failed to parse svg element`, { node, filePath });\n continue;\n }\n\n node.removeAttribute(inlineAttribute);\n node.removeAttribute(sourceAttribute);\n\n for (const [attribute, value] of Object.entries(node.attrs)) {\n svgElement.setAttribute(attribute, value);\n }\n\n node.replaceWith(svgElement);\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: \"svg\",\n description: `Adds the \\`${inlineAttribute}\\` attribute, which replaces the placeholder with the SVG element from the file the \\`src\\` points at, at build time.`,\n attributes: [\n {\n name: inlineAttribute,\n description:\n \"Enable inlining external SVGs directly into the HTML at build time. It supports both local files and remote URLs.\",\n valueSet: \"v\",\n },\n ],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const svgs = document.select(\"svg\");\n\n for (const element of svgs) {\n const inline = element.attribute(inlineAttribute);\n if (!inline) continue;\n\n const source = element.attribute(sourceAttribute);\n if (!source?.value) {\n report.error(inline.nameRange, `\"${inlineAttribute}\" needs a \"${sourceAttribute}\" pointing at the SVG to inline`);\n continue;\n }\n\n checkFileExists(source, document, report);\n }\n },\n };\n}\n\nasync function loadSvgMetadata(this: App, source: string, filePath: string): Promise<ValueOrError<SvgMetadata>> {\n // Download and load as a svg metadata\n if (isURL(source)) {\n const urlHash = await crypto.subtle.digest(\"SHA-1\", new TextEncoder().encode(source));\n const hashHex = Array.from(new Uint8Array(urlHash), b => b.toString(16).padStart(2, \"0\")).join(\"\");\n const downloadedFilePath = join(dirname(filePath), `downloaded/${hashHex}.svg`);\n\n // Already downloaded and loaded\n for (const metadata of this.metadataList) {\n if (isSvgMetadata(metadata) && metadata.filePath === downloadedFilePath) {\n return [metadata, null];\n }\n }\n\n const [downloaded, downloadError] = await downloadContent(source);\n if (downloadError) {\n return [null, downloadError];\n }\n\n const svgMetadata = await this.load(downloadedFilePath, { code: downloaded, type: \"svg\" });\n if (!isSvgMetadata(svgMetadata)) {\n return [null, new Error(\"Downloaded file is not SVG\")];\n }\n\n // No need to transform or resolve a downloaded svg\n\n this.addMetadata(svgMetadata);\n this.emitExclude.add(svgMetadata);\n\n return [svgMetadata, null];\n }\n\n // Load locally\n const [link] = splitHtmlLink(source);\n const sourcePath = join(dirname(filePath), link);\n\n const metadata = this.findMetadata({ filePath: sourcePath });\n if (!isSvgMetadata(metadata)) {\n return [null, new Error(\"Failed to find SVG metadata\")];\n }\n\n return [metadata, null];\n}\n","import { DependencyTracker } from \"../../helpers/dependency-tracker.ts\";\nimport { checkFileExists } from \"../../helpers/lsp-checks.ts\";\nimport { splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join, relative } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { safeReadFileSync } from \"../../utilities/read-file.ts\";\nimport { escapeHtml } from \"../../utilities/utilities.ts\";\n\nimport type { MetadataSource, Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlInlineTextOptions {\n /**\n * The tag name for the inline text.\n *\n * @default \"inline-text\"\n */\n tagName?: string;\n\n /**\n * The attribute name on the custom tag that holds the path to the external text file.\n *\n * @default \"src\"\n */\n sourceAttribute?: string;\n\n /**\n * The attribute name of the attribute that disables HTML escaping.\n *\n * @default \"no-escape\"\n */\n noEscapeAttribute?: string;\n}\n\n/**\n * Replaces an \"<inline-text src=...>\" tag with the contents of the file it points at (tag and attribute names configurable via\n * HtmlInlineTextOptions). The text is HTML-escaped unless the tag carries \"no-escape\", which inserts it as markup.\n *\n * Notes:\n *\n * - Runs in development and production alike.\n * - The file is read straight from disk, so it is not a build source and no other plugin transforms it.\n * - Contents are cached per path for the whole build, escaping included: when two tags point at the same file, the first one\n * decides whether both end up escaped.\n * - The cache is dropped when the file changes, and pages that inlined it are recompiled, so the dev server stays in sync.\n */\nexport function htmlInlineTextPlugin(options: HtmlInlineTextOptions = {}): Plugin {\n const tag = options.tagName ?? \"inline-text\";\n const sourceAttribute = options.sourceAttribute ?? \"src\";\n const noEscapeAttribute = options.noEscapeAttribute ?? \"no-escape\";\n\n const cache = new Map<string, string>();\n\n const dependencies = new DependencyTracker();\n\n /** Suffix on the tag's source while it travels through resolution, keeping it apart from real build sources. */\n const MARKER = \"?html-inline-text\";\n\n return {\n name: \"html-inline-text\",\n\n sourcesProvider(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const result: MetadataSource[] = [];\n\n const inlineTags = metadata.ast.querySelectorAll(tag);\n\n for (const inlineTag of inlineTags) {\n const source = inlineTag.getAttribute(sourceAttribute);\n if (!source) continue;\n\n // Marks the source as text to paste, so `resolveSource` can tell it apart from a build source\n const [link] = splitHtmlLink(source);\n inlineTag.setAttribute(sourceAttribute, link + MARKER);\n\n result.push({\n get source() {\n return inlineTag.getAttribute(sourceAttribute) ?? \"\";\n },\n set source(newValue) {\n inlineTag.setAttribute(sourceAttribute, newValue);\n },\n });\n }\n\n return result;\n },\n\n resolveSource(source, filePath) {\n const [, suffix] = splitHtmlLink(source);\n if (suffix !== MARKER) return;\n\n const resolved = this.resolver.resolve(source, filePath);\n if (!resolved?.exists) return;\n\n this.watcher?.add(relative(this.root, resolved.path));\n\n return { source: relative(join(this.root, dirname(filePath)), resolved.path), dependencyID: undefined };\n },\n\n transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const inlineTags = metadata.ast.querySelectorAll(tag);\n const currentSources = new Set<string>();\n\n for (const inlineTag of inlineTags) {\n const printFmtError = PrintFormattedError.create({\n function: htmlInlineTextPlugin,\n filePath: metadata.id,\n lang: \"html\",\n node: inlineTag,\n });\n\n const source = inlineTag.getAttribute(sourceAttribute);\n if (!source) {\n printFmtError(`Missing \"${sourceAttribute}\" attribute`);\n continue;\n }\n\n const [link] = splitHtmlLink(source);\n const sourceRelative = join(dirname(metadata.filePath), link);\n\n let contents: string;\n\n // From cache\n if (cache.has(sourceRelative)) {\n contents = cache.get(sourceRelative)!;\n }\n // Read and cache\n else {\n const [readContents, readError] = safeReadFileSync(sourceRelative, \"utf8\");\n if (readError) {\n printFmtError(readError);\n continue;\n }\n\n const isNoEscape = inlineTag.hasAttribute(noEscapeAttribute);\n contents = isNoEscape ? readContents : escapeHtml(readContents);\n cache.set(sourceRelative, contents);\n }\n\n currentSources.add(sourceRelative);\n\n inlineTag.replaceWith(contents);\n }\n\n dependencies.update(metadata.id, currentSources);\n },\n\n onFileEvent(event, id) {\n if (event === \"unlink\" || event === \"change\") {\n cache.delete(id);\n }\n\n if (event === \"unlink\") {\n dependencies.delete(id);\n }\n },\n\n resolveCompileList(compileSet, event) {\n if (event !== \"change\") return;\n\n for (const id of Array.from(compileSet)) {\n const importers = dependencies.getImporters(id);\n\n for (const importer of importers) {\n compileSet.add(importer);\n }\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: tag,\n description: \"At build time, this tag is replaced with the contents of the external text file.\",\n attributes: [\n {\n name: sourceAttribute,\n description: \"The path to the external text file.\",\n },\n {\n name: noEscapeAttribute,\n description: \"Disable HTML escaping.\",\n valueSet: \"v\",\n },\n ],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const inlineTags = document.select(tag);\n\n for (const element of inlineTags) {\n const source = element.attribute(sourceAttribute);\n\n if (!source?.value) {\n report.error(element, `<${tag}> needs a \"${sourceAttribute}\" pointing at a text file`);\n continue;\n }\n\n checkFileExists(source, document, report);\n }\n },\n };\n}\n","import { isDynamic, isEmptyElement } from \"../../helpers/lsp-checks.ts\";\nimport { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\n/** Where `insertAdjacentHTML` can put content. */\nconst POSITIONS = new Set<string>([\"beforebegin\", \"afterbegin\", \"beforeend\", \"afterend\"]);\n\nexport interface HtmlInsertOptions {\n /**\n * The HTML tag name of the custom insert element.\n *\n * @default \"insert\"\n */\n tagName?: string;\n\n /**\n * The attribute name that points to the target element via a CSS selector.\n *\n * @default \"selector\"\n */\n selectorAttribute?: string;\n\n /**\n * The attribute name that enables the replacement of the target element.\n *\n * @default \"replace\"\n */\n replaceAttribute?: string;\n\n /**\n * The attribute name that determines the position of the inserted element.\n *\n * @default \"where\"\n */\n whereAttribute?: string;\n}\n\n/**\n * Moves the content of an \"<insert>\" tag into any element on the same page, addressed by a CSS selector, then removes the tag\n * itself (names configurable via HtmlInsertOptions).\n *\n * Attributes:\n *\n * - \"selector\": the CSS selector of the target element.\n * - \"where\": where the content lands, one of \"beforebegin\", \"afterbegin\", \"beforeend\" (the default) or \"afterend\".\n * - \"replace\": swap the target element for the content instead of inserting into it.\n *\n * Notes:\n *\n * - Runs in development and production alike, and only searches the page the tag lives on.\n * - A tag whose target is not on the page yet is left untouched, since layouts and pages are assembled in several passes. Any tag\n * still unresolved at the end of the build is reported and stays in the output.\n * - An \"<insert>\" with no content or no selector is reported and left alone.\n */\nexport function htmlInsertPlugin(options: HtmlInsertOptions = {}): Plugin {\n const tag = options.tagName ?? \"insert\";\n const selectorAttribute = options.selectorAttribute ?? \"selector\";\n const replaceAttribute = options.replaceAttribute ?? \"replace\";\n const whereAttribute = options.whereAttribute ?? \"where\";\n\n const printFmtError = PrintFormattedError.create({\n function: htmlInsertPlugin,\n lang: \"html\",\n });\n\n return {\n name: \"html-insert\",\n\n transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const filePath = metadata.filePath;\n const elements = metadata.ast.querySelectorAll(tag);\n\n for (const node of elements) {\n const tag = node.tagName.toLowerCase();\n\n const content = node.innerHTML;\n if (!content) {\n printFmtError(`The tag <${tag}> is empty`, { node, filePath });\n continue;\n }\n\n const selector = node.getAttribute(selectorAttribute);\n if (!selector) {\n printFmtError(`The tag <${tag}> is missing the \"${selectorAttribute}\" attribute`, {\n node,\n filePath,\n });\n continue;\n }\n\n const targetElement = metadata.ast.querySelector(selector);\n if (!targetElement) {\n // ignore for now, this plugin might be called for layout when the page is not fully loaded\n continue;\n }\n\n if (node.hasAttribute(replaceAttribute)) {\n targetElement.replaceWith(content);\n } else {\n const where = (node.getAttribute(whereAttribute) || \"beforeend\") as InsertPosition;\n targetElement.insertAdjacentHTML(where, content);\n }\n\n node.remove();\n }\n },\n\n postTransform() {\n for (const metadata of this.metadataList) {\n if (!isHtmlMetadata(metadata)) continue;\n\n const elements = metadata.ast.querySelectorAll(tag);\n\n for (const node of elements) {\n printFmtError(`Could not find target element.`, { node, filePath: metadata.id });\n }\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: tag,\n description:\n \"At build time, inject HTML content into any target element on the page using a CSS selector at build time.\",\n attributes: [\n {\n name: selectorAttribute,\n description: \"The CSS selector of the target element.\",\n },\n {\n name: replaceAttribute,\n description: \"Replace the target element with the contents of the custom insert element.\",\n valueSet: \"v\",\n },\n {\n name: whereAttribute,\n description: \"The position of the inserted element.\",\n values: [...POSITIONS].map(position => ({ name: position })),\n },\n ],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const inserts = document.select(tag);\n\n for (const element of inserts) {\n const selector = element.attribute(selectorAttribute);\n const where = element.attribute(whereAttribute);\n\n if (isEmptyElement(element, document)) {\n report.error(element, `<${tag}> has nothing to insert`);\n }\n\n if (!selector?.value) {\n report.error(element, `<${tag}> needs a \"${selectorAttribute}\" with the CSS selector of the target element`);\n }\n\n if (where?.value && !isDynamic(where.value) && !POSITIONS.has(where.value)) {\n report.error(where, `\"${whereAttribute}\" must be one of ${[...POSITIONS].join(\", \")}`);\n }\n\n if (where && element.has(replaceAttribute)) {\n report.warn(where.nameRange, `\"${whereAttribute}\" does nothing with \"${replaceAttribute}\"`);\n }\n }\n },\n };\n}\n","import type { EmbeddedRegion } from \"../../types/lsp.ts\";\nimport type { ValueOrError } from \"../../utilities/value-or-error.ts\";\n\n/** `{{ expression }}`, or `\\{{ … }}` to have it left alone. The expression is captured without its surrounding whitespace. */\nconst placeholderRe = /(\\\\)?{{(\\s*)([\\s\\S]*?)\\s*}}/g;\n\n/** Where the expressions of the unescaped placeholders sit in `html`. */\nexport function findPlaceholders(html: string): EmbeddedRegion[] {\n const regions: EmbeddedRegion[] = [];\n\n for (const match of html.matchAll(placeholderRe)) {\n const [, escape, leadingSpace, expression] = match;\n if (escape) continue;\n\n // Past the `{{` and the whitespace after it\n const start = match.index + 2 + leadingSpace.length;\n const extent = { start: match.index, end: match.index + match[0].length };\n\n regions.push({ start, end: start + expression.length, extent });\n }\n\n return regions;\n}\n\n/** `{{ JavaScript expression }}` */\nexport function fillLayoutPlaceholders(html: string, placeholders: Record<string, unknown>): ValueOrError<string> {\n const errors: Error[] = [];\n\n const result = html.replace(placeholderRe, (match: string, escape: string, _leadingSpace: string, content: string) => {\n if (escape === \"\\\\\") {\n return match.slice(1);\n }\n\n const [expression, executeError] = executeExpression(content, placeholders);\n if (executeError) {\n errors.push(executeError);\n return \"\";\n }\n\n return expression;\n });\n\n // join errors\n if (errors.length > 0) {\n const combinedMessage = [\n \"Failed to fill placeholders\",\n ...errors.map((error, index) => ` [${index + 1}] ${error.message}`),\n ].join(\"\\n\");\n\n return [null, new AggregateError(errors, combinedMessage)];\n }\n\n return [result, null];\n}\n\ntype FunctionType = (data: Record<string, unknown>) => unknown;\nconst functionCache = new Map<string, FunctionType>();\n\nfunction executeExpression(expressionString: string, data: Record<string, unknown>): ValueOrError<string> {\n try {\n let function_ = functionCache.get(expressionString);\n if (!function_) {\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n function_ = new Function(\"$data\", `return ${expressionString}`) as FunctionType;\n functionCache.set(expressionString, function_);\n }\n\n const output = function_(data);\n\n if (output === undefined) {\n return [null, new Error(`Expression found in the placeholder {{ ${expressionString} }} returned undefined`)];\n }\n\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n const asString = String(output);\n\n if (asString === \"[object Object]\") {\n return [null, new Error(`Expression found in the placeholder {{ ${expressionString} }} returned an object`)];\n }\n\n return [asString, null];\n } catch (error) {\n return [null, new Error(`Failed to execute expression: ${expressionString}\\n ${(error as Error).message}`)];\n }\n}\n","import { NodeType } from \"@staticbolt/node-html-parser\";\n\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\n\nimport type { HTMLElement } from \"../../types/common.ts\";\nimport type { HtmlMetadata, MarkdownMetadata } from \"../../types/metadata.ts\";\nimport type { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport type { LayoutNames } from \"./options.ts\";\n\n/** The plugin's error printer. */\ntype PrintError = PrintFormattedError[\"print\"];\n\n/** Turns every `add-attr-x` and `remove-attr-x` of a layout into adding or removing `x`, by the value each holds. */\nexport function applyConditionalAttributes(layout: HtmlMetadata, names: LayoutNames): void {\n const addPrefix = `${names.addAttribute}-`;\n const removePrefix = `${names.removeAttribute}-`;\n const elements = layout.ast.querySelectorAll(\"*\");\n\n for (const element of elements) {\n if (!element.attributes) continue;\n\n for (const [name, value] of Object.entries(element.attributes)) {\n if (name.startsWith(addPrefix)) {\n element.removeAttribute(name);\n\n if (isSwitchedOn(value)) {\n element.setAttribute(name.slice(addPrefix.length), \"\");\n }\n\n continue;\n }\n\n if (!name.startsWith(removePrefix)) continue;\n\n element.removeAttribute(name);\n\n if (isSwitchedOn(value)) {\n element.removeAttribute(name.slice(removePrefix.length));\n }\n }\n }\n}\n\n/**\n * Drops from a layout instance the scripts, styles and stylesheet links the page already has from an earlier instance, so a\n * layout used twice emits each once. A tag marked always-include is kept, and the mark removed.\n */\nexport function dropRepeatedAssets(page: HtmlMetadata, layout: HtmlMetadata, alwaysInclude: string): void {\n const scriptsAndStyles = layout.ast.querySelectorAll(\"script,style\");\n\n for (const scriptOrStyle of scriptsAndStyles) {\n const id = scriptOrStyle.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!id) continue;\n\n if (scriptOrStyle.hasAttribute(alwaysInclude)) {\n scriptOrStyle.removeAttribute(alwaysInclude);\n continue;\n }\n\n const list = scriptOrStyle.tagName === \"SCRIPT\" ? \"scriptsMetadataList\" : \"stylesMetadataList\";\n if (!page[list].has(id)) continue;\n\n layout[list].delete(id);\n scriptOrStyle.remove();\n }\n\n const scriptsAndLinks = layout.ast.querySelectorAll('script[src], link[rel=\"stylesheet\"]');\n\n for (const scriptOrLink of scriptsAndLinks) {\n if (scriptOrLink.hasAttribute(alwaysInclude)) {\n scriptOrLink.removeAttribute(alwaysInclude);\n continue;\n }\n\n const isScript = scriptOrLink.tagName === \"SCRIPT\";\n const attribute = isScript ? \"src\" : \"href\";\n const selector = isScript ? \"script[src]\" : 'link[rel=\"stylesheet\"]';\n const layoutSource = join(dirname(layout.filePath), scriptOrLink.attributes[attribute]);\n\n const isOnPage = page.ast.querySelectorAll(selector).some(element => {\n const pageSource = join(dirname(page.filePath), element.attributes[attribute]);\n\n return pageSource === layoutSource;\n });\n\n if (isOnPage) {\n scriptOrLink.remove();\n }\n }\n}\n\n/**\n * Puts the tag's children into the layout's slots, by the `slot` attribute they name or into the unnamed slots, then unwraps\n * every slot. A slot keeps its own content as the fallback: the first fill replaces it, later ones append.\n */\nexport function fillSlots(tag: HTMLElement, layout: HtmlMetadata, layoutPath: string, printError: PrintError): void {\n const filledSlots = new Set<HTMLElement>();\n\n const fillSlot = (slot: HTMLElement, html: string) => {\n if (!filledSlots.has(slot)) {\n filledSlots.add(slot);\n slot.innerHTML = \"\";\n }\n\n slot.insertAdjacentHTML(\"beforeend\", html);\n };\n\n const children = tag.querySelectorAll(\":scope > *\");\n\n for (const element of children) {\n if (element.nodeType !== NodeType.ELEMENT_NODE) continue;\n\n if (!element.hasAttribute(\"slot\")) {\n const defaultSlots = layout.ast.querySelectorAll(\"slot:not([name])\");\n if (defaultSlots.length === 0) {\n printError(\"No default slot in layout file:\", layoutPath, { node: element });\n continue;\n }\n\n for (const defaultSlot of defaultSlots) {\n fillSlot(defaultSlot, element.outerHTML);\n }\n\n continue;\n }\n\n const slotName = element.getAttribute(\"slot\");\n if (!slotName) continue;\n\n // eslint-disable-next-line unicorn/require-css-escape\n const namedSlots = layout.ast.querySelectorAll(`slot[name=\"${slotName}\"]`);\n if (namedSlots.length === 0) {\n printError(`No slots with name \"${slotName}\" in layout file:`, layoutPath, { node: element });\n continue;\n }\n\n element.removeAttribute(\"slot\");\n\n for (const namedSlot of namedSlots) {\n fillSlot(namedSlot, element.outerHTML);\n }\n }\n\n for (const slot of layout.ast.querySelectorAll(\"slot\")) {\n slot.replaceWith(slot.innerHTML.trim());\n }\n}\n\n/**\n * Has a markdown page render inside the layout tag its front matter names: the naming key becomes the source attribute and the\n * other keys the tag's data.\n */\nexport function wrapMarkdownInLayout(metadata: MarkdownMetadata, names: LayoutNames): void {\n const tag = Object.keys(metadata.ast.frontmatter).find(key => names.tags.includes(key));\n if (!tag) return;\n\n let attributes = \"\";\n\n for (const [key, value] of Object.entries(metadata.ast.frontmatter)) {\n attributes += `${key === tag ? names.source : key}=\"${value}\" `;\n }\n\n const openTag = `<${tag} ${attributes}>`;\n const closeTag = `</${tag}>`;\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const render = metadata.ast.render;\n\n metadata.ast.render = async () => {\n const html = await render();\n\n return openTag + html + closeTag;\n };\n}\n\n/** Whether a conditional attribute's value, after the placeholders are filled, switches the attribute on. */\nfunction isSwitchedOn(value: string): boolean {\n const trimmed = value.trim();\n\n return trimmed !== \"\" && trimmed !== \"false\";\n}\n\n/** The tag's attributes other than the source, as the key a rendered instance is cached under. */\nexport function instanceKey(tag: HTMLElement, names: LayoutNames): string {\n let key = \"\";\n\n for (const [attribute, value] of Object.entries(tag.attributes)) {\n if (attribute === names.source) continue;\n\n key += `${attribute}=${value}`;\n }\n\n return key;\n}\n","import { basename } from \"../../utilities/path.ts\";\n\nexport interface HtmlLayoutOptions {\n /**\n * Tag names registered as valid HTML elements. Each name is also the required file suffix — e.g. `\"layout\"` means files must\n * end in `.layout.html`, `\"part\"` means `.part.html`.\n *\n * @default [\"layout\", \"part\"]\n */\n tags?: string[];\n\n /**\n * Attribute name used to point to the layout or part file.\n *\n * @default \"src\"\n */\n layoutSourceAttribute?: string;\n\n /**\n * Attribute name used to point to an external JSON file whose properties are merged into `$data`. Inline attributes take\n * priority over file keys.\n *\n * @default \"dataSource\"\n */\n dataSourceAttribute?: string;\n\n /**\n * Attribute name used to pass an inline JSON string as data. The value is parsed and merged into `$data` alongside any inline\n * attributes and any keys loaded via `dataSource`. Inline attributes take priority over `dataJson` keys; `dataJson` keys take\n * priority over `dataSource` keys.\n *\n * @default \"dataJson\"\n */\n dataJsonAttribute?: string;\n\n /**\n * Attribute name that opts a `<script>`, `<style>`, or `<link rel=\"stylesheet\">` tag out of deduplication. By default,\n * duplicate scripts and styles are removed when a layout or part is used more than once on the same page. Marking a tag with\n * this boolean attribute forces it to be emitted once per instance.\n *\n * @default \"always-include\"\n */\n alwaysIncludeAttribute?: string;\n\n /**\n * Prefix for conditionally adding boolean attributes. Append the target attribute name as a suffix — `add-attr-open`,\n * `add-attr-disabled`, etc. The value is a JS expression evaluated after placeholder resolution; if it is non-empty and not\n * `\"false\"`, the named attribute is added to the element. Multiple `add-attr-*` attributes can appear on the same element.\n *\n * ```html\n * <details add-attr-open=\"{{ $data.open }}\">…</details>\n * ```\n *\n * @default \"add-attr\"\n */\n addAttributeAttribute?: string;\n\n /**\n * Prefix for conditionally removing boolean attributes. Append the target attribute name as a suffix — `remove-attr-disabled`,\n * `remove-attr-hidden`, etc. The value is a JS expression evaluated after placeholder resolution; if it is non-empty and not\n * `\"false\"`, the named attribute is removed from the element. Multiple `remove-attr-*` attributes can appear on the same\n * element.\n *\n * ```html\n * <button disabled remove-attr-disabled=\"{{ $data.enabled }}\">…</button>\n * ```\n *\n * @default \"remove-attr\"\n */\n removeAttributeAttribute?: string;\n}\n\n/** The names the plugin works with, every option filled in. */\nexport interface LayoutNames {\n /** The tags that inline a file, and the suffixes of the files they inline. */\n tags: string[];\n\n /** The attribute holding the path of the file to inline. */\n source: string;\n\n /** The attribute holding the path of a JSON file with data. */\n dataSource: string;\n\n /** The attribute holding inline JSON data. */\n dataJson: string;\n\n /** The attribute that keeps a script or style for every instance of a layout. */\n alwaysInclude: string;\n\n /** The prefix of the attributes that add a boolean attribute. */\n addAttribute: string;\n\n /** The prefix of the attributes that remove a boolean attribute. */\n removeAttribute: string;\n}\n\n/** The options with their defaults filled in. */\nexport function resolveLayoutNames(options: HtmlLayoutOptions): LayoutNames {\n return {\n tags: options.tags ?? [\"layout\", \"part\"],\n source: options.layoutSourceAttribute ?? \"src\",\n dataSource: options.dataSourceAttribute ?? \"dataSource\",\n dataJson: options.dataJsonAttribute ?? \"dataJson\",\n alwaysInclude: options.alwaysIncludeAttribute ?? \"always-include\",\n addAttribute: options.addAttributeAttribute ?? \"add-attr\",\n removeAttribute: options.removeAttributeAttribute ?? \"remove-attr\",\n };\n}\n\n/** Whether a path is a file the tags inline: one named after a tag, `main.layout.html` say. */\nexport function isLayoutFile(file: string, names: LayoutNames): boolean {\n const fileName = basename(file);\n return names.tags.some(tag => fileName.endsWith(`.${tag}.html`));\n}\n\n/** Whether an attribute adds or removes a boolean attribute. */\nexport function isConditionalAttribute(name: string, names: LayoutNames): boolean {\n return name.startsWith(`${names.addAttribute}-`) || name.startsWith(`${names.removeAttribute}-`);\n}\n","import { checkFileExists, checkJsonObject, isDynamic } from \"../../helpers/lsp-checks.ts\";\nimport { findPlaceholders } from \"./fill-placeholders.ts\";\nimport { isConditionalAttribute, isLayoutFile } from \"./options.ts\";\n\nimport type { LayoutNames } from \"./options.ts\";\nimport type {\n AttributeInfo,\n DocumentInfo,\n ElementInfo,\n EmbeddedLanguage,\n HTMLDataV1,\n IAttributeData,\n ITagData,\n Plugin,\n ProblemReporter,\n} from \"@staticbolt/core\";\n\n/** The tags and attributes the plugin adds to HTML, for completion and hover. */\nexport function htmlData(names: LayoutNames): HTMLDataV1 {\n const layoutAttributes: IAttributeData[] = [\n { name: names.source, description: \"The path to the layout to use.\" },\n { name: names.dataSource, description: \"The path for a JSON file containing data for the layout.\" },\n { name: names.dataJson, description: \"The layout data in JSON format.\" },\n ];\n\n const alwaysInclude: IAttributeData = {\n name: names.alwaysInclude,\n description:\n \"When using a layout more than once on the same page. Always include this script/style/link[rel='stylesheet'] even if it is already present.\",\n valueSet: \"v\",\n };\n\n const alwaysIncludeDescription =\n `Adds the \\`${names.alwaysInclude}\\` attribute, which gives this tag one copy per layout instance` +\n \" instead of the single copy a layout used more than once on the same page emits.\";\n\n const tags: ITagData[] = [\n { name: \"script\", description: alwaysIncludeDescription, attributes: [alwaysInclude] },\n { name: \"link\", description: alwaysIncludeDescription, attributes: [alwaysInclude] },\n { name: \"style\", description: alwaysIncludeDescription, attributes: [alwaysInclude] },\n ];\n\n for (const tag of names.tags) {\n tags.push({ name: tag, description: `This tag allows inlining a \\`${tag}\\` file.`, attributes: layoutAttributes });\n }\n\n return {\n version: 1.1,\n tags,\n globalAttributes: [\n {\n name: names.addAttribute,\n description:\n \"Inside a layout file only.\" +\n \" Prefix for conditionally adding boolean attributes.\" +\n \" Append the target attribute name as a suffix — `add-attr-open`, `add-attr-disabled`, etc.\" +\n \" The value is a JS expression evaluated after placeholder resolution;\" +\n ' if it is non-empty and not `\"false\"`, the named attribute is added to the element.' +\n \" Multiple `add-attr-*` attributes can appear on the same element.\",\n },\n {\n name: names.removeAttribute,\n description:\n \"Inside a layout file only.\" +\n \" Prefix for conditionally removing boolean attributes.\" +\n \" Append the target attribute name as a suffix — `remove-attr-open`, `remove-attr-disabled`, etc.\" +\n \" The value is a JS expression evaluated after placeholder resolution;\" +\n ' if it is non-empty and not `\"false\"`, the named attribute is removed from the element.' +\n \" Multiple `remove-attr-*` attributes can appear on the same element.\",\n },\n ],\n };\n}\n\n/** The placeholders of layout files, as JavaScript that sees `$data`. */\nexport function embeddedLanguages(names: LayoutNames): EmbeddedLanguage[] {\n return [\n {\n name: \"placeholders\",\n filter: file => isLayoutFile(file, names),\n findRegions: document => findPlaceholders(document.text),\n prelude: \"declare const $data: Record<string, any>;\",\n },\n ];\n}\n\n/** Checks the layout tags of a document, and that the conditional attributes sit in a layout file. */\nexport function validate(names: LayoutNames): NonNullable<Plugin[\"lspValidate\"]> {\n return (document, report) => {\n const layoutTags = document.select(...names.tags);\n\n for (const element of layoutTags) {\n checkLayoutTag(element, document, report, names);\n }\n\n if (isLayoutFile(document.file, names)) {\n return;\n }\n\n // A markdown file may be rendered inside a layout, where the conditional attributes do work\n if (document.file.endsWith(\".md\")) {\n return;\n }\n\n // Conditional attributes only mean something where placeholders are filled\n for (const element of document.elements) {\n for (const attribute of element.attributes) {\n if (!isConditionalAttribute(attribute.name, names)) continue;\n\n report.warn(attribute.nameRange, `\"${attribute.name}\" only works inside a layout file`);\n }\n }\n };\n}\n\n/** A layout tag points at a file named after it, and its data attributes point at a JSON file and hold a JSON object. */\nfunction checkLayoutTag(element: ElementInfo, document: DocumentInfo, report: ProblemReporter, names: LayoutNames): void {\n const source = element.attribute(names.source);\n const dataSource = element.attribute(names.dataSource);\n const dataJson = element.attribute(names.dataJson);\n\n if (!source?.value) {\n report.error(element, `<${element.name}> needs a \"${names.source}\" pointing at a .${element.name}.html file`);\n }\n\n if (source) {\n checkFileExists(source, document, report);\n checkFileSuffix(source, report);\n }\n\n if (dataSource) {\n checkFileExists(dataSource, document, report);\n }\n\n if (dataJson) {\n checkJsonObject(dataJson, report);\n }\n}\n\n/** A tag inlines files named after it, so `<part>` takes a `.part.html` file. */\nfunction checkFileSuffix(source: AttributeInfo, report: ProblemReporter): void {\n if (!source.value) return;\n if (isDynamic(source.value)) return;\n\n const suffix = `.${source.element.name}.html`;\n if (source.value.endsWith(suffix)) return;\n\n report.warn(source, `<${source.element.name}> takes a file ending in \"${suffix}\"`);\n}\n","import { METADATA_TYPES, type HtmlMetadata, type MetadataBase, type TextAssetMetadata } from \"../../types/metadata.ts\";\nimport { isHtmlMetadata, isMarkdownMetadata, isTextAssetMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { basename, dirname, join } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { readJsonFile } from \"../../utilities/read-json-file.ts\";\nimport { mergeMaps } from \"../../utilities/utilities.ts\";\nimport { fillLayoutPlaceholders } from \"./fill-placeholders.ts\";\nimport { applyConditionalAttributes, dropRepeatedAssets, fillSlots, instanceKey, wrapMarkdownInLayout } from \"./inline-layout.ts\";\nimport { embeddedLanguages, htmlData, validate } from \"./lsp.ts\";\nimport { isLayoutFile, resolveLayoutNames } from \"./options.ts\";\n\nimport type { HtmlLayoutOptions } from \"./options.ts\";\nimport type { MetadataSource, Plugin } from \"@staticbolt/core\";\n\nexport type { HtmlLayoutOptions } from \"./options.ts\";\n\ninterface HtmlLayoutMetadata extends HtmlMetadata {\n hash: string;\n}\n\n/**\n * Composes pages out of reusable \"<layout>\" and \"<part>\" files (tag names configurable via HtmlLayoutOptions). The tag is\n * replaced by the file it points at, the tag's children are distributed into the file's \"<slot>\" elements, and the scripts and\n * styles the file declares are merged into the page.\n *\n * Attributes on the tag:\n *\n * - \"src\": the file to inline. Its name must end with \".<tag>.html\", so \"<part>\" loads \"*.part.html\".\n * - \"dataSource\" and \"dataJson\": data for the file's placeholders, as a path to a JSON file and as an inline JSON string.\n * - Anything else on the tag is data as well.\n *\n * Inside the file, \"{{ expression }}\" is evaluated as JavaScript with the data exposed as \"$data\" (a leading backslash escapes a\n * placeholder, and an expression returning undefined or an object is an error), while \"add-attr-<name>\" and \"remove-attr-<name>\"\n * toggle a boolean attribute when their value is non-empty and not \"false\".\n *\n * Notes:\n *\n * - Data precedence, lowest first: the \"dataSource\" file, then \"dataJson\", then the tag's own attributes.\n * - Layouts nest, and a page is rescanned after each expansion, so a layout can pull in further layouts and parts.\n * - Markdown pages take their layout from front matter: a \"layout\" or \"part\" key names the file, the other keys are data.\n * - Using the same layout twice on one page emits its scripts, styles and stylesheet links once; \"always-include\" opts a tag out of\n * that and gives it one copy per instance.\n * - Layout files never reach the output on their own, and editing one recompiles every page and layout that pulls it in.\n * - In production an instance is rendered once per file and attribute set, then cloned for the identical ones.\n */\nexport function htmlLayoutPlugin(options: HtmlLayoutOptions = {}): Plugin {\n const names = resolveLayoutNames(options);\n const layoutTags = names.tags;\n const sourceAttribute = names.source;\n const dataSourceAttribute = names.dataSource;\n const dataJsonAttribute = names.dataJson;\n const alwaysIncludeAttribute = names.alwaysInclude;\n const query = layoutTags.join(\",\");\n\n const printFmtError = PrintFormattedError.create({ function: htmlLayoutPlugin });\n\n const htmlLayoutMetadataCache: HtmlLayoutMetadata[] = [];\n\n /**\n * @key dataSource path\n * @value contents\n */\n const dataSourceCache = new Map<string, Record<string, unknown>>();\n\n function isLayoutPath(path: string): boolean {\n return isLayoutFile(path, names);\n }\n\n return {\n name: \"html-layout\",\n\n load(content, relativePath, { type }) {\n if (type && !layoutTags.includes(type)) return;\n\n if (!isLayoutPath(relativePath)) return;\n\n const textAssetMetadata: TextAssetMetadata = {\n type: METADATA_TYPES.TextAsset,\n filePath: relativePath,\n id: relativePath,\n code: content,\n directDependencies: new Set(),\n };\n\n this.emitExclude.add(textAssetMetadata);\n\n return textAssetMetadata;\n },\n\n sourcesProvider(metadata) {\n const sources: MetadataSource[] = [];\n\n if (isHtmlMetadata(metadata)) {\n const elements = metadata.ast.querySelectorAll(query);\n\n for (const node of elements) {\n const source = node.getAttribute(sourceAttribute);\n if (source) {\n sources.push({\n get source() {\n return source;\n },\n set source(newValue) {\n node.setAttribute(sourceAttribute, newValue);\n },\n });\n }\n\n const dataSource = node.getAttribute(dataSourceAttribute);\n if (dataSource) {\n sources.push({\n get source() {\n return dataSource;\n },\n set source(newValue) {\n node.setAttribute(dataSourceAttribute, newValue);\n },\n });\n }\n }\n }\n\n if (isMarkdownMetadata(metadata)) {\n for (const [key, source] of Object.entries(metadata.ast.frontmatter)) {\n if (!source) continue;\n\n if (layoutTags.includes(key) || key === dataSourceAttribute) {\n sources.push({\n get source() {\n return source;\n },\n set source(newValue) {\n metadata.ast.frontmatter[key] = newValue;\n },\n });\n }\n }\n }\n\n return sources;\n },\n\n resolveCompileList(compileSet, event, id) {\n if (event !== \"change\") return;\n\n // Update the dataSource cache and add relaying layouts to the compile list\n if (dataSourceCache.has(id)) {\n const [newJson, metadataError] = readJsonFile<Record<string, unknown>>(join(this.root, id));\n if (metadataError) {\n printFmtError(metadataError, { filePath: id });\n return;\n }\n\n dataSourceCache.set(id, newJson);\n\n for (const metadata of this.metadataList) {\n if (isTextAssetMetadata(metadata) && isLayoutPath(metadata.id) && metadata.directDependencies.has(id)) {\n compileSet.add(metadata.id);\n }\n }\n }\n\n for (const id of Array.from(compileSet)) {\n if (!isLayoutPath(id)) continue;\n\n const queue = [id];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n\n for (const metadata of this.metadataList) {\n if (!(metadata.directDependencies.has(current) && !compileSet.has(metadata.id))) {\n continue;\n }\n\n compileSet.add(metadata.id);\n\n // only keep climbing if it's also a layout\n if (isLayoutPath(metadata.id)) {\n queue.push(metadata.id);\n }\n }\n }\n }\n },\n\n async transform(metadata) {\n if (isHtmlMetadata(metadata)) {\n let node = metadata.ast.querySelector(query);\n\n const skip = () => {\n if (!node) return;\n node.replaceWith(node.innerHTML);\n node = metadata.ast.querySelector(query);\n };\n\n while (node) {\n const tag = node.tagName.toLowerCase();\n\n const source = node.getAttribute(sourceAttribute);\n if (!source) {\n printFmtError(`The tag <${tag}> is missing the attribute \"${sourceAttribute}\"`, {\n node,\n filePath: metadata.id,\n });\n skip();\n continue;\n }\n\n const layoutRelativePath = join(dirname(metadata.filePath), source);\n\n const layoutAssetMetadata = this.findMetadata<TextAssetMetadata>({ id: layoutRelativePath });\n if (!isTextAssetMetadata(layoutAssetMetadata)) {\n printFmtError(`Failed to load layout metadata`, { node, filePath: metadata.id });\n skip();\n continue;\n }\n\n if (!basename(layoutRelativePath).endsWith(`.${tag}.html`)) {\n printFmtError(`Usage of the tag <${tag}> is incorrect. The layout file name does not end with \"${tag}.html\"`, {\n node,\n filePath: metadata.id,\n level: \"warning\",\n });\n }\n\n // --- Read data source ---\n const fillData: Record<string, unknown> = {};\n\n const dataSourcePath = node.getAttribute(dataSourceAttribute);\n if (dataSourcePath) {\n const dataSourceRelativePath = join(dirname(metadata.filePath), dataSourcePath);\n layoutAssetMetadata.directDependencies.add(dataSourceRelativePath);\n\n // From cache\n if (dataSourceCache.has(dataSourceRelativePath)) {\n Object.assign(fillData, dataSourceCache.get(dataSourceRelativePath));\n }\n // From file\n else {\n const [dataSource, fillError] = readJsonFile<Record<string, unknown>>(join(this.root, dataSourceRelativePath));\n if (fillError) {\n printFmtError(fillError, { node, filePath: metadata.id });\n skip();\n continue;\n }\n\n dataSourceCache.set(dataSourceRelativePath, dataSource);\n Object.assign(fillData, dataSource);\n }\n }\n\n const dataJson = node.getAttribute(dataJsonAttribute);\n if (dataJson) {\n try {\n Object.assign(fillData, JSON.parse(dataJson));\n } catch (error) {\n printFmtError(`Failed to parse JSON data`, error as Error, { node, filePath: metadata.id });\n skip();\n continue;\n }\n }\n\n Object.assign(fillData, node.attributes);\n\n const [layoutCode, fillError] = fillLayoutPlaceholders(layoutAssetMetadata.code, fillData);\n if (fillError) {\n printFmtError(fillError, { node, filePath: metadata.id });\n skip();\n continue;\n }\n\n let layoutHtmlMetadata: HtmlLayoutMetadata | undefined;\n\n const hash = instanceKey(node, names);\n\n // Check cache only in production\n if (this.production) {\n const cachedMetadata = htmlLayoutMetadataCache.find(\n metadata => metadata.id === layoutRelativePath && metadata.hash === hash\n );\n\n if (cachedMetadata) {\n layoutHtmlMetadata = this.clone(cachedMetadata);\n }\n }\n\n // Create new\n if (!layoutHtmlMetadata) {\n // Code string to metadata.\n const layoutMetadata = await this.load(layoutRelativePath, { code: layoutCode, type: \"html\" });\n if (!isHtmlLayoutMetadata(layoutMetadata)) {\n printFmtError(`Failed to parse <${tag}> code`, { node, filePath: metadata.id });\n skip();\n continue;\n }\n\n const metadataList = await this.resolveAndLoad(layoutMetadata);\n\n // Merge except for the layout metadata (first one)\n this.addMetadata(metadataList.slice(1));\n\n // Only transform discovered metadata list until this point in time\n await this.transformAndSync(metadataList);\n\n applyConditionalAttributes(layoutMetadata, names);\n\n // Cache only in production\n if (this.production) {\n layoutMetadata.hash = hash;\n htmlLayoutMetadataCache.push(layoutMetadata);\n layoutHtmlMetadata = this.clone(layoutMetadata);\n }\n // In development use the original metadata\n else {\n layoutHtmlMetadata = layoutMetadata;\n }\n }\n\n if (!isHtmlLayoutMetadata(layoutHtmlMetadata)) {\n printFmtError(`Failed to parse <${tag}> code`, { node, filePath: metadata.id });\n skip();\n continue;\n }\n\n dropRepeatedAssets(metadata, layoutHtmlMetadata, alwaysIncludeAttribute);\n\n // The page inlining the layout should have same direct dependencies\n for (const dependency of layoutHtmlMetadata.directDependencies) {\n metadata.directDependencies.add(dependency);\n }\n\n await this.rebase(layoutHtmlMetadata, join(this.root, metadata.filePath));\n\n fillSlots(node, layoutHtmlMetadata, layoutRelativePath, printFmtError);\n\n // Copy script and style from layout metadata to where the layout tag is inlined.\n mergeMaps(metadata.scriptsMetadataList, layoutHtmlMetadata.scriptsMetadataList);\n mergeMaps(metadata.stylesMetadataList, layoutHtmlMetadata.stylesMetadataList);\n\n node.replaceWith(layoutHtmlMetadata.ast.root);\n node = metadata.ast.querySelector(query);\n }\n\n return;\n }\n\n if (isMarkdownMetadata(metadata)) {\n wrapMarkdownInLayout(metadata, names);\n }\n },\n\n lspHtmlData() {\n return htmlData(names);\n },\n\n lspEmbeddedLanguages() {\n return embeddedLanguages(names);\n },\n\n lspValidate: validate(names),\n };\n}\n\nfunction isHtmlLayoutMetadata(metadata: MetadataBase | undefined): metadata is HtmlLayoutMetadata {\n return isHtmlMetadata(metadata);\n}\n","import { DependencyTracker } from \"../../helpers/dependency-tracker.ts\";\nimport { checkFileExists, isEmptyElement } from \"../../helpers/lsp-checks.ts\";\nimport { splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata, isMarkdownMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\n\nimport type { MetadataSource, Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlMarkdownOptions {\n /**\n * The attribute that when present on a tag will render the content as markdown.\n *\n * @default \"markdown\"\n */\n markdownAttribute?: string;\n\n /**\n * The tag name of the element that can reference a markdown file.\n *\n * @default \"markdown\"\n */\n tag?: string;\n\n /**\n * The attribute that when present on a tag will render the content as markdown.\n *\n * @default \"src\"\n */\n sourceAttribute?: string;\n}\n\n/**\n * Renders markdown inside HTML pages, from a file or from the element's own text (names configurable via HtmlMarkdownOptions).\n *\n * - An element carrying the \"markdown\" attribute has its text rendered and replaced by the resulting HTML, and loses the attribute.\n * - A \"<markdown src=...>\" tag is replaced by the rendered contents of the file it points at.\n *\n * Notes:\n *\n * - Runs in development and production alike.\n * - The rendered HTML goes through the normal pipeline (resolve, load, transform), so its own tags are processed like the rest of\n * the page and a referenced file's links are rebased onto the page that renders it.\n * - Editing a referenced markdown file recompiles the pages that render it.\n */\nexport function htmlMarkdownPlugin(options: HtmlMarkdownOptions = {}): Plugin {\n const mdAttribute = options.markdownAttribute ?? \"markdown\";\n const markdownTag = options.tag ?? \"markdown\";\n const sourceAttribute = options.sourceAttribute ?? \"src\";\n\n const dependencies = new DependencyTracker();\n\n const printFmtError = PrintFormattedError.create({ function: htmlMarkdownPlugin });\n\n return {\n name: \"html-markdown\",\n\n sourcesProvider(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const result: MetadataSource[] = [];\n\n const markdowns = metadata.ast.querySelectorAll(markdownTag);\n for (const node of markdowns) {\n const source = node.getAttribute(sourceAttribute);\n if (!source) continue;\n\n result.push({\n get source() {\n return source;\n },\n set source(newValue) {\n node.setAttribute(sourceAttribute, newValue);\n },\n });\n }\n\n return result;\n },\n\n async transform(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n // Normal HTML tag with `markdown` attribute\n // eslint-disable-next-line unicorn/require-css-escape\n const elements = metadata.ast.querySelectorAll(`[${mdAttribute}]`);\n for (const node of elements) {\n node.removeAttribute(mdAttribute);\n\n const code = node.rawText;\n if (!code) {\n printFmtError(`The element \"${node.tagName}\" with the markdown attribute \"${mdAttribute}\" is empty`, {\n node,\n filePath: metadata.id,\n });\n continue;\n }\n\n const markdownMetadata = await this.load(metadata.filePath, { code, type: \"md\" });\n if (!isMarkdownMetadata(markdownMetadata)) {\n printFmtError(\"Invalid markdown file:\", metadata.filePath, { node, filePath: metadata.id });\n continue;\n }\n\n const asHtmlString = await markdownMetadata.ast.render();\n\n const htmlMetadata = await this.load(metadata.filePath, { code: asHtmlString, type: \"html\" });\n if (!isHtmlMetadata(htmlMetadata)) {\n printFmtError(\"Invalid HTML file:\", metadata.filePath, { node, filePath: metadata.id });\n continue;\n }\n\n const metadataList = await this.resolveAndLoad(htmlMetadata);\n this.addMetadata(metadataList.slice(1));\n await this.transformAndSync(metadataList);\n\n node.set_content(htmlMetadata.ast.children);\n }\n\n const currentSources = new Set<string>();\n\n // Custom `markdown` tag that can reference a markdown file\n const markdowns = metadata.ast.querySelectorAll(markdownTag);\n for (const node of markdowns) {\n const source = node.getAttribute(sourceAttribute);\n if (!source) {\n printFmtError(`The tag <${markdownTag}> is missing the attribute \"${sourceAttribute}\"`, {\n node,\n filePath: metadata.id,\n });\n continue;\n }\n\n const [link] = splitHtmlLink(source);\n\n const sourceRelative = join(dirname(metadata.filePath), link);\n\n const markdownMetadata = await this.load(sourceRelative, { type: \"md\" });\n if (!isMarkdownMetadata(markdownMetadata)) {\n printFmtError(\"Invalid markdown file:\", sourceRelative, { node, filePath: metadata.id });\n continue;\n }\n\n currentSources.add(sourceRelative);\n\n const asHtmlString = await markdownMetadata.ast.render();\n\n const htmlMetadata = await this.load(sourceRelative, { code: asHtmlString, type: \"html\" });\n if (!isHtmlMetadata(htmlMetadata)) {\n printFmtError(\"Invalid HTML file:\", sourceRelative, { node, filePath: metadata.id });\n continue;\n }\n\n const metadataList = await this.resolveAndLoad(htmlMetadata);\n this.addMetadata(metadataList.slice(1));\n await this.transformAndSync(metadataList);\n await this.rebase(htmlMetadata, join(this.root, metadata.filePath));\n\n node.replaceWith(...htmlMetadata.ast.children);\n }\n\n dependencies.update(metadata.id, currentSources);\n },\n\n onFileEvent(event, id) {\n if (event === \"unlink\") {\n dependencies.delete(id);\n }\n },\n\n resolveCompileList(compileSet, event) {\n if (event !== \"change\") return;\n\n for (const id of Array.from(compileSet)) {\n const importers = dependencies.getImporters(id);\n\n for (const importer of importers) {\n compileSet.add(importer);\n }\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n globalAttributes: [{ name: mdAttribute, description: \"Render the contents of this element as markdown.\", valueSet: \"v\" }],\n tags: [\n {\n name: markdownTag,\n description: \"This tag lets you render Markdown files inside HTML.\",\n attributes: [{ name: sourceAttribute, description: \"The path to the external markdown file.\" }],\n },\n ],\n };\n },\n\n lspValidate(document, report) {\n const markdowns = document.select(markdownTag);\n\n for (const element of markdowns) {\n const source = element.attribute(sourceAttribute);\n\n if (!source?.value) {\n report.error(element, `<${markdownTag}> needs a \"${sourceAttribute}\" pointing at a markdown file`);\n continue;\n }\n\n checkFileExists(source, document, report);\n }\n\n for (const element of document.elements) {\n const markdown = element.attribute(mdAttribute);\n if (!markdown) continue;\n if (!isEmptyElement(element, document)) continue;\n\n report.warn(markdown.nameRange, `There is no markdown in this <${element.name}> to render`);\n }\n },\n };\n}\n","import { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\nimport type { HTMLElement, Node } from \"@staticbolt/node-html-parser\";\n\ninterface StyleEntry {\n node: Node;\n metadataID: string;\n attrKey: string;\n}\n\n/**\n * Merges consecutive \"<style>\" tags in the \"<head>\" into a single tag, cutting the number of style blocks a page ships.\n *\n * Notes:\n *\n * - Production only, and only inside \"<head>\"; styles anywhere else are left alone.\n * - A run is only merged when the tags carry identical attributes, and a \"<link rel=stylesheet>\" between them breaks the run, so\n * the cascade order never changes.\n * - The merged rules are appended to the first tag of the run and the others are removed.\n */\nexport function htmlMergeStylesPlugin(): Plugin {\n function getAttributeKey(element: HTMLElement): string {\n const attributes = { ...element.attributes };\n delete attributes[CUSTOM_ATTRIBUTES.MetadataID];\n\n return Object.entries(attributes)\n .toSorted(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => `${k}=${v}`)\n .join(\"|\");\n }\n\n return {\n name: \"html-merge-styles\",\n\n postTransform() {\n if (!this.production) return;\n\n for (const metadata of this.metadataList) {\n if (!isHtmlMetadata(metadata)) continue;\n\n // Only merge styles in the head tag\n const head = metadata.ast.querySelector(\"head\");\n if (!head) continue;\n\n const headElements = head.querySelectorAll(\"style, link[rel=stylesheet]\");\n\n let currentGroup: StyleEntry[] = [];\n\n const flushGroup = () => {\n if (currentGroup.length >= 2) {\n const [first, ...rest] = currentGroup;\n const firstAst = metadata.stylesMetadataList.get(first.metadataID)!.ast;\n\n for (const { node, metadataID } of rest) {\n const styleMetadata = metadata.stylesMetadataList.get(metadataID);\n if (!styleMetadata) continue;\n\n // Merge AST nodes into the first root\n styleMetadata.ast.each(node => {\n node.parent = undefined;\n firstAst.append(node);\n });\n\n metadata.stylesMetadataList.delete(metadataID);\n node.remove();\n }\n }\n\n currentGroup = [];\n };\n\n for (const element of headElements) {\n // A stylesheet link breaks the consecutive chain — flush and reset\n if (element.tagName.toLowerCase() === \"link\") {\n flushGroup();\n continue;\n }\n\n const metadataID = element.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!metadataID) continue;\n\n const styleMetadata = metadata.stylesMetadataList.get(metadataID);\n if (!styleMetadata) continue;\n\n const attributeKey = getAttributeKey(element);\n\n // If the group is empty or attr signature matches, continue the group\n // Otherwise flush the current group and start a new one\n if (currentGroup.length > 0 && currentGroup[0].attrKey !== attributeKey) {\n flushGroup();\n }\n\n currentGroup.push({ node: element, metadataID, attrKey: attributeKey });\n }\n\n // Flush any remaining group at end of head\n flushGroup();\n }\n },\n };\n}\n","import { isValidRelativePath, splitHtmlLink } from \"../../../utilities/html-links.ts\";\nimport { isPackageMetadata, isTextAssetMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { basename, dirname, extname, join, relative, replaceExtension } from \"../../../utilities/path.ts\";\nimport { safeReadFileSync } from \"../../../utilities/read-file.ts\";\nimport { cloneObject } from \"../../../utilities/utilities.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\n/**\n * The baseline of the pipeline: reads files from disk, resolves and rebases links, and clones or prints the metadata kinds no\n * other plugin claims (text assets and bundled packages).\n *\n * Notes:\n *\n * - A resolved link keeps the style it was written in: an extensionless or directory-style link to a page stays that way, while a\n * script path resolving to \".ts\", \".tsx\" or \".jsx\" is rewritten to \".js\", which is what actually ships.\n * - Query strings and hashes survive both resolving and rebasing, and a link that ends up pointing at its own page becomes \"./\".\n */\nexport function coreBasePlugin(): Plugin {\n const JS_EXTENSIONS = new Set([\".js\", \".mjs\", \".cjs\", \".jsx\", \".ts\", \".mts\", \".cts\", \".tsx\"]);\n\n return {\n name: \"core-base\",\n\n read(absolutePath) {\n const [fileContent, readFileError] = safeReadFileSync(absolutePath, \"utf8\");\n if (readFileError) {\n return;\n }\n\n return fileContent;\n },\n\n onFileEvent(event, filePath) {\n if (event === \"unlink\") {\n this.resolver.files.delete(filePath);\n }\n },\n\n clone(metadata) {\n if (isTextAssetMetadata(metadata) || isPackageMetadata(metadata)) {\n return cloneObject(metadata);\n }\n },\n\n stringify(metadata) {\n if (isTextAssetMetadata(metadata) || isPackageMetadata(metadata)) {\n return metadata.code;\n }\n },\n\n resolveSource(source, filePath, metadata) {\n if (!isValidRelativePath(source)) return;\n\n const resolveResult = this.resolver.resolve(source, filePath);\n if (!resolveResult) {\n this.log.error(`Failed to resolve \"${source}\" found in \"${filePath}\" of type \"${metadata.type}\"`);\n return;\n }\n\n let resolved = resolveResult.path;\n\n // The browser can only load JS files\n if (JS_EXTENSIONS.has(extname(resolved))) {\n resolved = replaceExtension(resolved, \".js\");\n }\n\n resolved = relative(join(this.root, dirname(filePath)), resolved);\n\n if (!resolveResult.isFileAlias) {\n resolved = matchSourceStyle(source, resolved);\n }\n\n // case: \"./\" with suffix \"/\" -> \".//\" which is not a valid link\n if (resolved.endsWith(\"/\") && resolveResult.suffix.startsWith(\"/\")) {\n resolved = resolved.slice(0, -1);\n }\n\n resolved += resolveResult.suffix;\n\n const dependencyID = resolveResult.exists ? relative(this.root, resolveResult.path) : undefined;\n\n return { source: resolved, dependencyID };\n },\n\n rebaseSource(source, filePath, newAbsolutePath) {\n if (!isValidRelativePath(source)) return;\n\n const [link, suffix] = splitHtmlLink(source);\n\n // Already a self-reference (pointing to own directory)\n if ([\"index.html\", \"index.md\"].includes(basename(filePath)) && [\"./\", \".\", \"\"].includes(link)) {\n return source;\n }\n\n const oldAbsolutePath = join(this.root, filePath);\n const sourceAbsolute = join(dirname(oldAbsolutePath), link).replace(/\\/$/, \"\");\n\n let rebased = relative(dirname(newAbsolutePath), sourceAbsolute);\n\n // Going to be a self-reference after rebasing\n if (basename(newAbsolutePath) === \"index.html\" && isSelfReference(sourceAbsolute, newAbsolutePath)) {\n rebased = \"./\";\n }\n\n // Preserve \"/\" in this edge case\n if (link === \"./\" && !rebased.endsWith(\"/\")) {\n rebased += \"/\";\n }\n\n // Avoid double-slash\n if (rebased.endsWith(\"/\") && suffix.startsWith(\"/\")) {\n rebased = rebased.slice(0, -1);\n }\n\n rebased += suffix;\n\n return rebased;\n },\n\n onMetadataRebase(metadata, _, newAbsolutePath) {\n metadata.filePath = relative(this.root, newAbsolutePath);\n },\n };\n}\n\n/**\n * Adjusts a resolved path to match the style of the original link.\n *\n * Preserves whether the original link used an explicit extension, no extension, or an index-based directory style. Only applies\n * to `.html` and `.md` resolved paths.\n *\n * @example\n * matchSourceStyle(\"./auth/login/\", \"./auth/login.html\"); // \"./auth/login\"\n * matchSourceStyle(\"./auth/login/\", \"./auth/login/index.html\"); // \"./auth/login\"\n * matchSourceStyle(\"./auth/login\", \"./auth/login.html\"); // \"./auth/login\"\n * matchSourceStyle(\"./auth/login.html\", \"./auth/login.html\"); // \"./auth/login.html\"\n */\nfunction matchSourceStyle(originalSource: string, resolvedPath: string): string {\n const [originalLink] = splitHtmlLink(originalSource);\n\n const resolvedExtension = extname(resolvedPath);\n\n // Only target links to `.html` or `.md`\n if (resolvedExtension !== \".html\" && resolvedExtension !== \".md\") {\n return resolvedPath;\n }\n\n // Preserve explicit extensions\n const originalExtension = extname(originalLink);\n if (originalExtension === \".html\" || originalExtension === \".md\") {\n return resolvedPath;\n }\n\n const resolvedNoExtension = replaceExtension(resolvedPath, \"\");\n const resolvedFilename = basename(resolvedPath, resolvedExtension);\n\n // Match using index.html or index.md\n if (resolvedFilename === \"index\") {\n return dirname(resolvedPath);\n }\n\n // Match no extension\n return resolvedNoExtension;\n}\n\nexport function isSelfReference(sourceAbsolute: string, filePathAbsolute: string): boolean {\n const sourceExtension = extname(sourceAbsolute);\n\n // Only look for sources points to directories, .html, or .md\n if (![\".html\", \".md\", \"\"].includes(sourceExtension)) {\n return false;\n }\n\n // Exact match\n if (sourceAbsolute === filePathAbsolute) {\n return true;\n }\n\n // Try with .html\n const htmlExtensionCandidate = replaceExtension(sourceAbsolute, \".html\");\n if (htmlExtensionCandidate === filePathAbsolute) {\n return true;\n }\n\n // Try with .md\n const mdExtensionCandidate = replaceExtension(sourceAbsolute, \".md\");\n if (mdExtensionCandidate === filePathAbsolute) {\n return true;\n }\n\n // Try index.html\n const indexHtmlCandidate = join(sourceAbsolute, \"index.html\");\n if (indexHtmlCandidate === filePathAbsolute) {\n return true;\n }\n\n // Try index.md\n const indexMdCandidate = join(sourceAbsolute, \"index.md\");\n return indexMdCandidate === filePathAbsolute;\n}\n","import { dirname, extname, isSubpath, join, normalize, parse, replaceExtension } from \"../../utilities/path.ts\";\n\n/**\n * - Help to calculate the new html path when compiling html files in the pages directory\n * - For example: `./pages/home.html` => `./home/index.html`\n *\n * @returns - The new html path or the original path if it is not in the Pages directory\n */\nexport function calculatePagePath(originalPath: string, pagesDirectory: string): string {\n if (extname(originalPath) === \".md\") {\n originalPath = replaceExtension(originalPath, \".html\");\n }\n\n const isInPagesDirectory = isSubpath(pagesDirectory, dirname(originalPath));\n if (!isInPagesDirectory) {\n return normalize(originalPath);\n }\n\n const fileName = parse(originalPath).name; // without extension\n const extension = extname(originalPath);\n\n let newPath = cutLeadingSubpath(originalPath, pagesDirectory);\n\n // Only add \"index\" for files with an extension otherwise its a directory\n if (extension && fileName !== \"index\") {\n newPath = join(dirname(newPath), fileName, \"index\" + extension);\n }\n\n return newPath;\n}\n\n/**\n * - Cut the leading subpath from a path\n *\n * @example\n * cutLeadingSubpath('/a/b/c', '/a') => 'b/c'\n *\n * @param pathToCut - The path to cut\n * @param leadingSubpath - The leading subpath\n * @returns - The path without the leading subpath\n */\nfunction cutLeadingSubpath(pathToCut: string, leadingSubpath: string): string {\n const pathParts = normalize(pathToCut).split(\"/\");\n const subpathParts = normalize(leadingSubpath).split(\"/\");\n const withCut = pathParts\n .map((part, index) => (index >= subpathParts.length ? part : part === subpathParts[index] ? \"\" : part))\n .filter(Boolean);\n\n return normalize(withCut.join(\"/\"));\n}\n","import type { ValueOrError } from \"../../utilities/value-or-error.ts\";\nimport type { RouteData } from \"./dynamic-routes.ts\";\n\n/** (any){{any}} */\nconst placeholderRe = /(\\\\)?{{\\s*([\\s\\S]*?)\\s*}}/g;\n\n/** `{{ JavaScript expression }}` */\nexport function fillPlaceholders(html: string, routeData: RouteData): ValueOrError<string> {\n const errors: Error[] = [];\n\n const result = html.replace(placeholderRe, (match: string, escape: string, content: string) => {\n if (escape === \"\\\\\") {\n return match.slice(1);\n }\n\n const [expression, executeError] = executeExpression(content, routeData);\n if (executeError) {\n errors.push(executeError);\n return \"\";\n }\n\n return expression;\n });\n\n // join errors\n if (errors.length > 0) {\n const combinedMessage = [\n \"Failed to fill placeholders\",\n ...errors.map((error, index) => ` [${index + 1}] ${error.message}`),\n ].join(\"\\n\");\n\n return [null, new AggregateError(errors, combinedMessage)];\n }\n\n return [result, null];\n}\n\ntype FunctionType = (parameters: RouteData[\"params\"], properties: Required<RouteData>[\"props\"]) => unknown;\nconst functionCache = new Map<string, FunctionType>();\n\nfunction executeExpression(expressionString: string, data: RouteData): ValueOrError<string> {\n try {\n let function_ = functionCache.get(expressionString);\n if (!function_) {\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n function_ = new Function(\"$params\", \"$props\", `return ${expressionString}`) as FunctionType;\n functionCache.set(expressionString, function_);\n }\n\n const output = function_(data.params, data.props ?? {});\n\n if (output === undefined) {\n return [null, new Error(`Expression found in the placeholder {{ ${expressionString} }} returned undefined`)];\n }\n\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n const asString = String(output);\n\n if (asString === \"[object Object]\") {\n return [null, new Error(`Expression found in the placeholder {{ ${expressionString} }} returned an object`)];\n }\n\n return [asString, null];\n } catch (error) {\n return [null, new Error(`Failed to execute expression: ${expressionString}\\n ${(error as Error).message}`)];\n }\n}\n","import * as z from \"zod/v4\";\n\nimport { executeJsInVM } from \"../../helpers/execute-js-in-vm.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { Log } from \"../../utilities/logger.ts\";\nimport { isHtmlMetadata, isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { join, relative } from \"../../utilities/path.ts\";\nimport { printFmtError } from \"../../utilities/print-formatted-error.ts\";\nimport { fillPlaceholders } from \"./fill-placeholders.ts\";\n\nimport type { ValueOrError } from \"../../utilities/value-or-error.ts\";\nimport type { App, HtmlMetadata, ScriptMetadata } from \"@staticbolt/core\";\n\nconst getStaticPathsSchema = z.array(\n z.object({\n params: z.record(z.string(), z.string()),\n props: z.record(z.string(), z.string()).optional(),\n })\n);\n\ntype GetStaticPathsResults = z.infer<typeof getStaticPathsSchema>;\n\nexport type RouteData = GetStaticPathsResults[number];\n\nexport async function handleDynamicRoutes(this: App, htmlMetadata: HtmlMetadata) {\n // Collect executable scripts that need to be executed to extract routes data\n const executableScripts = collectExecutableScripts.call(this, htmlMetadata);\n\n const routesData: RouteData[] = [];\n\n for (const scriptMetadata of executableScripts) {\n await this.resolve(scriptMetadata);\n\n await this.transform(scriptMetadata);\n\n // TODO: Load dependencies\n\n // Execute and collect routes data\n const [parameters, collectError] = await collectParameters.call(this, htmlMetadata, scriptMetadata);\n if (collectError) {\n printFmtError(collectError, { filePath: htmlMetadata.id });\n continue;\n }\n\n routesData.push(...parameters);\n }\n\n const generatedRoutes: HtmlMetadata[] = [];\n\n const templateString = await this.stringify(htmlMetadata);\n\n for (const routeData of routesData) {\n // Fill and populate\n const [pageString, fillError] = fillPlaceholders(templateString, routeData);\n if (fillError) {\n printFmtError(fillError, { filePath: htmlMetadata.id });\n continue;\n }\n\n // String to HTML metadata\n const generatedMetadata = await this.load(htmlMetadata.filePath, { code: pageString, type: \"html\" });\n if (!isHtmlMetadata(generatedMetadata)) {\n Log.error(\"Expected HTML metadata\");\n continue;\n }\n\n const metadataList = await this.resolveAndLoad(generatedMetadata);\n\n // Remove generated metadata (first one)\n metadataList.shift();\n\n // Add discovered metadata\n this.addMetadata(metadataList);\n\n const newFilePath = fillDynamicPath(htmlMetadata.filePath, routeData.params);\n await this.rebase(generatedMetadata, join(this.root, newFilePath));\n\n // Remove existing\n const existingIndex = generatedRoutes.findIndex(existing => existing.filePath === generatedMetadata.filePath);\n if (existingIndex !== -1) {\n generatedRoutes.splice(existingIndex, 1);\n }\n\n generatedRoutes.push(generatedMetadata);\n }\n\n return { routesData, generatedRoutes };\n}\n\nfunction collectExecutableScripts(this: App, htmlMetadata: HtmlMetadata): ScriptMetadata[] {\n const attribute = \"params\";\n const query = `script[${attribute}]`;\n\n const result: ScriptMetadata[] = [];\n\n const scripts = htmlMetadata.ast.querySelectorAll(query);\n\n for (const node of scripts) {\n // Script with content\n const metadataID = node.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (metadataID) {\n const inlinedMetadata = htmlMetadata.scriptsMetadataList.get(metadataID);\n if (!inlinedMetadata) {\n printFmtError(\"Failed to execute script tag. Missing metadata\", { node, filePath: htmlMetadata.id });\n continue;\n }\n\n result.push(inlinedMetadata);\n continue;\n }\n\n // Script with src attribute\n const source = node.getAttribute(\"src\");\n if (!source) {\n printFmtError('Failed to execute script tag. Missing \"src\" attribute', { node, filePath: htmlMetadata.id });\n continue;\n }\n\n const resolved = this.resolver.resolve(source, htmlMetadata.id);\n if (!resolved || !resolved.exists) {\n printFmtError(\"Failed to execute script tag. Missing file\", { node, filePath: htmlMetadata.id });\n continue;\n }\n\n const relativeToRoot = relative(this.root, resolved.path);\n\n const fileMetadata = this.findMetadata({ filePath: relativeToRoot });\n if (!isScriptMetadata(fileMetadata)) {\n printFmtError(\"Failed to execute script tag. Missing metadata\", { node, filePath: htmlMetadata.id });\n continue;\n }\n\n result.push(fileMetadata);\n }\n\n // remove script tags after executing\n for (const node of htmlMetadata.ast.querySelectorAll(query)) {\n node.remove();\n }\n\n return result;\n}\n\n/** Fills a dynamic route path with the given params. Supports [param] and [...param] (catch-all) segments. */\nfunction fillDynamicPath(path: string, parameters: Record<string, string>): string {\n const segments = path.split(\"/\");\n const result: string[] = [];\n\n for (const segment of segments) {\n const catchAllMatch = segment.match(/^\\[\\.\\.\\.(.*)\\]$/);\n if (catchAllMatch) {\n result.push(parameters[catchAllMatch[1]] ?? \"\");\n continue;\n }\n\n const dynamicMatch = segment.match(/\\[([^\\]]+)\\]/);\n if (dynamicMatch) {\n const key = dynamicMatch[1];\n const value = parameters[key] ?? dynamicMatch[0];\n\n if (value.includes(\"/\")) {\n throw new Error(`Dynamic param \"${key}\" contains slashes. Use \"[...${key}]\" for catch-all routes.`);\n }\n\n result.push(segment.replace(/\\[([^\\]]+)\\]/, () => value));\n continue;\n }\n\n result.push(segment);\n }\n\n return result.filter(Boolean).join(\"/\");\n}\n\nasync function collectParameters(\n this: App,\n parentHtmlMetadata: HtmlMetadata,\n scriptMetadata: ScriptMetadata\n): Promise<ValueOrError<GetStaticPathsResults>> {\n const getCode = async (targetPath: string) => {\n // Entry point\n if (targetPath === scriptMetadata.filePath) {\n return await this.stringify(scriptMetadata);\n }\n\n // External file\n const foundMetadata = this.findMetadata({ filePath: targetPath });\n if (foundMetadata) {\n return await this.stringify(foundMetadata);\n }\n };\n\n const context = { window: globalThis, document: parentHtmlMetadata.ast };\n\n const [executeResult, error] = await executeJsInVM({\n root: this.root,\n entryFile: scriptMetadata.filePath,\n getCode,\n context,\n });\n\n if (error) {\n return [null, error];\n }\n\n if (!(\"getStaticPaths\" in executeResult.exports)) {\n return [null, new Error(\"Must export a function named `getStaticPaths`\")];\n }\n\n const getStaticPaths = executeResult.exports.getStaticPaths;\n if (typeof getStaticPaths !== \"function\") {\n return [null, new Error(\"Must export a function named `getStaticPaths`\")];\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n const parameters = (await getStaticPaths()) as unknown;\n\n const parseResult = getStaticPathsSchema.safeParse(parameters);\n if (!parseResult.success) {\n return [null, parseResult.error];\n }\n\n return [parseResult.data, null];\n}\n\nconst DYNAMIC_SEGMENT_RE = /\\[(\\.{3})?[a-zA-Z_][a-zA-Z0-9_]*\\]/;\n\n/** Checks if the file path is a dynamic route. E.g. `/users/[id].html`, `/users/[...slug]/profile.html` */\nexport function isDynamicRoute(path: string): boolean {\n return path.split(\"/\").some(segment => DYNAMIC_SEGMENT_RE.test(segment));\n}\n","import { globSync } from \"glob\";\n\nimport { isValidRelativePath, splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata, isMarkdownMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { basename, dirname, extname, isSubpath, join, normalize, relative } from \"../../utilities/path.ts\";\nimport { isSelfReference } from \"../core-plugins/base-plugin/base-plugin.ts\";\nimport { calculatePagePath } from \"./calculate-page-path.ts\";\nimport { handleDynamicRoutes, isDynamicRoute } from \"./dynamic-routes.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlPagesOptions {\n /**\n * Pages directory relative to the root.\n *\n * @default [\"pages\"]\n */\n pagesDir?: string;\n\n /**\n * Where to output the HTML pages relative to the output directory.\n *\n * @default \"./\"\n */\n outputDir?: string;\n}\n\n/**\n * Turns the files under the pages directory into routes: every \".html\" and \".md\" file in \"pagesDir\" is emitted at its clean URL\n * path, and the links pointing into the directory are rewritten to match.\n *\n * - \"pages/home.html\" becomes \"home/index.html\", so it is served at \"/home/\", while a file already named \"index\" keeps its place.\n * - Markdown pages are rendered to HTML first, and the markdown itself is kept out of the output.\n * - Square brackets mark a dynamic route: \"pages/users/[id].html\" is expanded into one page per entry returned by the\n * \"getStaticPaths\" export of its \"<script params>\" tag, with \"{{ $params.x }}\" and \"{{ $props.x }}\" filled in.\n *\n * Notes:\n *\n * - Rebasing goes both ways: a page's own links survive the move out of \"pagesDir\", and links from anywhere else pointing into it\n * are rewritten to the final URL.\n * - \"outputDir\" puts the whole route tree under a subdirectory of the output.\n * - The dev server resolves a request through the same computed paths, with or without the trailing \"index.html\", dynamic routes\n * included.\n */\nexport function htmlPagesPlugin(options: HtmlPagesOptions = {}): Plugin {\n const pagesDirectory = normalize(options.pagesDir ?? \"./pages\");\n const outputDirectory = normalize(options.outputDir ?? \"./\");\n\n const pagesFiles = new Set<string>();\n const dynamicPathGeneratedMap = new Map<string, Set<string>>();\n\n return {\n name: \"html-pages\",\n\n async setup() {\n if (this.production) return;\n\n this.watcher?.add(pagesDirectory);\n\n const pages = globSync(`${pagesDirectory}/**/*.{html,md}`, { cwd: this.root, nodir: true });\n\n for (let pageFile of pages) {\n pageFile = normalize(pageFile);\n\n pagesFiles.add(pageFile);\n\n if (extname(pageFile) !== \".html\" || !isDynamicRoute(pageFile)) continue;\n\n // Load dynamic routes to be able to resolve requests from dev server\n const metadata = await this.load(pageFile);\n if (metadata) {\n this.addMetadata(metadata);\n }\n }\n },\n\n async preTransform() {\n for (const htmlMetadata of Array.from(this.metadataList)) {\n if (!isHtmlMetadata(htmlMetadata)) continue;\n\n const isDynamic = isPageDirectorySubpath(htmlMetadata.filePath, pagesDirectory) && isDynamicRoute(htmlMetadata.filePath);\n if (!isDynamic) continue;\n\n // Remove any metadata with the same ID\n this.removeMetadata(this.filterMetadata({ id: htmlMetadata.id }));\n\n const { generatedRoutes } = await handleDynamicRoutes.call(this, htmlMetadata);\n\n for (const generated of generatedRoutes) {\n this.addMetadata(generated);\n\n const generatedSet = dynamicPathGeneratedMap.get(generated.id) ?? new Set();\n generatedSet.add(generated.filePath);\n dynamicPathGeneratedMap.set(generated.id, generatedSet);\n }\n }\n },\n\n resolveRequestPath(requestPath) {\n const [requestPathWithoutQuery] = splitHtmlLink(requestPath);\n\n for (const [id, generatedSet] of dynamicPathGeneratedMap) {\n for (const generated of generatedSet) {\n const pageOutputPath = calculatePagePath(generated, pagesDirectory);\n\n // exact match\n if (requestPathWithoutQuery === pageOutputPath) {\n return id;\n }\n\n // without index.html\n if (basename(pageOutputPath) === \"index.html\" && requestPathWithoutQuery === dirname(pageOutputPath)) {\n return id;\n }\n }\n }\n\n for (const pageFile of pagesFiles) {\n const pageOutputPath = calculatePagePath(pageFile, pagesDirectory);\n\n // exact match\n if (requestPathWithoutQuery === pageOutputPath) {\n return pageFile;\n }\n\n // without index.html\n if (basename(pageOutputPath) === \"index.html\" && requestPathWithoutQuery === dirname(pageOutputPath)) {\n return pageFile;\n }\n }\n },\n\n onFileEvent(type, filePath) {\n if (type === \"add\" && isPageDirectorySubpath(filePath, pagesDirectory)) {\n pagesFiles.add(filePath);\n return;\n }\n\n if (type === \"unlink\") {\n pagesFiles.delete(filePath);\n }\n },\n\n // Since we are moving all pages outside the \"pages\" directory, we need to rebase links points to the \"pages\" directory\n rebaseSource(source, filePath, newAbsolutePath) {\n if (!isValidRelativePath(source)) return;\n\n const relativeNewPath = relative(this.root, newAbsolutePath);\n\n const isRebasingFromPages = isPageDirectorySubpath(filePath, pagesDirectory);\n const isRebasingToPages = isPageDirectorySubpath(relativeNewPath, pagesDirectory);\n\n // Same directory rebase. Skip\n if (isRebasingFromPages && isRebasingToPages) {\n return;\n }\n\n // Only proceed when rebasing involves the pages directory. Skip\n if (!isRebasingFromPages && !isRebasingToPages) {\n return;\n }\n\n const [link, suffix] = splitHtmlLink(source);\n\n // Already a self-reference. Return the original source\n if ([\"index.html\", \"index.md\"].includes(basename(filePath)) && [\"./\", \".\", \"\"].includes(link)) {\n return source;\n }\n\n const sourceAbs = join(this.root, dirname(filePath), link);\n\n // Only sources points to directories, HTML, Markdown\n const isSourceHTML = [\".html\", \".md\", \"\"].includes(extname(sourceAbs));\n if (!isSourceHTML) {\n return;\n }\n\n // Only sources points to file inside the \"pages\" directory\n const isSourcePage = isPageDirectorySubpath(relative(this.root, sourceAbs), pagesDirectory);\n if (!isSourcePage) {\n return;\n }\n\n // Going to be a self-reference after rebasing\n const newFileName = basename(newAbsolutePath);\n const absFilePath = join(this.root, filePath);\n if ([\"index.html\", \"index.md\"].includes(newFileName) && isSelfReference(sourceAbs, absFilePath)) {\n return \"./\" + suffix.replace(/^\\//, \"\");\n }\n\n const sourceRootRelative = join(dirname(filePath), link);\n let rebased = relative(dirname(join(pagesDirectory, relativeNewPath)), sourceRootRelative);\n\n // Preserve \"/\" in this edge case\n if (link === \"./\" && !rebased.endsWith(\"/\")) {\n rebased += \"/\";\n }\n\n // Avoid double-slash\n if (rebased.endsWith(\"/\") && suffix.startsWith(\"/\")) {\n rebased = rebased.slice(0, -1);\n }\n\n rebased += suffix;\n\n return rebased;\n },\n\n // Sources from outside the \"pages\" directory pointing to the \"pages\" directory should be rebased as well\n transformSource(source, filePath) {\n if (!isValidRelativePath(source)) return;\n\n // Pages' own sources are handled by rebaseSource during transform\n const isFilePage = [\".html\", \".md\", \"\"].includes(extname(filePath));\n if (isFilePage && isPageDirectorySubpath(filePath, pagesDirectory)) {\n return;\n }\n\n const [sourceLink, suffix] = splitHtmlLink(source);\n\n // Only sources pointing to directories, HTML, Markdown\n const isSourceHTML = [\".html\", \".md\", \"\"].includes(extname(sourceLink));\n if (!isSourceHTML) {\n return;\n }\n\n const sourceRootRelative = join(dirname(filePath), sourceLink);\n\n // Only fix links pointing into the pages directory\n const isPointingToPage = isPageDirectorySubpath(sourceRootRelative, pagesDirectory);\n if (!isPointingToPage) {\n return;\n }\n\n // Where the source page ends up after being moved out of pagesDirectory\n const isPagesItself = normalize(sourceRootRelative) === normalize(pagesDirectory);\n const sourceNewPath = isPagesItself\n ? outputDirectory\n : join(outputDirectory, calculatePagePath(sourceRootRelative, pagesDirectory));\n\n const rebased = relative(dirname(filePath), sourceNewPath);\n\n return rebased + suffix;\n },\n\n async transform(metadata) {\n if (isHtmlMetadata(metadata)) {\n if (!isPageDirectorySubpath(metadata.filePath, pagesDirectory)) return;\n\n const pageOutputPath = calculatePagePath(metadata.filePath, pagesDirectory);\n const absPageOutputPath = join(this.root, outputDirectory, pageOutputPath);\n\n await this.rebase(metadata, absPageOutputPath);\n\n return;\n }\n\n if (isMarkdownMetadata(metadata)) {\n if (!isPageDirectorySubpath(metadata.filePath, pagesDirectory)) return;\n\n const asHtmlString = await metadata.ast.render();\n\n // Load as HTML\n const htmlMetadata = await this.load(metadata.id, { code: asHtmlString, type: \"html\" });\n if (!isHtmlMetadata(htmlMetadata)) {\n this.log.error(`Failed to load HTML metadata for \"${metadata.filePath}\"`);\n return;\n }\n\n // Resolve -> Discover -> Load -> Transform\n const metadataList = await this.resolveAndLoad(htmlMetadata);\n this.addMetadata(metadataList);\n await this.transformAndSync(metadataList);\n\n this.emitExclude.add(metadata);\n\n return;\n }\n },\n };\n}\n\nfunction isPageDirectorySubpath(filePath: string, pagesDirectory: string): boolean {\n filePath = extname(filePath) ? dirname(filePath) : filePath;\n\n if (filePath === pagesDirectory) {\n return true;\n }\n\n return isSubpath(pagesDirectory, dirname(filePath));\n}\n","import { basename, extname } from \"../../utilities/path.ts\";\n\nconst MIME_TYPES: Record<string, string> = Object.freeze({\n // Fonts\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".ttf\": \"font/ttf\",\n \".otf\": \"font/otf\",\n \".eot\": \"application/vnd.ms-fontobject\",\n\n // Audio\n \".mp3\": \"audio/mpeg\",\n \".wav\": \"audio/wav\",\n \".ogg\": \"audio/ogg\",\n \".m4a\": \"audio/mp4\",\n\n // Video\n \".mp4\": \"video/mp4\",\n \".webm\": \"video/webm\",\n \".ogv\": \"video/ogg\",\n\n // Images\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".avif\": \"image/avif\",\n \".svg\": \"image/svg+xml\",\n\n // Files\n \".json\": \"application/json\",\n \".wasm\": \"application/wasm\",\n \".bin\": \"application/octet-stream\",\n \".data\": \"application/octet-stream\",\n \".pb\": \"application/x-protobuf\",\n \".msgpack\": \"application/x-msgpack\",\n});\n\nconst AS_TYPES: Record<string, string> = Object.freeze({\n \".js\": \"script\",\n \".mjs\": \"script\",\n \".css\": \"style\",\n \".woff\": \"font\",\n \".woff2\": \"font\",\n \".ttf\": \"font\",\n \".otf\": \"font\",\n \".eot\": \"font\",\n \".mp3\": \"audio\",\n \".wav\": \"audio\",\n \".ogg\": \"audio\",\n \".m4a\": \"audio\",\n \".mp4\": \"video\",\n \".webm\": \"video\",\n \".ogv\": \"video\",\n \".png\": \"image\",\n \".jpg\": \"image\",\n \".jpeg\": \"image\",\n \".gif\": \"image\",\n \".webp\": \"image\",\n \".avif\": \"image\",\n \".svg\": \"image\",\n\n // fetch — data files loaded via fetch()/XHR\n \".json\": \"fetch\",\n \".wasm\": \"fetch\",\n \".bin\": \"fetch\",\n \".data\": \"fetch\",\n \".pb\": \"fetch\",\n \".msgpack\": \"fetch\",\n});\n\ninterface PreloadInfo {\n rel: \"preload\" | \"modulepreload\";\n as: string;\n type?: string;\n crossorigin?: true;\n}\n\nexport function getPreloadInfo(filePath: string): PreloadInfo | undefined {\n const extension = extname(basename(filePath)).toLowerCase();\n const as = AS_TYPES[extension];\n\n if (!as) {\n return undefined;\n }\n\n const info: PreloadInfo = { rel: \"preload\", as };\n\n const mime = MIME_TYPES[extension];\n if (mime) {\n info.type = mime;\n }\n\n // Fonts must be fetched with CORS or the browser ignores the hint\n if (as === \"font\") {\n info.crossorigin = true;\n }\n\n if (extension === \".wasm\") {\n info.rel = \"modulepreload\";\n }\n\n return info;\n}\n","import { DependenciesFinder as DependenciesFinder } from \"../../helpers/find-dependencies.ts\";\nimport { isScriptType } from \"../../helpers/is-script-type.ts\";\nimport { isDynamic, isJavaScript } from \"../../helpers/lsp-checks.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { splitHtmlLink } from \"../../utilities/html-links.ts\";\nimport { isHtmlMetadata, isScriptMetadata, isStyleMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join, isPathMatch, parsePatterns, relative } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { getPreloadInfo } from \"./get-file-type.ts\";\n\nimport type { ElementInfo, HTMLElement, HtmlMetadata, MetadataBase, Plugin } from \"@staticbolt/core\";\n\nexport interface HtmlPreloadOptions {\n /**\n * Attribute name that enables preloading.\n *\n * @default \"preload\"\n */\n preloadAttribute?: string;\n\n /**\n * Attribute name for including files.\n *\n * @default \"preload-include\"\n */\n includeAttribute?: string;\n\n /**\n * Attribute name for excluding files.\n *\n * @default \"preload-exclude\"\n */\n excludeAttribute?: string;\n}\n\n/**\n * Adds \"<link rel=preload>\" tags to the \"<head>\" for the dependencies of the scripts and stylesheets marked with \"preload\"\n * (attribute names configurable via HtmlPreloadOptions), so the browser starts fetching them before parsing gets that far.\n *\n * Attributes:\n *\n * - \"preload\": marks the tag. Its value narrows what to emit to a space-separated list of \"script\", \"style\", \"fetch\", \"font\",\n * \"audio\", \"video\" and \"image\"; an empty value means all of them.\n * - \"preload-include\" and \"preload-exclude\": semicolon-separated glob patterns, matched against paths relative to the project root.\n *\n * Notes:\n *\n * - Production only; in development the three attributes are just stripped.\n * - Handles \"<script>\", \"<style>\" and \"<link rel=stylesheet>\" tags. The attribute on any other tag emits nothing.\n * - The dependency walk covers the whole graph behind the tag (imports, \"@import\", \"url()\") plus the file it points at, and files\n * whose extension has no known \"as\" type are skipped.\n * - The links are appended at the end of \"<head>\", so they come after whatever the page already has there.\n */\nexport function htmlPreloadPlugin(options: HtmlPreloadOptions = {}): Plugin {\n const preloadAttribute = options.preloadAttribute ?? \"preload\";\n const includeAttribute = options.includeAttribute ?? \"preload-include\";\n const excludeAttribute = options.excludeAttribute ?? \"preload-exclude\";\n\n const asTypes = [\"script\", \"style\", \"fetch\", \"font\", \"audio\", \"video\", \"image\"];\n const query = `[${preloadAttribute}]`;\n\n const printFmtError = PrintFormattedError.create({ function: htmlPreloadPlugin });\n\n return {\n name: \"html-preload\",\n\n // Clean up during development\n transform(metadata) {\n if (this.production || !isHtmlMetadata(metadata)) return;\n\n const elements = metadata.ast.querySelectorAll(query);\n for (const node of elements) {\n node.removeAttribute(preloadAttribute);\n node.removeAttribute(includeAttribute);\n node.removeAttribute(excludeAttribute);\n }\n },\n\n async postTransform() {\n if (!this.production) return;\n\n const dependenciesFinder = new DependenciesFinder(this, this.root);\n\n for (const htmlMetadata of this.metadataList) {\n if (!isHtmlMetadata(htmlMetadata)) continue;\n\n const head = htmlMetadata.ast.querySelector(\"head\");\n if (!head) continue;\n\n const elements = htmlMetadata.ast.querySelectorAll(query);\n\n for (const node of elements) {\n const preloadValue = node.getAttribute(preloadAttribute);\n const preloadTypes = preloadValue ? preloadValue.split(\" \").filter(Boolean) : asTypes;\n\n const includePatterns = parsePatterns(node.getAttribute(includeAttribute));\n const include = includePatterns?.length ? includePatterns : [\"**/*\"];\n const ignore = parsePatterns(node.getAttribute(excludeAttribute));\n\n node.removeAttribute(preloadAttribute);\n node.removeAttribute(includeAttribute);\n node.removeAttribute(excludeAttribute);\n\n // Case script or style tag:\n const isScript = node.tagName === \"SCRIPT\";\n const isStyle = node.tagName === \"STYLE\";\n const isStyleSheetLink = node.tagName === \"LINK\" && node.getAttribute(\"rel\") === \"stylesheet\";\n\n const scriptType = node.getAttribute(\"type\");\n if (isScript && !isScriptType(scriptType)) {\n continue;\n }\n\n const preloadPaths = new Set<string>();\n\n if (isScript || isStyle || isStyleSheetLink) {\n const metadata = getMetadata(this.metadataList, htmlMetadata, node);\n if (!isStyleMetadata(metadata) && !isScriptMetadata(metadata)) {\n printFmtError(`Failed to get metadata for ${node.tagName} tag`, { node, filePath: htmlMetadata.id });\n continue;\n }\n\n const dependencies = await dependenciesFinder.findDeps(metadata);\n\n const source = node.getAttribute(\"src\") ?? node.getAttribute(\"href\");\n\n if ((isScript && source) || (isStyleSheetLink && source)) {\n const [link] = splitHtmlLink(source);\n dependencies.add(join(this.root, dirname(htmlMetadata.filePath), link));\n }\n\n for (const dependency of dependencies) {\n const relativeDependencyPath = relative(this.root, dependency);\n\n if (!isPathMatch(relativeDependencyPath, { include, ignore, root: this.root })) {\n continue;\n }\n\n preloadPaths.add(relative(dirname(htmlMetadata.filePath), dependency));\n }\n }\n\n const linkTags: string[] = [];\n\n for (const path of preloadPaths) {\n const typeInfo = getPreloadInfo(path);\n if (!typeInfo) {\n continue;\n }\n\n if (!preloadTypes.includes(typeInfo.as)) {\n continue;\n }\n\n linkTags.push(createLinkTag(typeInfo, path));\n }\n\n head.insertAdjacentHTML(\"beforeend\", linkTags.join(\"\\n\"));\n\n // TODO: Preload for other kinds of tags\n }\n }\n },\n\n lspHtmlData() {\n const attributes = [\n {\n name: preloadAttribute,\n description:\n \"Enable preloading.\" +\n '\\nAutomatically generates `<link rel=\"preload\">` tags for the dependencies of your scripts and stylesheets.' +\n \"\\nThis tells the browser to start fetching those files early, before they are discovered through normal parsing.\" +\n \"\\n\\nYou can narrow down the files to preload by specifying a space-separated list of dependency types,\" +\n ` additionally you can use the \\`${includeAttribute}\\` and \\`${excludeAttribute}\\` attributes.`,\n values: asTypes.map(type => ({ name: type })),\n },\n {\n name: includeAttribute,\n description: `Glob patterns list to include when using the \\`${preloadAttribute}\\` attribute. (semicolon-separated)`,\n },\n {\n name: excludeAttribute,\n description: `Glob patterns list to exclude when using the \\`${preloadAttribute}\\` attribute. (semicolon-separated)`,\n },\n ];\n\n const description =\n `Adds the \\`${preloadAttribute}\\`, \\`${includeAttribute}\\` and \\`${excludeAttribute}\\` attributes,` +\n ` which emit \\`<link rel=\"preload\">\\` tags in the \\`<head>\\` for this tag's dependencies at build time.`;\n\n return {\n version: 1.1,\n tags: [\n { name: \"link\", description, attributes },\n { name: \"script\", description, attributes },\n ],\n };\n },\n\n lspValidate(document, report) {\n for (const element of document.elements) {\n const preload = element.attribute(preloadAttribute);\n if (!preload) continue;\n\n if (!isPreloadable(element)) {\n report.warn(preload.nameRange, `\"${preloadAttribute}\" only works on a script, a style or a stylesheet link`);\n continue;\n }\n\n if (!preload.value) continue;\n if (isDynamic(preload.value)) continue;\n\n const unknownTypes = preload.value.split(\" \").filter(type => type && !asTypes.includes(type));\n if (unknownTypes.length === 0) continue;\n\n report.error(preload, `Unknown preload types ${unknownTypes.join(\", \")}, use ${asTypes.join(\", \")}`);\n }\n },\n };\n}\n\n/** Whether the preload attribute means something on an element: a JavaScript script, a style or a stylesheet link. */\nfunction isPreloadable(element: ElementInfo): boolean {\n if (element.name === \"script\") {\n return isJavaScript(element);\n }\n\n if (element.name === \"style\") {\n return true;\n }\n\n return element.name === \"link\" && element.attribute(\"rel\")?.value === \"stylesheet\";\n}\n\nfunction getMetadata(metadataList: readonly MetadataBase[], htmlMetadata: HtmlMetadata, node: HTMLElement) {\n const isScriptTag = node.tagName === \"SCRIPT\";\n const isStyleTag = node.tagName === \"STYLE\";\n const isStyleSheetLinkTag = node.tagName === \"LINK\" && node.getAttribute(\"rel\") === \"stylesheet\";\n\n // With source\n const source = isScriptTag ? node.getAttribute(\"src\") : isStyleSheetLinkTag ? node.getAttribute(\"href\") : undefined;\n if (source) {\n const [link] = splitHtmlLink(source);\n const filePath = join(dirname(htmlMetadata.filePath), link);\n return metadataList.find(metadata => metadata.filePath === filePath);\n }\n\n // Embedded\n if (isScriptTag || isStyleTag) {\n const metadataID = node.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!metadataID) return;\n\n return htmlMetadata[isScriptTag ? \"scriptsMetadataList\" : \"stylesMetadataList\"].get(metadataID);\n }\n}\n\nfunction createLinkTag(info: NonNullable<ReturnType<typeof getPreloadInfo>>, href: string) {\n return (\n \"<link\" +\n (info.type ? ` type=\"${info.type}\"` : \"\") +\n ` as=\"${info.as}\"` +\n (info.crossorigin ? ` crossorigin` : \"\") +\n ` href=\"${href}\"` +\n ` rel=\"${info.rel}\"` +\n \" />\"\n );\n}\n","import type { Document, HTMLElement } from \"@staticbolt/core\";\n\ninterface ParseHtmlLinksResult {\n get source(): string;\n set source(newValue: string);\n node: HTMLElement;\n}\n\nconst attributeTagsMap = {\n src: new Set([\"img\", \"video\", \"audio\", \"source\", \"track\", \"script\", \"iframe\", \"embed\", \"input\"]),\n srcset: new Set([\"img\", \"source\"]),\n href: new Set([\"a\", \"area\", \"link\", \"base\"]),\n data: new Set([\"object\"]),\n action: new Set([\"form\"]),\n formaction: new Set([\"button\", \"input\"]),\n poster: new Set([\"video\"]),\n cite: new Set([\"blockquote\", \"del\", \"ins\", \"q\"]),\n ping: new Set([\"a\", \"area\"]),\n};\n\n// tag → attributes[] reverse lookup, e.g. \"a\" → [\"href\", \"ping\"]\nconst tagAttributeMap = new Map<string, string[]>();\n\nfor (const [attribute, tags] of Object.entries(attributeTagsMap)) {\n for (const tag of tags) {\n let attributes = tagAttributeMap.get(tag);\n if (!attributes) {\n attributes = [];\n tagAttributeMap.set(tag, attributes);\n }\n\n attributes.push(attribute);\n }\n}\n\nfunction parseSrcset(value: string) {\n const parts = value.split(\",\");\n\n const result: { url: string; descriptor?: string }[] = [];\n\n for (let part of parts) {\n part = part.trim();\n if (part) {\n const [url, descriptor] = part.split(/\\s+/, 2);\n result.push({ url, descriptor });\n }\n }\n\n return result;\n}\n\nfunction stringifySrcset(entries: { url: string; descriptor?: string }[]) {\n let srcset = \"\";\n\n for (const entry of entries) {\n srcset += entry.descriptor ? `, ${entry.url} ${entry.descriptor}` : `, ${entry.url}`;\n }\n\n return srcset;\n}\n\n/** Match placeholders [[ ]] or {{ }} */\nconst placeholderRe = /(?:\\[\\[([^\\]]*[^\\]]*?)\\]\\]|\\{\\{([^}]*[^}]*?)\\}\\})/;\n\n/**\n * Collects elements in document order, cheaper than a `querySelectorAll` with a many-branch selector. Tagless container elements\n * (parsed fragment roots) are descended into but not collected.\n */\nfunction collectElements(node: Document | HTMLElement, out: HTMLElement[]) {\n for (const child of node.childNodes) {\n if (child.nodeType !== 1) continue;\n\n if (child.tagName) {\n out.push(child);\n }\n\n collectElements(child, out);\n }\n}\n\nexport function parseHtmlSources(ast: Document): ParseHtmlLinksResult[] {\n const links: ParseHtmlLinksResult[] = [];\n\n const elements: HTMLElement[] = [];\n collectElements(ast, elements);\n\n for (const node of elements) {\n const attributes = tagAttributeMap.get(node.tagName.toLowerCase());\n if (!attributes) continue;\n\n for (const attribute of attributes) {\n const value = node.getAttribute(attribute);\n if (!value) continue;\n\n if (attribute === \"srcset\") {\n const entries = parseSrcset(value);\n\n for (const [index, entry] of entries.entries()) {\n if (placeholderRe.test(entry.url)) {\n continue;\n }\n\n let decodedEntryUrl: string | undefined;\n\n links.push({\n node,\n get source() {\n return (decodedEntryUrl ??= decodeURIComponent(entry.url));\n },\n set source(newValue: string) {\n const current = parseSrcset(node.getAttribute(\"srcset\") || \"\");\n current[index].url = newValue;\n node.setAttribute(\"srcset\", stringifySrcset(current));\n },\n });\n }\n\n continue;\n }\n\n if (placeholderRe.test(value)) {\n continue;\n }\n\n let decodedValue: string | undefined;\n\n links.push({\n node,\n get source() {\n return (decodedValue ??= decodeURIComponent(value));\n },\n set source(newValue: string) {\n node.setAttribute(attribute, newValue);\n },\n });\n }\n }\n\n return links;\n}\n","import { parse } from \"@staticbolt/node-html-parser\";\n\nimport { valueOrError } from \"../utilities/value-or-error.ts\";\n\nimport type { ParseOptions } from \"@staticbolt/node-html-parser\";\n\nfunction parseHtmlUnsafe(html: string, options: Partial<ParseOptions> = {}) {\n return parse(html, { comment: true, ...options });\n}\n\n/** Parse HTML string and return the root node */\nconst parseHtml = valueOrError(parseHtmlUnsafe);\n\nexport { parseHtml };\n","import { isScriptType, TYPESCRIPT_TYPE } from \"../../../helpers/is-script-type.ts\";\nimport { parseHtml } from \"../../../parsers/html-parser.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../../types/common.ts\";\nimport { METADATA_TYPES } from \"../../../types/metadata.ts\";\nimport { isScriptMetadata, isStyleMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { hashContent } from \"../../../utilities/utilities.ts\";\n\nimport type { ValueOrError } from \"../../../utilities/value-or-error.ts\";\nimport type { App, HtmlMetadata, ScriptMetadata, StyleMetadata } from \"@staticbolt/core\";\n\ntype HtmlLoaderResult = ValueOrError<HtmlMetadata>;\n\nexport async function htmlLoader(this: App, relativePath: string, code: string): Promise<HtmlLoaderResult> {\n const [rootElement, parseError] = parseHtml(code);\n if (parseError !== null) {\n parseError.message = `Failed to parse HTML file \"${relativePath}\"\\n` + parseError.message;\n return [null, parseError];\n }\n\n // Script loader\n const scriptsMetadataList = new Map<string, ScriptMetadata>();\n\n const scripts = rootElement.querySelectorAll(\"script\");\n for (const script of scripts) {\n // For the editor; every script is parsed as TypeScript anyway, and a browser would skip the type\n if (script.getAttribute(\"type\")?.toLowerCase() === TYPESCRIPT_TYPE) {\n script.removeAttribute(\"type\");\n\n // The type slot is taken, so a module says so with its own attribute\n if (script.hasAttribute(\"module\")) {\n script.removeAttribute(\"module\");\n script.setAttribute(\"type\", \"module\");\n }\n }\n\n const hasSource = script.hasAttribute(\"src\");\n if (hasSource) continue;\n\n const scriptType = script.getAttribute(\"type\");\n if (!isScriptType(scriptType)) {\n continue;\n }\n\n const scriptCode = script.rawText;\n if (!scriptCode) {\n return [null, new Error(\"No code found in <script> tag\")];\n }\n\n const scriptMetadata = await this.load(relativePath, { code: scriptCode, type: \"js\" });\n if (!isScriptMetadata(scriptMetadata)) {\n return [null, new Error(\"Script loader returned non-script metadata\")];\n }\n\n const isTypeModule = script.getAttribute(\"type\") === \"module\";\n scriptMetadata.module = isTypeModule;\n\n const astID = hashContent((isTypeModule ? \"module:\" : \"script:\") + scriptCode);\n script.setAttribute(CUSTOM_ATTRIBUTES.MetadataID, astID);\n scriptsMetadataList.set(astID, scriptMetadata);\n }\n\n // Style loader\n const stylesMetadataList = new Map<string, StyleMetadata>();\n\n const styles = rootElement.querySelectorAll(\"style\");\n for (const style of styles) {\n const styleCode = style.rawText;\n if (!styleCode) continue;\n\n const styleMetadata = await this.load(relativePath, { code: styleCode, type: \"css\" });\n if (!isStyleMetadata(styleMetadata)) {\n return [null, new Error(\"Style loader returned non-style metadata\")];\n }\n\n const astID = hashContent(styleCode);\n style.setAttribute(CUSTOM_ATTRIBUTES.MetadataID, astID);\n stylesMetadataList.set(astID, styleMetadata);\n }\n\n const htmlMetadata: HtmlMetadata = {\n type: METADATA_TYPES.HTML,\n ast: rootElement,\n filePath: relativePath,\n id: relativePath,\n scriptsMetadataList,\n stylesMetadataList,\n directDependencies: new Set(),\n };\n\n return [htmlMetadata, null];\n}\n","import { TYPESCRIPT_TYPE } from \"../../../helpers/is-script-type.ts\";\nimport { isTypeScriptScript } from \"../../../helpers/lsp-checks.ts\";\n\nimport type { EmbeddedLanguage, HTMLDataV1 } from \"@staticbolt/core\";\n\n/**\n * The bodies of the inline scripts marked `type=\"${TYPESCRIPT_TYPE}\"`, served as TypeScript through the project's own TypeScript,\n * so they see the browser the way the project's tsconfig describes it. A plugin that runs a script elsewhere claims it over\n * this.\n */\nexport function embeddedLanguages(): EmbeddedLanguage[] {\n return [\n {\n name: \"scripts\",\n filter: () => true,\n findRegions: document =>\n document.select(\"script\").flatMap(script => {\n if (!isTypeScriptScript(script) || script.has(\"src\") || !script.contentRange) return [];\n return { ...script.contentRange, isModule: script.has(\"module\") };\n }),\n isColouredByEditor: true,\n },\n ];\n}\n\n/** The attributes the plugin adds to `<script>`, for completion and hover. */\nexport function htmlData(): HTMLDataV1 {\n return {\n version: 1.1,\n tags: [\n {\n name: \"script\",\n attributes: [\n {\n name: \"type\",\n description:\n `\\`${TYPESCRIPT_TYPE}\\` marks the script as TypeScript for the editor: Prettier formats it as such,` +\n \" the staticbolt language server serves it through the project's TypeScript, and the build drops the type.\",\n values: [{ name: TYPESCRIPT_TYPE }],\n },\n {\n name: \"module\",\n description: `With \\`type=\"${TYPESCRIPT_TYPE}\"\\`, whose type slot is taken: the build prints the script as \\`type=\"module\"\\`.`,\n valueSet: \"v\",\n },\n ],\n },\n ],\n };\n}\n","import { parseHtmlSources } from \"../../../ast-utilities/html-utils/parse-html-sources.ts\";\nimport { isScriptType } from \"../../../helpers/is-script-type.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../../types/common.ts\";\nimport { splitHtmlLink } from \"../../../utilities/html-links.ts\";\nimport { isHtmlMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { extname, join, relative } from \"../../../utilities/path.ts\";\nimport { printFmtError } from \"../../../utilities/print-formatted-error.ts\";\nimport { cloneObject } from \"../../../utilities/utilities.ts\";\nimport { formatHtml, formatHtmlPass, minifyHtml, minifyHtmlPass } from \"./deferred.ts\";\nimport { htmlLoader } from \"./html-loader.ts\";\nimport { embeddedLanguages, htmlData } from \"./lsp.ts\";\n\nimport type { FormatHtmlPayload } from \"./deferred.ts\";\nimport type { HTMLElement, MetadataSource, Plugin, ScriptMetadata, StyleMetadata } from \"@staticbolt/core\";\n\nexport interface CoreHtmlPluginOptions {\n /**\n * The attribute name to use for minifying script and style tags.\n *\n * @default \"minify\"\n */\n minifyAttribute?: string;\n}\n\n/**\n * The HTML half of the core pipeline: parses a page into a document, splits its \"<script>\" and \"<style>\" tags into metadata of\n * their own, and prints the whole thing back out.\n *\n * Notes:\n *\n * - Each inline script or style is tied to its tag by an internal id attribute, which is stripped from the printed output.\n * - Sources come from the page's links plus the sources of every extracted script and style, so an import inside an inline script\n * counts as a dependency of the page.\n * - A \"minify\" attribute on a single tag minifies just that tag regardless of the build settings, and when the rest of the page is\n * formatted such a tag is preceded by a \"prettier-ignore\" comment so it stays that way.\n * - Rebasing a page carries its inline scripts and styles along with it.\n */\nexport function coreHtmlPlugin(options: CoreHtmlPluginOptions = {}): Plugin {\n const minifyAttribute = options.minifyAttribute ?? \"minify\";\n const ignoreFormatComment = \"\\n<!-- prettier-ignore -->\\n\";\n\n return {\n name: \"core-html-metadata\",\n\n async load(content, relativePath, { type }) {\n const [link] = splitHtmlLink(relativePath);\n\n type ??= extname(link).slice(1);\n\n if (type !== \"html\") {\n return;\n }\n\n const [fileMetadata, metadataError] = await htmlLoader.call(this, link, content);\n if (metadataError) {\n printFmtError(metadataError, { function: coreHtmlPlugin });\n return;\n }\n\n return fileMetadata;\n },\n\n clone(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n const cloned = cloneObject(metadata);\n\n cloned.ast = metadata.ast.clone();\n\n cloned.scriptsMetadataList = new Map<string, ScriptMetadata>();\n for (const [metadataID, scriptMetadata] of metadata.scriptsMetadataList) {\n cloned.scriptsMetadataList.set(metadataID, this.clone(scriptMetadata));\n }\n\n cloned.stylesMetadataList = new Map<string, StyleMetadata>();\n for (const [metadataID, cssMetadata] of metadata.stylesMetadataList) {\n cloned.stylesMetadataList.set(metadataID, this.clone(cssMetadata));\n }\n\n return cloned;\n },\n\n async stringify(metadata, { format, minify, defer }) {\n if (!isHtmlMetadata(metadata)) return;\n\n const nodeIdMap = new Map<HTMLElement, string>();\n\n const scriptsAndStyles = metadata.ast.querySelectorAll(\"script,style\");\n\n for (const node of scriptsAndStyles) {\n const hasMinifyAttribute = node.hasAttribute(minifyAttribute);\n const shouldMinify = minify || hasMinifyAttribute;\n const isScript = node.tagName === \"SCRIPT\";\n\n node.removeAttribute(minifyAttribute);\n\n const scriptType = node.getAttribute(\"type\");\n if (isScript && !isScriptType(scriptType)) {\n continue;\n }\n\n const metadataID = node.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!metadataID) continue;\n\n // Remove metadata id temporarily\n nodeIdMap.set(node, metadataID);\n node.removeAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n\n const tagMetadata = metadata[isScript ? \"scriptsMetadataList\" : \"stylesMetadataList\"].get(metadataID);\n if (!tagMetadata) continue;\n\n const code = await this.stringify(tagMetadata, { format: format && !shouldMinify, minify: shouldMinify });\n if (!code) continue;\n\n node.textContent = code;\n\n if (format && hasMinifyAttribute) {\n node.replaceWith(ignoreFormatComment + node.outerHTML);\n }\n }\n\n const code = metadata.ast.toString();\n\n // Restore metadata ids\n for (const [node, metadataID] of nodeIdMap) {\n node.setAttribute(CUSTOM_ATTRIBUTES.MetadataID, metadataID);\n }\n\n if (format) {\n const payload: FormatHtmlPayload = { filePath: join(this.root, metadata.filePath) };\n\n if (defer) {\n defer(formatHtmlPass(payload));\n return code;\n }\n\n try {\n return await formatHtml(code, payload);\n } catch {\n this.log.error(\"Failed to format html\", metadata.filePath);\n return;\n }\n }\n\n if (minify) {\n if (defer) {\n defer(minifyHtmlPass());\n return code;\n }\n\n try {\n return await minifyHtml(code);\n } catch {\n this.log.error(\"Failed to minify html\", metadata.filePath);\n return;\n }\n }\n\n return code;\n },\n\n async sourcesProvider(metadata) {\n if (!isHtmlMetadata(metadata)) return;\n\n // HTML Links\n const htmlSources: MetadataSource[] = parseHtmlSources(metadata.ast);\n\n const scriptsAndStyles = metadata.ast.querySelectorAll(\"script,style\");\n const scripts = scriptsAndStyles.filter(node => node.tagName === \"SCRIPT\");\n const styles = scriptsAndStyles.filter(node => node.tagName === \"STYLE\");\n\n // Embedded scripts\n for (const script of scripts) {\n const id = script.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!id) continue;\n\n const scriptMetadata = metadata.scriptsMetadataList.get(id);\n if (!scriptMetadata) continue;\n\n const requestedSources = await this.requestSources(scriptMetadata);\n htmlSources.push(...requestedSources);\n }\n\n // Embedded styles\n for (const style of styles) {\n const id = style.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!id) continue;\n\n const styleMetadata = metadata.stylesMetadataList.get(id);\n if (!styleMetadata) continue;\n\n const requestedSources = await this.requestSources(styleMetadata);\n htmlSources.push(...requestedSources);\n }\n\n return htmlSources;\n },\n\n onMetadataRebase(metadata, _, newAbsolutePath) {\n if (!isHtmlMetadata(metadata)) return;\n\n metadata.filePath = relative(this.root, newAbsolutePath);\n\n for (const [, scriptMetadata] of metadata.scriptsMetadataList) {\n scriptMetadata.filePath = metadata.filePath;\n }\n\n for (const [, cssMetadata] of metadata.stylesMetadataList) {\n cssMetadata.filePath = metadata.filePath;\n }\n },\n\n lspEmbeddedLanguages() {\n return embeddedLanguages();\n },\n\n lspHtmlData() {\n return htmlData();\n },\n };\n}\n","import rehypeExternalLinks from \"rehype-external-links\";\nimport rehypeSlug from \"rehype-slug\";\nimport rehypeStringify from \"rehype-stringify\";\nimport { remark } from \"remark\";\nimport remarkFrontmatter from \"remark-frontmatter\";\nimport remarkGfm from \"remark-gfm\";\nimport remarkRehype from \"remark-rehype\";\nimport remarkSmartypants from \"remark-smartypants\";\nimport { unified } from \"unified\";\nimport { visit } from \"unist-util-visit\";\nimport { parse as parseYaml } from \"yaml\";\n\nimport { METADATA_TYPES, type MarkdownMetadata } from \"../../../types/metadata.ts\";\nimport { splitHtmlLink } from \"../../../utilities/html-links.ts\";\nimport { isMarkdownMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { extname, join } from \"../../../utilities/path.ts\";\nimport { printFmtError } from \"../../../utilities/print-formatted-error.ts\";\nimport { cloneObject } from \"../../../utilities/utilities.ts\";\nimport { formatMarkdown, formatMarkdownPass } from \"./deferred.ts\";\n\nimport type { FormatMarkdownPayload } from \"./deferred.ts\";\nimport type { ValueOrError } from \"../../../utilities/value-or-error.ts\";\nimport type { MarkdownAst, MetadataSource, Plugin } from \"@staticbolt/core\";\nimport type { Pluggable } from \"unified\";\n\nexport interface CoreMarkdownPluginOptions {\n /**\n * Remark plugins.\n *\n * **Default**:\n *\n * 1. `remark-frontmatter`\n * 2. `remark-gfm`\n * 3. `remark-smartypants`\n */\n remarkPlugins?: Pluggable[];\n\n /**\n * Rehype plugins.\n *\n * **Default**:\n *\n * 1. `remark-rehype`\n * 2. `rehype-slug`\n * 3. `rehype-autolink-headings`\n * 4. `rehype-external-links`\n * 5. `rehype-stringify`\n */\n rehypePlugins?: Pluggable[];\n\n /**\n * Whether to allow HTML in markdown.\n *\n * @default false\n */\n allowDangerousHtml?: boolean;\n}\n\n/**\n * The markdown half of the core pipeline: parses \".md\" files with remark, exposes their YAML front matter, and renders them to\n * HTML on demand through \"ast.render()\".\n *\n * The remark chain is front matter, GFM and smartypants, then \"remarkPlugins\"; rendering runs remark-rehype, heading slugs and\n * external links (opened in a new tab, with \"noopener noreferrer\"), then \"rehypePlugins\".\n *\n * Notes:\n *\n * - Raw HTML inside the markdown is dropped unless \"allowDangerousHtml\" is on.\n * - Front matter is only read from the very first node, and only when it is a YAML block.\n * - Links and images are reported as sources, so they get resolved and rebased; anything inside raw HTML is not.\n * - Printing this metadata gives markdown back, not HTML.\n */\nexport function coreMarkdownPlugin(options: CoreMarkdownPluginOptions = {}): Plugin {\n const shouldAllowDangerousHtml = options.allowDangerousHtml ?? false;\n\n const processor = remark()\n .use(remarkFrontmatter, [\"yaml\"])\n .use(remarkGfm)\n .use(remarkSmartypants)\n .use(options.remarkPlugins ?? []);\n\n // HTML renderer (mdast → html), shared across all ast instances\n const htmlProcessor = unified()\n .use(remarkRehype, { allowDangerousHtml: shouldAllowDangerousHtml })\n .use(rehypeSlug)\n .use(rehypeExternalLinks, { target: \"_blank\", rel: [\"noopener\", \"noreferrer\"] })\n .use(options.rehypePlugins ?? [])\n .use(rehypeStringify, { allowDangerousHtml: shouldAllowDangerousHtml });\n\n async function parseMarkdown(code: string): Promise<ValueOrError<MarkdownAst>> {\n try {\n const root = processor.parse(code);\n await processor.run(root);\n\n // Extract frontmatter from the first node if it's a yaml block\n const frontmatter: Record<string, string> = {};\n // eslint-disable-next-line unicorn/better-dom-traversing\n const firstNode = root.children[0];\n if (firstNode?.type === \"yaml\") {\n const parsed = (parseYaml(firstNode.value) as Record<string, string>) ?? {};\n Object.assign(frontmatter, parsed);\n }\n\n const ast: MarkdownAst = {\n root,\n frontmatter,\n render: async () => {\n const hast = await htmlProcessor.run(root);\n return htmlProcessor.stringify(hast);\n },\n };\n\n return [ast, null];\n } catch (error) {\n return [null, error instanceof Error ? error : new Error(String(error))];\n }\n }\n\n return {\n name: \"core-markdown-metadata\",\n\n async load(content, relativePath, { type }) {\n const [link] = splitHtmlLink(relativePath);\n\n type ??= extname(link).slice(1);\n\n if (type !== \"md\") {\n return;\n }\n\n const [markdownAst, parseError] = await parseMarkdown(content);\n if (parseError) {\n printFmtError(parseError, relativePath);\n return;\n }\n\n const markdownMetadata: MarkdownMetadata = {\n type: METADATA_TYPES.Markdown,\n ast: markdownAst,\n filePath: link,\n id: link,\n directDependencies: new Set(),\n };\n\n return markdownMetadata;\n },\n\n clone(metadata) {\n if (!isMarkdownMetadata(metadata)) return;\n\n const cloned = cloneObject(metadata);\n const clonedRoot = structuredClone(metadata.ast.root);\n\n cloned.ast = {\n root: clonedRoot,\n frontmatter: { ...metadata.ast.frontmatter },\n render: async () => {\n const hast = await htmlProcessor.run(clonedRoot);\n return htmlProcessor.stringify(hast);\n },\n };\n\n return cloned;\n },\n\n async stringify(metadata, { format, defer }) {\n if (!isMarkdownMetadata(metadata)) return;\n\n const code = processor.stringify(metadata.ast.root);\n\n if (format) {\n const payload: FormatMarkdownPayload = { filePath: join(this.root, metadata.filePath) };\n\n if (defer) {\n defer(formatMarkdownPass(payload));\n return code;\n }\n\n try {\n return await formatMarkdown(code, payload);\n } catch {\n this.log.error(\"Failed to format markdown\", metadata.filePath);\n return;\n }\n }\n\n return code;\n },\n\n sourcesProvider(metadata) {\n if (!isMarkdownMetadata(metadata)) return;\n\n const sources: MetadataSource[] = [];\n\n visit(metadata.ast.root, node => {\n if (node.type === \"link\" && node.url) {\n sources.push({\n get source() {\n return node.url;\n },\n set source(value: string) {\n node.url = value;\n },\n });\n\n return;\n }\n\n if (node.type === \"image\" && node.url) {\n sources.push({\n get source() {\n return node.url;\n },\n set source(value: string) {\n node.url = value;\n },\n });\n\n return;\n }\n\n // TODO: parse html and extract sources\n // if (node.type === \"html\" && node.value) {\n // }\n });\n\n return sources;\n },\n };\n}\n","import * as t from \"@babel/types\";\n\nimport type { BabelAst } from \"@staticbolt/core\";\n\nexport type Kind = \"value\" | \"type\" | \"typeof\" | \"dynamic\" | \"url\";\nexport type Kinds = Kind[];\n\ninterface Options {\n ast: BabelAst;\n filePath: string;\n}\n\ninterface ParseJsLinksResult {\n kind: Kind;\n node: t.Node;\n get source(): string;\n set source(newValue: string);\n}\n\nexport function parseScriptSources({ ast }: Options): ParseJsLinksResult[] {\n const result: ParseJsLinksResult[] = [];\n\n t.traverseFast(ast, node => {\n // import default from \"source\";\n // import { value } from \"source\";\n // import * as value from \"source\";\n if (t.isImportDeclaration(node)) {\n if (!t.isStringLiteral(node.source)) return;\n\n const kind = node.importKind ?? \"value\";\n if (kind === \"type\") return;\n\n const source = node.source.value;\n\n if (source.startsWith(\"node:\")) {\n return;\n }\n\n result.push({\n kind,\n node,\n get source() {\n return source;\n },\n set source(newValue) {\n if (node) {\n node.source = t.stringLiteral(newValue);\n }\n },\n });\n\n return;\n }\n\n // export * from \"source\";\n if (t.isExportAllDeclaration(node)) {\n if (!node.source.value) return;\n\n const kind = node.exportKind ?? \"value\";\n if (kind === \"type\") return;\n\n result.push({\n kind,\n node,\n get source() {\n return node.source.value;\n },\n set source(newValue) {\n node.source = t.stringLiteral(newValue);\n },\n });\n return;\n }\n\n // export default from \"source\";\n // export { value } from \"source\";\n // export * as value from \"source\";\n if (t.isExportNamedDeclaration(node)) {\n if (!t.isStringLiteral(node.source)) return;\n\n const kind = node.exportKind ?? \"value\";\n if (kind === \"type\") return;\n\n const source = node.source.value;\n\n result.push({\n kind,\n node,\n get source() {\n return source;\n },\n set source(newValue) {\n node.source = t.stringLiteral(newValue);\n },\n });\n\n return;\n }\n\n // await import(\"source\");\n if (t.isCallExpression(node)) {\n if (!t.isImport(node.callee) || !t.isStringLiteral(node.arguments[0])) return;\n\n const setSource = (newValue: string) => {\n node.arguments[0] = t.stringLiteral(newValue);\n };\n\n const source = node.arguments[0].value;\n\n result.push({\n kind: \"dynamic\",\n node,\n get source() {\n return source;\n },\n set source(newValue) {\n setSource(newValue);\n },\n });\n\n return;\n }\n\n // New URL(\"source\", ...)\n if (t.isNewExpression(node)) {\n if (!t.isIdentifier(node.callee, { name: \"URL\" })) return;\n\n const firstArgument = node.arguments[0];\n if (!t.isStringLiteral(firstArgument)) {\n return;\n }\n\n const setSource = (newValue: string) => {\n node.arguments[0] = t.stringLiteral(newValue);\n };\n\n result.push({\n kind: \"url\",\n node,\n get source() {\n return firstArgument.value;\n },\n set source(newValue) {\n setSource(newValue);\n },\n });\n\n return;\n }\n });\n\n return result;\n}\n","import * as babelParser from \"@babel/parser\";\n\nimport { valueOrError } from \"../utilities/value-or-error.ts\";\n\nexport interface ParseJsOptions {\n code: string;\n filePath: string;\n sourceType?: \"script\" | \"module\" | \"unambiguous\";\n}\n\nfunction parseJsUnsafe({ code, filePath, sourceType }: ParseJsOptions) {\n return babelParser.parse(code, {\n plugins: [\"typescript\", \"jsx\", \"decorators\", \"decoratorAutoAccessors\"],\n sourceType: sourceType ?? \"unambiguous\",\n sourceFilename: filePath,\n });\n}\n\n/** Parse JS string and return the AST */\nconst parseJs = valueOrError(parseJsUnsafe);\n\nexport { parseJs };\n","import { parseJs } from \"../../../parsers/js-parser.ts\";\nimport { METADATA_TYPES, type ScriptMetadata } from \"../../../types/metadata.ts\";\n\nimport type { ValueOrError } from \"../../../utilities/value-or-error.ts\";\nimport type { App } from \"@staticbolt/core\";\n\ntype TypescriptLoaderResults = ValueOrError<ScriptMetadata>;\n\nexport function scriptLoader(this: App, relativePath: string, code: string): TypescriptLoaderResults {\n const [ast, parseError] = parseJs({ code, filePath: relativePath });\n if (parseError !== null) {\n parseError.message = `Failed to parse JS file \"${relativePath}\"\\n` + parseError.message;\n return [null, parseError];\n }\n\n const scriptMetadata: ScriptMetadata = {\n type: METADATA_TYPES.Script,\n ast,\n filePath: relativePath,\n id: relativePath,\n directDependencies: new Set(),\n module: ast.program.sourceType === \"module\",\n };\n\n return [scriptMetadata, null];\n}\n","import _generator from \"@babel/generator\";\nimport * as t from \"@babel/types\";\n\nimport { parseScriptSources } from \"../../../ast-utilities/babel-utils/parse-script-srouces.ts\";\nimport { splitHtmlLink } from \"../../../utilities/html-links.ts\";\nimport { isScriptMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { extname, join } from \"../../../utilities/path.ts\";\nimport { printFmtError } from \"../../../utilities/print-formatted-error.ts\";\nimport { cloneObject } from \"../../../utilities/utilities.ts\";\nimport { formatScript, formatScriptPass, minifyScript, minifyScriptPass } from \"./deferred.ts\";\nimport { scriptLoader } from \"./script-loader.ts\";\n\nimport type { FormatScriptPayload, MinifyScriptPayload } from \"./deferred.ts\";\nimport type { Plugin } from \"@staticbolt/core\";\n\nconst generator = typeof _generator === \"function\" ? _generator : _generator.default;\n\n/**\n * The script half of the core pipeline: loads JavaScript and TypeScript files (\".js\", \".mjs\", \".cjs\", \".jsx\", \".ts\", \".mts\",\n * \".cts\", \".tsx\") into a Babel AST, prints them back out, and reports their imports as sources.\n *\n * Notes:\n *\n * - Loading only parses. Stripping types and JSX is transformJsPlugin's job.\n * - Printing goes through Babel; \"format\" hands the result to prettier and \"minify\" to SWC, which is told whether the file is a\n * module or a classic script.\n */\nexport function coreScriptPlugin(): Plugin {\n const jsExtensions = new Set([\".js\", \".mjs\", \".cjs\", \".jsx\", \".ts\", \".mts\", \".cts\", \".tsx\"]);\n\n return {\n name: \"core-script-metadata\",\n\n load(content, relativePath, { type }) {\n const [link] = splitHtmlLink(relativePath);\n\n type ??= extname(link).slice(1);\n\n if (!jsExtensions.has(`.${type}`)) {\n return;\n }\n\n const [fileMetadata, metadataError] = scriptLoader.call(this, link, content);\n if (metadataError) {\n printFmtError(metadataError, { function: coreScriptPlugin });\n return;\n }\n\n return fileMetadata;\n },\n\n clone(metadata) {\n if (!isScriptMetadata(metadata)) return;\n\n const cloned = cloneObject(metadata);\n cloned.ast = t.cloneNode(cloned.ast, true);\n\n return cloned;\n },\n\n async stringify(metadata, { format, minify, defer }) {\n if (!isScriptMetadata(metadata)) return;\n\n const code = generator(metadata.ast, { jsescOption: { minimal: true } }).code;\n\n if (format) {\n const payload: FormatScriptPayload = { filePath: join(this.root, metadata.filePath) };\n\n if (defer) {\n defer(formatScriptPass(payload));\n return code;\n }\n\n try {\n return await formatScript(code, payload);\n } catch {\n this.log.error(\"Failed to format script\", metadata.filePath);\n return;\n }\n }\n\n if (minify) {\n const payload: MinifyScriptPayload = { module: metadata.module };\n\n if (defer) {\n defer(minifyScriptPass(payload));\n return code;\n }\n\n try {\n return await minifyScript(code, payload);\n } catch (minifyError) {\n printFmtError(\"Failed to minify script\", minifyError as Error, { filePath: metadata.filePath });\n return;\n }\n }\n\n return code;\n },\n\n sourcesProvider(metadata) {\n if (!isScriptMetadata(metadata)) return;\n\n return parseScriptSources({ ast: metadata.ast, filePath: metadata.filePath });\n },\n };\n}\n","import { parseImportPrelude } from \"./import-prelude.ts\";\n\nimport type { PostcssAst } from \"@staticbolt/core\";\nimport type { AtRule, Declaration } from \"postcss\";\n\nconst cssUrlRe = /url\\((['\"]?)(.+?)\\1\\)/gm;\n\ninterface CssUrlHandle {\n get source(): string;\n set source(newSource: string);\n node: Declaration | AtRule;\n}\n\nexport function parseStyleSources(ast: PostcssAst): CssUrlHandle[] {\n const handles: CssUrlHandle[] = [];\n\n ast.walkDecls(declaration => {\n for (const match of declaration.value.matchAll(cssUrlRe)) {\n const source = match[2];\n if (!source) continue;\n\n handles.push({\n node: declaration,\n get source() {\n return source;\n },\n set source(newSource) {\n declaration.value = declaration.value.replace(source, () => newSource);\n },\n });\n }\n });\n\n ast.walkAtRules(/^import$/i, atRule => {\n const prelude = parseImportPrelude(atRule.params);\n if (!prelude?.url) return;\n\n const { urlStart } = prelude;\n let { url, urlEnd } = prelude;\n\n handles.push({\n node: atRule,\n get source() {\n return url;\n },\n set source(newSource) {\n atRule.params = atRule.params.slice(0, urlStart) + newSource + atRule.params.slice(urlEnd);\n urlEnd = urlStart + newSource.length;\n url = newSource;\n },\n });\n });\n\n return handles;\n}\n","import { parseStyleSources } from \"../../../ast-utilities/postcss-utils/parse-style-srouces.ts\";\nimport { isStyleMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { extname, join } from \"../../../utilities/path.ts\";\nimport { printFmtError } from \"../../../utilities/print-formatted-error.ts\";\nimport { cloneObject } from \"../../../utilities/utilities.ts\";\nimport { formatStyle, formatStylePass, minifyStyle, minifyStylePass } from \"./deferred.ts\";\nimport { styleLoader } from \"./style-loader.ts\";\n\nimport type { FormatStylePayload, MinifyStylePayload } from \"./deferred.ts\";\nimport type { Plugin } from \"@staticbolt/core\";\nimport type { Targets } from \"lightningcss\";\n\n/**\n * The style half of the core pipeline: loads \".css\" files into a PostCSS AST, prints them back out, and reports their \"@import\"\n * and \"url()\" references as sources.\n *\n * Notes:\n *\n * - \"format\" hands the result to prettier; \"minify\" runs Lightning CSS against the project's browserslist, resolved once and reused\n * for the rest of the build.\n */\nexport function coreStylePlugin(): Plugin {\n let targets: Targets | undefined;\n\n return {\n name: \"core-style-metadata\",\n\n load(content, relativePath, { type }) {\n type ??= extname(relativePath).slice(1);\n\n if (type !== \"css\") {\n return;\n }\n\n const [fileMetadata, metadataError] = styleLoader.call(this, relativePath, content);\n if (metadataError) {\n printFmtError(metadataError, { function: coreStylePlugin });\n return;\n }\n\n return fileMetadata;\n },\n\n clone(metadata) {\n if (!isStyleMetadata(metadata)) return;\n\n const cloned = cloneObject(metadata);\n cloned.ast = metadata.ast.clone();\n\n return cloned;\n },\n\n async stringify(metadata, { format, minify, defer }) {\n if (!isStyleMetadata(metadata)) return;\n\n const code = metadata.ast.toString();\n\n if (format) {\n const payload: FormatStylePayload = { filePath: join(this.root, metadata.filePath) };\n\n if (defer) {\n defer(formatStylePass(payload));\n return code;\n }\n\n try {\n return await formatStyle(code, payload);\n } catch {\n this.log.error(\"Failed to format style\", metadata.filePath);\n return;\n }\n }\n\n if (minify) {\n if (targets === undefined) {\n const { browserslistToTargets } = await import(\"lightningcss\");\n targets = browserslistToTargets(this.browserslist);\n }\n\n const payload: MinifyStylePayload = { filePath: metadata.filePath, targets };\n\n if (defer) {\n defer(minifyStylePass(payload));\n return code;\n }\n\n try {\n return await minifyStyle(code, payload);\n } catch {\n this.log.error(\"Failed to minify style\", metadata.filePath);\n return;\n }\n }\n\n return code;\n },\n\n sourcesProvider(metadata) {\n if (!isStyleMetadata(metadata)) return;\n\n return parseStyleSources(metadata.ast);\n },\n };\n}\n","import { parseHtml } from \"../../../parsers/html-parser.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../../types/common.ts\";\nimport { METADATA_TYPES, type StyleMetadata, type SvgMetadata } from \"../../../types/metadata.ts\";\nimport { isStyleMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { hashContent } from \"../../../utilities/utilities.ts\";\n\nimport type { ValueOrError } from \"../../../utilities/value-or-error.ts\";\nimport type { App } from \"@staticbolt/core\";\n\ntype SvgLoaderResult = ValueOrError<SvgMetadata>;\n\nexport async function svgLoader(this: App, relativePath: string, code: string): Promise<SvgLoaderResult> {\n // Parse HTML to AST (HTML root element)\n const [rootElement, parseError] = parseHtml(code);\n if (parseError !== null) {\n parseError.message = `Failed to parse SVG file \"${relativePath}\"\\n` + parseError.message;\n return [null, parseError];\n }\n\n // Style loader\n const stylesMetadataList = new Map<string, StyleMetadata>();\n\n const styles = rootElement.querySelectorAll(\"style\");\n for (const style of styles) {\n const styleCode = style.textContent;\n if (!styleCode) continue;\n\n const styleMetadata = await this.load(relativePath, { code: styleCode, type: \"css\" });\n if (!isStyleMetadata(styleMetadata)) {\n return [null, new Error(\"Style loader returned non-CSS metadata\")];\n }\n\n const astID = hashContent(styleCode);\n style.setAttribute(CUSTOM_ATTRIBUTES.MetadataID, astID);\n stylesMetadataList.set(astID, styleMetadata);\n }\n\n const svgMetadata: SvgMetadata = {\n type: METADATA_TYPES.SVG,\n ast: rootElement,\n filePath: relativePath,\n id: relativePath,\n stylesMetadataList,\n directDependencies: new Set(),\n };\n\n return [svgMetadata, null];\n}\n","import { parseHtmlSources } from \"../../../ast-utilities/html-utils/parse-html-sources.ts\";\nimport { CUSTOM_ATTRIBUTES } from \"../../../types/common.ts\";\nimport { splitHtmlLink } from \"../../../utilities/html-links.ts\";\nimport { isSvgMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { extname, join } from \"../../../utilities/path.ts\";\nimport { printFmtError } from \"../../../utilities/print-formatted-error.ts\";\nimport { cloneObject } from \"../../../utilities/utilities.ts\";\nimport { formatSvg, formatSvgPass, minifySvg, minifySvgPass } from \"./deferred.ts\";\nimport { svgLoader } from \"./svg-loader.ts\";\n\nimport type { FormatSvgPayload } from \"./deferred.ts\";\nimport type { MetadataSource, Plugin, StyleMetadata } from \"@staticbolt/core\";\n\n/**\n * The SVG half of the core pipeline: parses \".svg\" files as documents, splits their \"<style>\" tags into metadata of their own,\n * and prints them back out.\n *\n * Notes:\n *\n * - Sources come from the document's own links plus the sources of the extracted styles.\n * - \"format\" runs prettier as HTML, and \"minify\" goes through the HTML minifier.\n */\nexport function coreSvgPlugin(): Plugin {\n return {\n name: \"core-svg-metadata\",\n\n async load(content, relativePath, { type }) {\n const [link] = splitHtmlLink(relativePath);\n\n type ??= extname(link).slice(1);\n\n if (type !== \"svg\") {\n return;\n }\n\n const [fileMetadata, metadataError] = await svgLoader.call(this, link, content);\n if (metadataError) {\n printFmtError(metadataError, { function: coreSvgPlugin });\n return;\n }\n\n return fileMetadata;\n },\n\n clone(metadata) {\n if (!isSvgMetadata(metadata)) return;\n\n const cloned = cloneObject(metadata);\n\n cloned.ast = metadata.ast.clone();\n\n cloned.stylesMetadataList = new Map<string, StyleMetadata>();\n for (const [metadataID, cssMetadata] of metadata.stylesMetadataList) {\n cloned.stylesMetadataList.set(metadataID, this.clone(cssMetadata));\n }\n\n return cloned;\n },\n\n async stringify(metadata, { format, minify, defer }) {\n if (!isSvgMetadata(metadata)) return;\n\n const styles = metadata.ast.querySelectorAll(\"style\");\n\n for (const node of styles) {\n const id = node.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!id) continue;\n\n const styleMetadata = metadata.stylesMetadataList.get(id);\n if (!styleMetadata) continue;\n\n node.textContent = await this.stringify(styleMetadata);\n }\n\n const code = metadata.ast.toString();\n\n if (format) {\n const payload: FormatSvgPayload = { filePath: join(this.root, metadata.filePath) };\n\n if (defer) {\n defer(formatSvgPass(payload));\n return code;\n }\n\n try {\n return await formatSvg(code, payload);\n } catch {\n this.log.error(\"Failed to format svg\", metadata.filePath);\n return;\n }\n }\n\n if (minify) {\n if (defer) {\n defer(minifySvgPass());\n return code;\n }\n\n try {\n return await minifySvg(code);\n } catch {\n this.log.error(\"Failed to minify svg\", metadata.filePath);\n return;\n }\n }\n\n return code;\n },\n\n async sourcesProvider(metadata) {\n if (!isSvgMetadata(metadata)) return;\n\n // HTML Links\n const htmlSources = parseHtmlSources(metadata.ast);\n\n const stylesSources: MetadataSource[] = [];\n\n // Embedded styles\n const styles = metadata.ast.querySelectorAll(\"style\");\n for (const style of styles) {\n const id = style.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!id) continue;\n\n const styleMetadata = metadata.stylesMetadataList.get(id);\n if (!styleMetadata) continue;\n\n const requestedSources = await this.requestSources(styleMetadata);\n stylesSources.push(...requestedSources);\n }\n\n return [...htmlSources, ...stylesSources];\n },\n };\n}\n","import json5 from \"json5\";\n\nimport { METADATA_TYPES, type WebManifestMetadata } from \"../../../types/metadata.ts\";\nimport { valueOrError, type ValueOrError } from \"../../../utilities/value-or-error.ts\";\n\nimport type { App } from \"@staticbolt/core\";\n\nexport function webManifestLoader(this: App, relativePath: string, code: string): ValueOrError<WebManifestMetadata> {\n const [manifestData, manifestError] = valueOrError(json5.parse<WebManifestMetadata[\"ast\"]>)(code);\n if (manifestError !== null) {\n return [null, manifestError];\n }\n\n // check if the manifest is valid\n if (!manifestData.name || !manifestData.short_name || !manifestData.icons) {\n return [null, new Error(`Invalid manifest.json file: ${relativePath}`)];\n }\n\n const webManifestMetadata: WebManifestMetadata = {\n type: METADATA_TYPES.WebAppManifest,\n ast: manifestData,\n filePath: relativePath,\n id: relativePath,\n directDependencies: new Set(),\n };\n\n return [webManifestMetadata, null];\n}\n","import { splitHtmlLink } from \"../../../utilities/html-links.ts\";\nimport { isWebManifestMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { basename } from \"../../../utilities/path.ts\";\nimport { printFmtError } from \"../../../utilities/print-formatted-error.ts\";\nimport { cloneObject } from \"../../../utilities/utilities.ts\";\nimport { webManifestLoader } from \"./web-manifest-loader.ts\";\n\nimport type { MetadataSource, Plugin } from \"@staticbolt/core\";\n\n/**\n * The web app manifest half of the core pipeline: loads a \"manifest.json\" as JSON data and reports the assets it points at.\n *\n * Notes:\n *\n * - Detection is by file name, so a manifest under a different name is only picked up when the type is passed explicitly.\n * - Icons, screenshots and shortcut icons are reported as sources, so their paths are resolved and rebased with everything else.\n * - Printing gives compact JSON, or indented when formatting.\n */\nexport function coreWebManifestPlugin(): Plugin {\n return {\n name: \"core-web-manifest-metadata\",\n\n load(content, relativePath, { type }) {\n const [link] = splitHtmlLink(relativePath);\n\n type ??= basename(link);\n\n if (type !== \"manifest.json\") {\n return;\n }\n\n const [fileMetadata, metadataError] = webManifestLoader.call(this, link, content);\n if (metadataError) {\n printFmtError(metadataError, { function: coreWebManifestPlugin, filePath: relativePath });\n return;\n }\n\n return fileMetadata;\n },\n\n clone(metadata) {\n if (!isWebManifestMetadata(metadata)) return;\n\n const cloned = cloneObject(metadata);\n cloned.ast = structuredClone(metadata.ast);\n\n return cloned;\n },\n\n stringify(metadata, { format }) {\n if (!isWebManifestMetadata(metadata)) return;\n\n if (format) {\n return JSON.stringify(metadata.ast, null, 2);\n }\n\n return JSON.stringify(metadata.ast);\n },\n\n sourcesProvider(metadata) {\n if (!isWebManifestMetadata(metadata)) return;\n\n const icons = metadata.ast.icons ?? [];\n const shortcutIcons = metadata.ast.shortcuts?.flatMap(shortcut => shortcut.icons ?? []) ?? [];\n const screenshots = metadata.ast.screenshots ?? [];\n\n const sources: MetadataSource[] = [];\n\n for (const asset of [...icons, ...screenshots, ...shortcutIcons]) {\n const source = asset.src;\n if (!source) continue;\n\n sources.push({\n node: asset,\n get source() {\n return source;\n },\n set source(newValue) {\n asset.src = newValue;\n },\n });\n }\n\n return sources;\n },\n };\n}\n","import { createServer } from \"node:net\";\nimport { createInterface } from \"node:readline/promises\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport chalk from \"chalk\";\n\nimport { Log } from \"../../../utilities/logger.ts\";\n\nexport const PROJECT_HEADER = \"x-staticbolt-project\";\nexport const PID_HEADER = \"x-staticbolt-pid\";\n\nconst FREE_PORT_SEARCH = 20;\nconst KILL_TIMEOUT_MS = 3000;\n\ntype PortOwner = { kind: \"other\" } | { kind: \"staticbolt\"; project: string; pid: number };\n\ninterface Choice {\n label: string;\n port?: number;\n killPid?: number;\n}\n\n/**\n * The port to listen on: `port` when it is free, otherwise what the user picks. Another dev server of ours can be killed to take\n * its port over, any holder can be sidestepped with the next free port, and declining, or having no terminal to ask on, fails\n * with the wanted port's error.\n */\nexport async function claimPort(port: number, host: string, project: string): Promise<number> {\n if (await isPortFree(port, host)) return port;\n\n const owner = await identifyOwner(port);\n const problem = describeOwner(owner, port, project);\n const choice = process.stdin.isTTY ? await ask(problem, await listChoices(owner, port, host)) : undefined;\n\n if (choice?.port === undefined) {\n throw new Error(`${problem} Stop what is using it, or pick another with developmentServerPlugin({ port })`, { cause: owner });\n }\n\n if (choice.killPid !== undefined) {\n await kill(choice.killPid, port, host);\n }\n\n return choice.port;\n}\n\n/** A `HEAD /` answered with the project header means a dev server of ours. Anything else, or no answer, is another application. */\nasync function identifyOwner(port: number): Promise<PortOwner> {\n try {\n const response = await fetch(`http://127.0.0.1:${port}/`, { method: \"HEAD\", signal: AbortSignal.timeout(1000) });\n const project = response.headers.get(PROJECT_HEADER);\n const pid = Number(response.headers.get(PID_HEADER));\n\n return project && pid ? { kind: \"staticbolt\", project, pid } : { kind: \"other\" };\n } catch {\n return { kind: \"other\" };\n }\n}\n\nfunction describeOwner(owner: PortOwner, port: number, project: string): string {\n if (owner.kind === \"other\") return `Port ${port} is used by another application.`;\n if (owner.project === project) return `A dev server for this project is already running on port ${port}.`;\n\n return `Port ${port} is used by the dev server of \"${owner.project}\".`;\n}\n\nasync function listChoices(owner: PortOwner, port: number, host: string): Promise<Choice[]> {\n const choices: Choice[] = [];\n\n if (owner.kind === \"staticbolt\") {\n choices.push({ label: `Kill it and use port ${port}`, port, killPid: owner.pid });\n }\n\n const freePort = await findFreePort(port + 1, host);\n if (freePort !== undefined) {\n choices.push({ label: `Use port ${freePort}`, port: freePort });\n }\n\n choices.push({ label: \"Do nothing\" });\n\n return choices;\n}\n\nasync function kill(pid: number, port: number, host: string): Promise<void> {\n process.kill(pid);\n\n const deadline = Date.now() + KILL_TIMEOUT_MS;\n while (Date.now() < deadline) {\n if (await isPortFree(port, host)) return;\n await sleep(100);\n }\n\n throw new Error(`Port ${port} is still busy after stopping process ${pid}`);\n}\n\nasync function findFreePort(from: number, host: string): Promise<number | undefined> {\n for (let port = from; port < from + FREE_PORT_SEARCH; port++) {\n if (await isPortFree(port, host)) return port;\n }\n\n return undefined;\n}\n\nfunction isPortFree(port: number, host: string): Promise<boolean> {\n return new Promise(resolve => {\n const server = createServer();\n\n server.once(\"error\", () => resolve(false));\n server.listen(port, host, () => server.close(() => resolve(true)));\n });\n}\n\n/** Numbered choices in the terminal. An empty answer takes the first, a closed input the last. */\nasync function ask(question: string, choices: Choice[]): Promise<Choice> {\n const readline = createInterface({ input: process.stdin, output: process.stdout });\n\n try {\n Log.warn(question);\n for (const [index, choice] of choices.entries()) {\n console.log(` ${chalk.bold(index + 1)}) ${choice.label}`);\n }\n\n while (true) {\n const answer = await readline.question(chalk.bold(\" Choice (1): \"));\n const picked = choices[answer.trim() === \"\" ? 0 : Number(answer) - 1];\n\n if (picked) return picked;\n }\n } catch {\n return choices.at(-1)!;\n } finally {\n readline.close();\n }\n}\n","import { isHtmlMetadata } from \"../../../utilities/metadata-utilities.ts\";\n\nimport type { MetadataBase } from \"@staticbolt/core\";\n\nconst id = \"inject-reload-script\";\n\nexport function injectReloadScript(metadata: MetadataBase) {\n if (!isHtmlMetadata(metadata)) return;\n\n // eslint-disable-next-line unicorn/require-css-escape\n const isAlreadyInjected = metadata.ast.querySelector(`script[id=\"${id}\"]`);\n if (isAlreadyInjected) return;\n\n const element = metadata.ast.querySelector(\"html\");\n if (!element) return;\n\n const newNode = `<script id=\"${id}\">${HOT_RELOAD_SCRIPT(metadata.id)}</script>`;\n\n element.insertAdjacentHTML(\"beforeend\", newNode);\n}\n\nconst HOT_RELOAD_SCRIPT = (htmlFilePath: string) => String.raw`\n// Code injected by staticbolt\n\nconst htmlFilePath = \"${htmlFilePath}\";\n\nfunction refreshCSS() {\n const sheets = [].slice.call(document.getElementsByTagName(\"link\"));\n const head = document.getElementsByTagName(\"head\")[0];\n\n for (let i = 0; i < sheets.length; ++i) {\n const elem = sheets[i];\n const parent = elem.parentElement || head;\n parent.removeChild(elem);\n const rel = elem.rel;\n if ((elem.href && typeof rel != \"string\") || rel.length == 0 || rel.toLowerCase() == \"stylesheet\") {\n const url = elem.href.replace(/(&|\\?)_cacheOverride=\\d+/, \"\");\n elem.href = url + (url.indexOf(\"?\") >= 0 ? \"&\" : \"?\") + \"_cacheOverride=\" + new Date().valueOf();\n }\n parent.appendChild(elem);\n }\n}\n\nfunction cleanHref(el) {\n const url = new URL(el.href, window.location.origin);\n\n let path = url.pathname;\n\n if (!path.startsWith(\"./\") && !path.startsWith(\"../\")) {\n path = \".\" + path;\n }\n\n return path;\n}\n\nfunction getCssLinks() {\n const links = document.querySelectorAll(\"link[rel=stylesheet]\");\n return Array.from(links).map(link => cleanHref(link));\n}\n\nconst address = (window.location.protocol === \"http:\" ? \"ws://\" : \"wss://\")\n + window.location.host + window.location.pathname + \"/ws\";\n\nconst RETRY_INTERVAL_MS = 1000;\n\nlet retryTimeout = null;\nlet hasConnected = false;\nlet socket = null;\n\nfunction connect() {\n socket = new WebSocket(address);\n\n\n socket.onopen = function () {\n if (hasConnected) {\n location.reload();\n return;\n }\n\n hasConnected = true;\n console.log(\"[staticbolt] WebSocket connected.\");\n };\n\n socket.onmessage = function (msg) {\n const data = JSON.parse(msg.data).data;\n\n if (!Array.isArray(data)) return;\n\n if (data.includes(htmlFilePath)) {\n location.reload();\n return;\n }\n\n const links = getCssLinks();\n if (data.some(link => links.includes(link))) {\n refreshCSS();\n }\n };\n\n socket.onclose = function () {\n console.log(\"[staticbolt] WebSocket disconnected. Retrying in \" + RETRY_INTERVAL_MS + \"ms...\");\n retryTimeout = setTimeout(() => {\n connect();\n }, RETRY_INTERVAL_MS);\n };\n\n socket.onerror = function () {\n socket.close();\n };\n}\n\n// Navigating away does not reliably close the socket\nwindow.addEventListener(\"pagehide\", function () {\n clearTimeout(retryTimeout);\n\n if (socket) {\n socket.onclose = null;\n socket.close();\n }\n});\n\n// Restored from the back/forward cache.\nwindow.addEventListener(\"pageshow\", function (event) {\n if (event.persisted) {\n location.reload();\n }\n});\n\nconnect();\n`;\n","import type { MetadataBase } from \"@staticbolt/core\";\n\nexport function orderByDependencyDepth(\n allMetadata: readonly MetadataBase[],\n entryPoints: string[],\n filePaths: Set<string>\n): string[] {\n const metadataById = new Map(allMetadata.map(m => [m.id, m]));\n\n // BFS from all entry points to compute max depth for each reachable node\n const maxDepth = new Map<string, number>();\n const queue: { id: string; depth: number }[] = entryPoints.map(id => ({ id, depth: 0 }));\n\n while (queue.length > 0) {\n const { id, depth } = queue.shift()!;\n\n // Keep the deepest (max) depth seen for this node\n const known = maxDepth.get(id) ?? -1;\n if (depth <= known) continue;\n maxDepth.set(id, depth);\n\n const metadata = metadataById.get(id);\n if (!metadata) continue;\n\n if (depth >= allMetadata.length) continue;\n\n for (const dependencyId of metadata.directDependencies) {\n queue.push({ id: dependencyId, depth: depth + 1 });\n }\n }\n\n const reachable: string[] = [];\n const unreachable: string[] = [];\n\n for (const id of filePaths) {\n if (maxDepth.has(id)) {\n reachable.push(id);\n continue;\n }\n\n unreachable.push(id);\n }\n\n // Sort reachable: deepest first (highest depth number first)\n reachable.sort((a, b) => (maxDepth.get(b) ?? 0) - (maxDepth.get(a) ?? 0));\n\n return [...unreachable, ...reachable];\n}\n","import type { IncomingMessage } from \"node:http\";\nimport { networkInterfaces } from \"node:os\";\nimport type { Duplex } from \"node:stream\";\nimport fastifyStatic from \"@fastify/static\";\nimport fastifyUrlData from \"@fastify/url-data\";\nimport chalk from \"chalk\";\nimport Fastify from \"fastify\";\nimport { WebSocketServer } from \"ws\";\n\nimport { Log } from \"../../../utilities/logger.ts\";\nimport { isHtmlMetadata, isPackageMetadata, isScriptMetadata, isStyleMetadata } from \"../../../utilities/metadata-utilities.ts\";\nimport { basename, extname, join, normalize } from \"../../../utilities/path.ts\";\nimport { claimPort, PID_HEADER, PROJECT_HEADER } from \"./claim-port.ts\";\nimport { injectReloadScript } from \"./inject-reload-script.ts\";\nimport { orderByDependencyDepth } from \"./order-by-dependency-depth.ts\";\n\nimport type { MetadataBase, Plugin } from \"@staticbolt/core\";\nimport type { onRequestHookHandler } from \"fastify\";\nimport type { Server, WebSocket } from \"ws\";\n\n/** What the serve command hands over through `app.pluginData`, taking precedence over the plugin options for that run. */\nexport interface DevelopmentServerOverrides {\n host?: boolean | string;\n}\n\nexport const DEVELOPMENT_SERVER_OVERRIDES = \"development-server\";\n\nexport interface DevelopmentServerOptions {\n /**\n * Where the dev server listens. `true` listens on every address, so the site is reachable from other devices on the network; a\n * string is a specific address to listen on. The `--host` flag of the serve command turns this on for one run.\n *\n * @default false\n */\n host?: boolean | string;\n\n /**\n * The dev server port.\n *\n * @default 3000\n */\n port?: number;\n\n /**\n * Entry url pathname when opening the browser.\n *\n * @default /\n */\n entry?: string;\n\n /**\n * Files in the public directory are served from the root as a fallback.\n *\n * @default \"public\"\n */\n publicDirectory?: string;\n}\n\n/**\n * The dev server: serves the build from memory over Fastify, compiles pages on demand, and pushes updates to the browser over a\n * web socket.\n *\n * Notes:\n *\n * - Development only.\n * - A request is answered from what is already compiled; otherwise the path is resolved to an entry point and compiled on the spot,\n * with a directory path getting \"index.html\" appended. Anything that is not an entry point falls through to the static handler,\n * which serves the project root and the public directory.\n * - The reload script is injected into HTML entry points as they are served, so it never exists in the built output.\n * - On a change, the affected pages are recompiled in dependency order and metadata nothing references any more is dropped. If only\n * CSS changed the stylesheets are swapped in place, otherwise the page reloads.\n * - Compiled pages are trimmed to the number of connected clients, dropping the least recently served ones.\n * - Closing the app drops the connected clients and stops the server, which frees the port for the next one; the browser reloads\n * itself as soon as it reconnects.\n */\nexport function developmentServerPlugin(options: DevelopmentServerOptions = {}): Plugin {\n const port = options.port ?? 3000;\n const entry = options.entry ?? \"/\";\n const publicDirectory = options.publicDirectory ?? \"public\";\n\n let fastify: Fastify.FastifyInstance | undefined;\n let websocket: Server | undefined;\n const wsClients: Set<WebSocket> = new Set();\n const entryPointAgeMap = new Map<string, number>();\n\n function upgradeWebSocketHandler(server: Server, request: IncomingMessage, socket: Duplex, head: Buffer) {\n server.handleUpgrade(request, socket, head, ws => {\n wsClients.add(ws);\n server.emit(\"connection\", ws, request);\n\n ws.send(JSON.stringify({ data: \"connected\" }));\n\n ws.on(\"close\", () => {\n wsClients.delete(ws);\n });\n\n ws.on(\"error\", error => {\n Log.error(\"WebSocket error:\", error.message);\n });\n });\n }\n\n function sendMessageToClients(message: string[]) {\n for (const client of wsClients) {\n if (client) client.send(JSON.stringify({ data: message }));\n }\n }\n\n return {\n name: \"dev-server\",\n\n async setup() {\n if (this.production) return;\n\n // Web Socket\n const websocketServer = new WebSocketServer({ noServer: true });\n websocket = websocketServer;\n\n // Web Server\n const projectName = basename(this.root);\n const fastifyServe: onRequestHookHandler = async (request, reply) => {\n reply.header(PROJECT_HEADER, projectName).header(PID_HEADER, process.pid);\n\n const requestPath = normalize(\".\" + decodeURIComponent(request.urlData().path || \"./\"));\n await this.handleRequest(requestPath, reply, request);\n };\n\n fastify = Fastify();\n fastify.register(fastifyUrlData);\n fastify.register(fastifyStatic, { root: [this.root, join(this.root, publicDirectory)] });\n fastify.addHook(\"onRequest\", fastifyServe);\n fastify.server.on(\"upgrade\", (request, socket, head) => upgradeWebSocketHandler(websocketServer, request, socket, head));\n\n websocketServer.on(\"connection\", () => {\n // From oldest to newest\n const sortedByAge = Array.from(entryPointAgeMap)\n .toSorted((a, b) => a[1] - b[1])\n .map(([id]) => id);\n\n // Trim excess\n const excess = sortedByAge.length - wsClients.size;\n\n // Trim excess\n if (excess > 0) {\n for (const id of sortedByAge.slice(0, excess)) {\n entryPointAgeMap.delete(id);\n removeAndPruneOrphans(this.metadataList, id);\n }\n }\n });\n\n const overrides = this.pluginData[DEVELOPMENT_SERVER_OVERRIDES] as DevelopmentServerOverrides | undefined;\n const host = resolveHost(overrides?.host ?? options.host);\n const listeningPort = await claimPort(port, host, projectName);\n await fastify.listen({ port: listeningPort, host });\n\n this.log.info(describeAddresses(host, listeningPort, entry));\n },\n\n async teardown() {\n for (const client of wsClients) {\n client.terminate();\n }\n\n wsClients.clear();\n websocket?.close();\n\n await fastify?.close();\n },\n\n async onFileEvent(event, changedSource) {\n if (event === \"unlink\") {\n removeAndPruneOrphans(this.metadataList, changedSource);\n return;\n }\n\n if (event !== \"change\") return;\n\n const htmlEntryPoints = this.metadataList.filter(meta => this.entryPoints.has(meta.id) && isHtmlMetadata(meta));\n const affected = htmlEntryPoints\n .filter(meta => meta.id === changedSource || isDependency(this.metadataList, meta, changedSource))\n .map(entry => entry.id);\n\n const compileList = await this.getCompileList(\"change\", changedSource);\n compileList.add(changedSource);\n\n const ordered = orderByDependencyDepth(this.metadataList, affected, compileList);\n\n let isStyleOnly = true;\n\n for (const id of ordered) {\n const oldMetadataList = this.filterMetadata({ id });\n\n // Nothing to recompile\n if (oldMetadataList.length === 0) {\n continue;\n }\n\n // Capture all old dependencies before removal\n const oldDependencies = new Set(oldMetadataList.flatMap(m => Array.from(m.directDependencies)));\n\n // Remove any previous metadata before processing\n this.removeMetadata(oldMetadataList);\n\n // Process\n const isSuccess = await this.process(id);\n if (!isSuccess) {\n this.addMetadata(oldMetadataList);\n continue;\n }\n\n // Capture new dependencies\n const newMetadataList = this.filterMetadata({ id });\n const newDependencies = new Set(newMetadataList.flatMap(m => Array.from(m.directDependencies)));\n\n // Diff to find removed dependencies\n const removedDependencies = Array.from(oldDependencies).filter(dependency => !newDependencies.has(dependency));\n\n // Remove orphans\n for (const dependency of removedDependencies) {\n const isStillReferenced = this.metadataList.some(m => m.directDependencies && m.directDependencies.has(dependency));\n if (isStillReferenced) continue;\n\n const orphans = this.filterMetadata({ id: dependency });\n if (orphans && orphans.length > 0) {\n this.removeMetadata(orphans);\n }\n }\n\n if (extname(id) !== \".css\") {\n isStyleOnly = false;\n }\n\n this.log.info(\"Recompiled:\", id);\n }\n\n // Refresh CSS or reload clients\n if (isStyleOnly) {\n // changedSource may be a deeply @import-ed file. The browser can only\n // hot-swap <link> tags it actually has in the DOM, so resolve upward\n // to the CSS files that are direct dependencies of the affected HTML pages.\n const rootCssFiles = new Set<string>();\n\n for (const htmlId of affected) {\n const metadataListWithId = this.filterMetadata({ id: htmlId });\n for (const meta of metadataListWithId) {\n for (const dependency of meta.directDependencies) {\n if (extname(dependency) === \".css\") {\n rootCssFiles.add(dependency);\n }\n }\n }\n }\n\n // Fallback: if nothing resolved (e.g. changedSource IS a root), use it directly\n sendMessageToClients(rootCssFiles.size > 0 ? Array.from(rootCssFiles) : [changedSource]);\n return;\n }\n\n // Reload clients\n sendMessageToClients(affected);\n },\n\n async handleRequest(requestPath, reply) {\n // Add index.html for a directory path\n if (!extname(requestPath)) {\n requestPath = join(requestPath, \"index.html\");\n }\n\n // Already compiled\n let metadata = this.metadataList.find(\n m =>\n // Flatten paths outside of root\n m.filePath.replace(/^(\\.\\.\\/)+/, \"./\") === requestPath\n );\n\n if (!metadata) {\n // Try to get the real file path\n const resolvedRequestPath = (await this.resolveRequestPath(requestPath)) ?? requestPath;\n\n // Only compile entry points\n if (this.entryPoints.has(resolvedRequestPath)) {\n this.log.info(\"Compiling:\", resolvedRequestPath);\n\n await this.process(resolvedRequestPath);\n\n // Should be added after compilation\n metadata = this.findMetadata({ filePath: requestPath });\n }\n }\n\n if (!metadata) {\n return;\n }\n\n if (this.entryPoints.has(metadata.id) && isHtmlMetadata(metadata)) {\n // Hot reload script\n injectReloadScript(metadata);\n\n entryPointAgeMap.set(metadata.id, Date.now());\n }\n\n const stringified = await this.stringify(metadata);\n if (typeof stringified !== \"string\") return;\n\n reply.type(getMetadataMimeType(metadata)).send(stringified);\n\n return true;\n },\n };\n}\n\n/** The URLs the server answers on: localhost, plus every LAN address when it is bound to all interfaces. */\nfunction describeAddresses(host: string, port: number, entry: string): string {\n const isEveryInterface = host === \"0.0.0.0\" || host === \"::\";\n const isLoopback = host === \"127.0.0.1\" || host === \"::1\";\n const url = (hostname: string) => chalk.green(`http://${hostname}:${port}${entry}`);\n\n const lines = [`${chalk.bold(\"Local:\")} ${url(isEveryInterface || isLoopback ? \"localhost\" : host)}`];\n\n if (isEveryInterface) {\n for (const address of lanAddresses()) {\n lines.push(`${chalk.bold(\"Network:\")} ${url(address)}`);\n }\n } else if (isLoopback) {\n lines.push(`${chalk.bold(\"Network:\")} ${chalk.dim(\"use --host to expose\")}`);\n }\n\n return \"\\n\" + lines.join(\"\\n\");\n}\n\nfunction lanAddresses(): string[] {\n return Object.values(networkInterfaces())\n .flat()\n .filter(address => address?.family === \"IPv4\" && !address.internal)\n .map(address => address!.address);\n}\n\nfunction isDependency(allMetadata: readonly MetadataBase[], metadata: MetadataBase, filePath: string): boolean {\n if (metadata.directDependencies.has(filePath)) {\n return true;\n }\n\n const metadataByPath = new Map(allMetadata.map(m => [m.id, m]));\n\n const visited = new Set<string>();\n const queue = [...metadata.directDependencies];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n\n if (visited.has(current)) continue;\n visited.add(current);\n\n const currentMetadata = metadataByPath.get(current);\n if (!currentMetadata) continue;\n\n for (const dependency of currentMetadata.directDependencies) {\n if (dependency === filePath) return true;\n if (!visited.has(dependency)) queue.push(dependency);\n }\n }\n\n return false;\n}\n\nfunction getMetadataMimeType(metadata: MetadataBase) {\n if (isHtmlMetadata(metadata)) {\n return \"text/html\";\n }\n\n if (isStyleMetadata(metadata)) {\n return \"text/css\";\n }\n\n if (isScriptMetadata(metadata) || isPackageMetadata(metadata)) {\n return \"application/javascript\";\n }\n\n return \"text/plain\";\n}\n\n/**\n * Removes a metadata entry by ID from the array in place, then cascades removal to any of its dependencies that are no longer\n * referenced by any remaining entry. Repeats until no unreferenced entries remain.\n */\nfunction removeAndPruneOrphans(metadataList: MetadataBase[], targetId: string): void {\n const queue = [targetId];\n const removed = new Set<string>();\n\n while (queue.length > 0) {\n const currentId = queue.shift()!;\n\n if (removed.has(currentId)) continue;\n removed.add(currentId);\n\n // Collect deps from ALL entries with this id\n const entries = metadataList.filter(m => m.id === currentId);\n if (entries.length === 0) continue;\n\n const dependencies = new Set(entries.flatMap(m => [...m.directDependencies]));\n\n // Remove all copies\n for (let index = metadataList.length - 1; index >= 0; index--) {\n if (metadataList[index].id === currentId) metadataList.splice(index, 1);\n }\n\n // Queue orphaned deps\n for (const dependencyId of dependencies) {\n const isStillUsed = metadataList.some(m => m.directDependencies.has(dependencyId));\n if (!isStillUsed) queue.push(dependencyId);\n }\n }\n}\n\n/** Every address, a given one, or the IPv4 loopback: \"localhost\" itself can resolve to IPv6 only, Windows being the usual case. */\nfunction resolveHost(host: boolean | string | undefined): string {\n if (host === true) return \"0.0.0.0\";\n if (typeof host === \"string\" && host !== \"\") return host;\n return \"127.0.0.1\";\n}\n","import chalk from \"chalk\";\n\ntype ExecutionTime = Record<string, Record<string, number>>;\n\nfunction formatDuration(ms: number): string {\n if (ms < 1) {\n return chalk.gray(`${(ms * 1000).toFixed(2)}μs`);\n }\n if (ms < 1000) {\n const color = ms < 100 ? chalk.green : ms < 500 ? chalk.yellow : chalk.red;\n return color(`${ms.toFixed(2)}ms`);\n }\n return ms < 60_000 ? chalk.redBright(`${(ms / 1000).toFixed(2)}s`) : chalk.magenta(`${(ms / 60_000).toFixed(2)}m`);\n}\n\nfunction buildBar(value: number, total: number): string {\n const BAR_WIDTH = 16;\n const ratio = total > 0 ? value / total : 0;\n const filled = Math.round(ratio * BAR_WIDTH);\n const empty = BAR_WIDTH - filled;\n const pct = (ratio * 100).toFixed(0).padStart(3);\n\n const filledBar =\n ratio < 0.2\n ? chalk.green(\"█\".repeat(filled))\n : ratio < 0.5\n ? chalk.yellow(\"█\".repeat(filled))\n : chalk.red(\"█\".repeat(filled));\n\n return filledBar + chalk.dim(\"░\".repeat(empty)) + chalk.dim(` ${pct}%`);\n}\n\nexport function printExecutionTime(executionTime: ExecutionTime): void {\n // Sort groups by their total time descending\n const sortedGroups = Object.entries(executionTime).toSorted(([, a], [, b]) => {\n const totalA = Object.values(a).reduce((sum, v) => sum + v, 0);\n const totalB = Object.values(b).reduce((sum, v) => sum + v, 0);\n return totalB - totalA;\n });\n\n for (const [groupName, metrics] of sortedGroups) {\n const total = Object.values(metrics).reduce((sum, v) => sum + v, 0);\n\n // Filter out hooks under 1ms, sort remaining by duration descending\n const entries = Object.entries(metrics)\n .filter(([, v]) => v >= 1)\n .toSorted(([, a], [, b]) => b - a);\n\n console.log();\n\n // Empty groups: single line, no box\n if (entries.length === 0) {\n console.log(chalk.bold.cyan(\"─ \") + chalk.bold.white(groupName) + chalk.dim(` total: ${formatDuration(total)}`));\n continue;\n }\n\n const maxLabelLength = Math.max(...entries.map(([k]) => k.length));\n\n console.log(chalk.bold.cyan(\"─ \") + chalk.bold.white(groupName) + chalk.dim(` total: ${formatDuration(total)}`));\n\n for (const [key, value] of entries) {\n const label = chalk.dim(key.padEnd(maxLabelLength));\n const bar = buildBar(value, total);\n const time = formatDuration(value);\n\n console.log(` ${label} ${bar} ${time}`);\n }\n }\n\n console.log();\n}\n","import browserslistFn from \"browserslist\";\nimport chokidar from \"chokidar\";\n\nimport { printExecutionTime } from \"./helpers/pirnt-debug.ts\";\nimport { coreBasePlugin } from \"./plugins/core-plugins/base-plugin/base-plugin.ts\";\nimport { Resolver } from \"./resolver/resolver.ts\";\nimport { createLog, Log } from \"./utilities/logger.ts\";\nimport { basename, isAbsolute, join, normalize, relative, resolve } from \"./utilities/path.ts\";\n\nimport type {\n MetadataBase,\n AppConfig,\n BoundPlugin,\n MetadataSource,\n Plugin,\n ServerReply,\n ServerRequest,\n StringifyOptions,\n} from \"@staticbolt/core\";\nimport type { FSWatcher } from \"chokidar\";\n\ntype PluginOnlyHooks = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof BoundPlugin as BoundPlugin[K] extends (...arguments_: any) => any ? K : never]: BoundPlugin[K];\n};\n\ntype PluginHook = keyof PluginOnlyHooks;\n\ntype AnyHook = (...arguments_: never[]) => unknown;\n\n/** The hooks that run on an app context. `cli` runs on the CLI program instead, and the `lsp*` hooks are called as written. */\ntype BoundHook = Exclude<PluginHook, \"cli\" | \"lspHtmlData\" | \"lspEmbeddedLanguages\" | \"lspValidate\">;\n\n/** Every bound hook, in bind order. The `satisfies` makes a hook added to `Plugin` a type error until it is listed here. */\nconst BOUND_HOOKS = Object.keys({\n setup: true,\n teardown: true,\n read: true,\n load: true,\n resolveSource: true,\n transformSource: true,\n preTransform: true,\n transform: true,\n postTransform: true,\n write: true,\n postBuild: true,\n clone: true,\n stringify: true,\n sourcesProvider: true,\n rebaseSource: true,\n onMetadataRebase: true,\n\n // Dev server\n handleRequest: true,\n resolveRequestPath: true,\n onFileEvent: true,\n resolveCompileList: true,\n} satisfies Record<BoundHook, true>) as BoundHook[];\n\n/**\n * Shared no-op bound to hooks a plugin doesn't implement. Hot loops compare against it to skip the call (and the `await`\n * microtask) entirely.\n */\nconst emptyFunction = () => {};\n\nexport class App {\n readonly configPath: string;\n\n /** The absolute path to the project root. */\n readonly root: string;\n\n /** The absolute path to the output directory. */\n readonly outdir: string;\n\n /** Whether the application is running in production mode. */\n readonly production: boolean;\n\n /** A list of browsers to target. */\n readonly browserslist: string[];\n\n readonly metadataList: MetadataBase[] = [];\n\n private readonly plugins: BoundPlugin[] = [];\n\n readonly resolver: Resolver;\n\n log = Log;\n\n /** File paths to load as sources. */\n readonly entryPoints: Set<string> = new Set();\n\n /** Any type of data for plugins to use. */\n readonly pluginData: Record<string, unknown> = {};\n\n /** Exclude paths from being emitted. */\n readonly emitExclude: Set<MetadataBase> = new Set();\n\n /** Chokidar watcher. Development only, and gone once the app is closed. */\n watcher: FSWatcher | undefined;\n\n private isPluginInitialized = false;\n private isClosed = false;\n\n private measureExecutionTime = false;\n private executionTime: Record<string, Record<string, number>> = {};\n\n /** How long the hooks called from inside the hook currently being measured took. Held in an object so plugin contexts share it. */\n private readonly nestedTime = { ms: 0 };\n\n readonly pluginIndex: number = -1;\n readonly pluginName: string = \"\";\n\n constructor(options: AppConfig = {}, configPath: string) {\n // Config\n this.configPath = configPath;\n this.root = resolve(options.root ?? process.cwd());\n this.production = options.production ?? false;\n this.measureExecutionTime = options.measureExecutionTime ?? false;\n options.outdir ??= \"./dist\";\n this.outdir = isAbsolute(options.outdir) ? options.outdir : join(this.root, options.outdir);\n this.browserslist = browserslistFn(options.browserslist, { path: this.root });\n this.resolver = new Resolver(this.root, this.production, options.aliases);\n\n // Load plugins\n const pluginsList = options.plugins ?? [];\n for (const pluginOrPlugins of pluginsList) {\n const items = Array.isArray(pluginOrPlugins) ? pluginOrPlugins : [pluginOrPlugins];\n for (const plugin of items) {\n this.plugins.push(this.bindPlugin(plugin, this.plugins.length));\n }\n }\n\n // Base plugin\n this.plugins.push(this.bindPlugin(coreBasePlugin(), this.plugins.length));\n\n // Rename duplicates\n const groups = new Map<string, Plugin[]>();\n\n for (const plugin of this.plugins) {\n const name = plugin.name;\n\n if (!groups.has(name)) {\n groups.set(name, []);\n }\n\n groups.get(name)!.push(plugin);\n }\n\n for (const [name, list] of groups) {\n if (list.length <= 1) continue;\n\n for (const [index, p] of list.entries()) {\n p.name = `${name}#${index}`;\n }\n }\n\n if (this.production) {\n return;\n }\n\n // Create watcher\n this.watcher = chokidar.watch([], { cwd: this.root, ignoreInitial: true });\n this.watcher\n .on(\"change\", async changePath => await this.emitFileChange(\"change\", changePath))\n .on(\"add\", async changePath => await this.emitFileChange(\"add\", changePath))\n .on(\"unlink\", async changePath => await this.emitFileChange(\"unlink\", changePath))\n .on(\"error\", error => {\n this.log.error(\"FILE WATCHER ERROR:\");\n console.error(error);\n });\n }\n\n /** Binds a copy of the plugin's hooks to this app, leaving the user's object untouched. */\n private bindPlugin(plugin: Plugin, pluginIndex: number): BoundPlugin {\n const pluginContext = Object.create(this) as App & { pluginIndex: number; pluginName: string };\n pluginContext.pluginIndex = pluginIndex;\n pluginContext.pluginName = plugin.name;\n pluginContext.log = createLog(`[${plugin.name}]`);\n\n const boundPlugin = { ...plugin } as BoundPlugin;\n\n // A hook the plugin does not implement becomes the shared no-op.\n const hooks = boundPlugin as Record<BoundHook, AnyHook | undefined>;\n\n for (const hookName of BOUND_HOOKS) {\n const hook = hooks[hookName];\n hooks[hookName] = hook ? hook.bind(pluginContext) : emptyFunction;\n }\n\n return boundPlugin;\n }\n\n private callPluginMethod<T extends keyof PluginOnlyHooks>(\n plugin: BoundPlugin,\n method: T,\n ...arguments_: Parameters<PluginOnlyHooks[T]>\n ) {\n if (!this.measureExecutionTime) {\n const methodFunction = plugin[method] as (...arguments__: unknown[]) => unknown;\n return methodFunction(...arguments_) as ReturnType<BoundPlugin[T]>;\n }\n\n this.executionTime[plugin.name] ??= {};\n this.executionTime[plugin.name][method] ??= 0;\n\n const now = performance.now();\n const callerNestedTime = this.nestedTime.ms;\n this.nestedTime.ms = 0;\n\n /**\n * Hooks call back into the app, so what a hook spends inside other hooks is subtracted from its own time and handed to the\n * caller instead. Every dispatch is awaited in order, so one hook is ever being measured at a time.\n */\n const record = () => {\n const elapsed = performance.now() - now;\n this.executionTime[plugin.name][method] += elapsed - this.nestedTime.ms;\n this.nestedTime.ms = callerNestedTime + elapsed;\n };\n\n const methodFunction = plugin[method] as (...arguments__: unknown[]) => unknown;\n const result = methodFunction(...arguments_) as ReturnType<BoundPlugin[T]>;\n\n // Async hooks must be timed until they settle, not until they return their promise.\n if (result instanceof Promise) {\n return result.finally(record) as ReturnType<BoundPlugin[T]>;\n }\n\n record();\n\n return result;\n }\n\n private async emitFileChange(event: \"change\" | \"add\" | \"unlink\", filePath: string) {\n filePath = normalize(filePath);\n\n for (const plugin of this.plugins) {\n if (plugin.onFileEvent === emptyFunction) continue;\n await this.callPluginMethod(plugin, \"onFileEvent\", event, filePath);\n }\n }\n\n async run() {\n const mode = this.production ? \"production\" : \"development\";\n this.log.info(`Starting in ${mode} mode`);\n\n // setup\n if (this.plugins.length > 0) {\n this.log.info(`Setting up ${this.plugins.length} plugin(s)`);\n\n for (const plugin of this.plugins) {\n await this.callPluginMethod(plugin, \"setup\");\n }\n }\n\n this.isPluginInitialized = true;\n\n if (!this.production) {\n this.log.info(\"Dev mode: on-demand build active, skipping build pipeline\");\n return;\n }\n\n // Load initial entry points\n for (const entryFile of this.entryPoints) {\n const exists = this.findMetadata({ id: entryFile });\n if (exists) continue;\n\n const metadata = await this.load(entryFile);\n if (!metadata) {\n this.log.error(`Could not load \"${entryFile}\".`);\n return;\n }\n\n this.addMetadata(metadata);\n }\n\n // Resolve & Load\n this.log.info(`Resolving ${this.metadataList.length} entry point(s)`);\n await this.resolveAndLoad(this.metadataList);\n\n // Transform\n this.log.info(`Transforming ${this.metadataList.length} file(s)`);\n\n for (const plugin of this.plugins) {\n await this.callPluginMethod(plugin, \"preTransform\");\n }\n\n await this.transform(this.metadataList);\n\n for (const plugin of this.plugins) {\n await this.callPluginMethod(plugin, \"postTransform\");\n }\n\n // Write\n this.log.info(`Writing ${this.metadataList.length} output file(s)`);\n await this.writeFiles();\n\n // Post Build\n this.log.info(\"Finalizing\");\n for (const plugin of this.plugins) {\n await this.callPluginMethod(plugin, \"postBuild\");\n }\n\n this.log.info(\"Build complete\");\n\n if (this.measureExecutionTime) {\n printExecutionTime(this.executionTime);\n }\n }\n\n /**\n * Stops watching and lets every plugin release what its `setup` took, in reverse order. A teardown that throws is reported and\n * the rest still run. Closing again does nothing.\n */\n async close() {\n if (this.isClosed) return;\n this.isClosed = true;\n\n await this.watcher?.close();\n this.watcher = undefined;\n\n for (const plugin of this.plugins.toReversed()) {\n if (plugin.teardown !== emptyFunction) {\n try {\n await this.callPluginMethod(plugin, \"teardown\");\n } catch (error) {\n this.log.error(`[${plugin.name}] Teardown failed:`);\n console.error(error);\n }\n }\n }\n }\n\n async process(id: string): Promise<boolean> {\n const metadata = await this.load(id);\n if (!metadata) {\n this.log.error(`Could not load \"${id}\".`);\n return false;\n }\n\n const metadataList = await this.resolveAndLoad(metadata);\n\n // Snapshot\n const previouslyTransformed = new Set(this.metadataList);\n\n // Merge\n this.addMetadata(metadataList);\n\n // Ready\n for (const plugin of this.plugins) {\n await this.callPluginMethod(plugin, \"preTransform\");\n }\n\n // Transform only newly added metadata\n for (const plugin of this.plugins) {\n if (plugin.transform === emptyFunction) continue;\n for (const metadataItem of this.metadataList) {\n if (!previouslyTransformed.has(metadataItem)) {\n await this.callPluginMethod(plugin, \"transform\", metadataItem);\n }\n }\n }\n\n // Pre-write\n for (const plugin of this.plugins) {\n await this.callPluginMethod(plugin, \"postTransform\");\n }\n\n return true;\n }\n\n async resolve(metadata: MetadataBase): Promise<Set<string>> {\n if (!this.isPluginInitialized) {\n this.log.warn(\"[resolve] Plugins are not fully setup yet.\");\n }\n\n const discoveredSet = new Set<string>();\n\n const sources = await this.requestSources(metadata);\n\n for (const sourceReference of sources) {\n let dependencyID: string | undefined;\n\n for (const plugin of this.plugins) {\n if (plugin.resolveSource === emptyFunction) continue;\n const resolved = await this.callPluginMethod(\n plugin,\n \"resolveSource\",\n sourceReference.source,\n metadata.filePath,\n metadata\n );\n if (!resolved) continue;\n\n sourceReference.source = resolved.source;\n dependencyID = resolved.dependencyID;\n\n if (dependencyID) {\n discoveredSet.add(dependencyID);\n this.watcher?.add(dependencyID);\n }\n\n break; // first plugin that resolves wins, skip remaining plugins\n }\n\n // After resolution is settled, let plugins transform the source\n for (const plugin of this.plugins) {\n if (plugin.transformSource === emptyFunction) continue;\n const transformed = await this.callPluginMethod(\n plugin,\n \"transformSource\",\n sourceReference.source,\n metadata.filePath,\n metadata,\n dependencyID\n );\n if (!transformed) continue;\n\n sourceReference.source = transformed;\n break; // same first-wins convention\n }\n }\n\n return discoveredSet;\n }\n\n /**\n * Resolve and load recursively\n *\n * 1. Resolves given metadata item or list\n * 2. Loads discovered dependencies if not already loaded skipping entry points\n * 3. Returns metadata list\n */\n async resolveAndLoad(metadataItemOrList: MetadataBase | MetadataBase[]) {\n const metadataList = Array.isArray(metadataItemOrList) ? metadataItemOrList : [metadataItemOrList];\n\n for (const metadataItem of metadataList) {\n const discovered = await this.resolve(metadataItem);\n\n for (const discoveredID of discovered) {\n if (discoveredID === metadataItem.id || this.entryPoints.has(discoveredID)) continue;\n\n metadataItem.directDependencies.add(discoveredID);\n\n const exists = this.findMetadata({ id: discoveredID }) ?? metadataList.find(m => m.id === discoveredID);\n if (exists) continue;\n\n const loadedMetadata = await this.load(discoveredID);\n if (!loadedMetadata) continue;\n\n // eslint-disable-next-line unicorn/no-loop-iterable-mutation -- It's intentional\n metadataList.push(loadedMetadata);\n }\n }\n\n return metadataList;\n }\n\n async transform(metadataItemOrList: MetadataBase | MetadataBase[]) {\n if (!this.isPluginInitialized) {\n this.log.warn(\"[transform] Plugins are not fully setup yet.\");\n }\n\n const metadataList = Array.isArray(metadataItemOrList) ? metadataItemOrList : [metadataItemOrList];\n\n for (const plugin of this.plugins) {\n if (plugin.transform === emptyFunction) continue;\n for (const metadata of metadataList) {\n await this.callPluginMethod(plugin, \"transform\", metadata);\n }\n }\n }\n\n async transformAndSync(metadataItemOrList: MetadataBase | MetadataBase[]) {\n if (!this.isPluginInitialized) {\n this.log.warn(\"[transformAndSync] Plugins are not fully setup yet.\");\n }\n\n if (this.pluginIndex < 0) {\n this.log.error(`[transformAndSync] Plugin index is not set.`);\n return;\n }\n\n if (!Object.hasOwn(this.plugins, this.pluginIndex)) {\n this.log.error(`[transformAndSync] Plugin with index \"${this.pluginIndex}\" does not exist.`);\n return;\n }\n\n const metadataList = Array.isArray(metadataItemOrList) ? metadataItemOrList : [metadataItemOrList];\n\n for (let index = 0; index <= this.pluginIndex; index++) {\n const plugin = this.plugins[index];\n if (plugin.transform === emptyFunction) continue;\n\n for (const metadata of metadataList) {\n await this.callPluginMethod(plugin, \"transform\", metadata);\n }\n }\n }\n\n async rebase(metadata: MetadataBase, newAbsolutePath: string) {\n if (!this.isPluginInitialized) {\n this.log.warn(\"[rebase] Plugins are not fully setup yet.\");\n }\n\n const oldAbsolutePath = join(this.root, metadata.filePath);\n if (oldAbsolutePath === newAbsolutePath) return;\n\n const sources = await this.requestSources(metadata);\n\n for (const sourceReference of sources) {\n for (const plugin of this.plugins) {\n if (plugin.rebaseSource === emptyFunction) continue;\n const rebased = await this.callPluginMethod(\n plugin,\n \"rebaseSource\",\n sourceReference.source,\n metadata.filePath,\n newAbsolutePath\n );\n\n if (rebased !== undefined) {\n sourceReference.source = rebased;\n break;\n }\n }\n }\n\n for (const plugin of this.plugins) {\n if (plugin.onMetadataRebase === emptyFunction) continue;\n await this.callPluginMethod(plugin, \"onMetadataRebase\", metadata, oldAbsolutePath, newAbsolutePath);\n }\n }\n\n async writeFiles() {\n if (!this.isPluginInitialized) {\n this.log.warn(\"[emit] Plugins are not fully setup yet.\");\n }\n\n for (const plugin of this.plugins) {\n if (plugin.write === emptyFunction) continue;\n await this.callPluginMethod(plugin, \"write\");\n }\n }\n\n async read(filePath: string) {\n filePath = normalize(filePath);\n\n if (!isAbsolute(filePath)) {\n filePath = join(this.root, filePath);\n }\n\n for (const plugin of this.plugins) {\n if (plugin.read === emptyFunction) continue;\n const content = await this.callPluginMethod(plugin, \"read\", filePath);\n if (content !== undefined) return content;\n }\n }\n\n async load(relativePath: string, options: { code?: string; type?: string } = {}) {\n // Try to find the exact file to load\n // In some cases a path like ./sources/index.js does not exist, but ./sources/index.ts does\n const resolved = this.resolver.resolve(basename(relativePath), relativePath);\n if (resolved) {\n relativePath = relative(this.root, resolved.path);\n }\n\n relativePath = normalize(relativePath);\n\n const content = options.code ?? (await this.read(relativePath));\n if (!content) return;\n\n for (const plugin of this.plugins) {\n if (plugin.load === emptyFunction) continue;\n const metadata = await this.callPluginMethod(plugin, \"load\", content, relativePath, { type: options.type });\n\n // Don't load\n if (metadata === null) break;\n\n if (metadata) {\n return metadata;\n }\n }\n }\n\n async requestSources(metadata: MetadataBase) {\n if (!this.isPluginInitialized) {\n this.log.warn(\"[requestSources] Plugins are not fully setup yet.\");\n }\n\n const result: MetadataSource[] = [];\n\n for (const plugin of this.plugins) {\n if (plugin.sourcesProvider === emptyFunction) continue;\n const sources = await this.callPluginMethod(plugin, \"sourcesProvider\", metadata);\n if (sources) result.push(...sources);\n }\n\n return result;\n }\n\n async stringify(metadata: MetadataBase, options: StringifyOptions = {}): Promise<string> {\n if (!this.isPluginInitialized) {\n this.log.warn(\"[stringify] Plugins are not fully setup yet.\");\n }\n\n for (const plugin of this.plugins) {\n if (plugin.stringify === emptyFunction) continue;\n const string = await this.callPluginMethod(plugin, \"stringify\", metadata, options);\n if (typeof string === \"string\") {\n return string;\n }\n }\n\n this.log.fatal(`Failed to stringify metadata: ${metadata.id}`);\n return \"\";\n }\n\n async getCompileList(event: \"change\" | \"add\" | \"unlink\", filePath: string) {\n filePath = normalize(filePath);\n\n const compileSet = new Set<string>([filePath]);\n\n for (const plugin of this.plugins) {\n if (plugin.resolveCompileList === emptyFunction) continue;\n await this.callPluginMethod(plugin, \"resolveCompileList\", compileSet, event, filePath);\n }\n\n return compileSet;\n }\n\n async handleRequest(requestPath: string, reply: ServerReply, request: ServerRequest) {\n for (const plugin of this.plugins) {\n if (plugin.handleRequest === emptyFunction) continue;\n const serve = await this.callPluginMethod(plugin, \"handleRequest\", requestPath, reply, request);\n if (serve) return serve;\n }\n }\n\n async resolveRequestPath(requestPath: string) {\n for (const plugin of this.plugins) {\n if (plugin.resolveRequestPath === emptyFunction) continue;\n const resolvedPath = await this.callPluginMethod(plugin, \"resolveRequestPath\", requestPath);\n if (resolvedPath) {\n requestPath = resolvedPath;\n }\n }\n\n return requestPath;\n }\n\n clone<T extends MetadataBase>(metadata: T): T {\n for (const plugin of this.plugins) {\n if (plugin.clone === emptyFunction) continue;\n const clone = this.callPluginMethod(plugin, \"clone\", metadata);\n if (clone) {\n return clone as T;\n }\n }\n\n this.log.fatal(`Failed to stringify metadata: ${metadata.id}`);\n\n return metadata;\n }\n\n addMetadata(itemOrList: MetadataBase | MetadataBase[]) {\n const items = Array.isArray(itemOrList) ? itemOrList : [itemOrList];\n\n for (const item of items) {\n this.metadataList.push(item);\n }\n }\n\n removeMetadata(metadataOrIndex: MetadataBase | MetadataBase[] | number) {\n if (typeof metadataOrIndex === \"number\") {\n if (metadataOrIndex === -1) return;\n\n this.metadataList.splice(metadataOrIndex, 1);\n return;\n }\n\n const items = Array.isArray(metadataOrIndex) ? metadataOrIndex : [metadataOrIndex];\n\n for (const item of items) {\n const index = this.metadataList.indexOf(item);\n if (index === -1) continue;\n\n this.metadataList.splice(index, 1);\n }\n }\n\n findMetadata<T extends MetadataBase>(metadataFilter: Partial<T>) {\n const filterEntries = Object.entries(metadataFilter);\n\n for (const metadata of this.metadataList) {\n // Match by reference\n if (metadata === metadataFilter) {\n return metadata as T;\n }\n\n let isMatch = true;\n\n for (const [key, value] of filterEntries) {\n if ((metadata as unknown as Record<string, unknown>)[key] !== value) {\n isMatch = false;\n break;\n }\n }\n\n if (isMatch) {\n return metadata as T;\n }\n }\n }\n\n filterMetadata<T extends MetadataBase>(metadataFilter: Partial<T>) {\n const filterEntries = Object.entries(metadataFilter);\n\n return this.metadataList.filter(metadata => {\n // Match by reference\n if (metadata === metadataFilter) {\n return true;\n }\n\n for (const [key, value] of filterEntries) {\n if ((metadata as unknown as Record<string, unknown>)[key] !== value) {\n return false;\n }\n }\n\n return true;\n }) as T[];\n }\n}\n","import chalk from \"chalk\";\nimport * as z from \"zod\";\n\nimport { App } from \"../../../main.ts\";\nimport { Log } from \"../../../utilities/logger.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface BuildCliPluginOptions {\n /**\n * Build command name.\n *\n * @default \"build\"\n */\n command?: string;\n\n /**\n * Build command aliases.\n *\n * @default [\"b\"]\n */\n aliases?: string[];\n}\n\n/**\n * Adds the \"build\" command (aliased \"b\"): runs the pipeline once in production mode and reports how long it took.\n *\n * Notes:\n *\n * - The command owns the run. It forces production mode onto the config and creates its own App.\n * - \"--measure\" turns on per-plugin hook timing and prints the report when the build finishes.\n */\nexport function buildCliPlugin(options: BuildCliPluginOptions = {}): Plugin {\n const name = options.command ?? \"build\";\n const aliases = options.aliases ?? [\"b\"];\n\n return {\n name: \"build-cli-plugin\",\n\n cli(config, configPath) {\n const buildCommand = this.defineSubcommand({\n name,\n aliases,\n meta: { description: \"Build static website command.\" },\n\n options: {\n measure: {\n schema: z.boolean().optional(),\n coerce: this.coerce.boolean,\n meta: {\n description: \"Measure per-plugin hook execution time and print a report after the build.\",\n },\n },\n },\n });\n\n buildCommand.onExecute(async ({ options: cliOptions }) => {\n const startTime = performance.now();\n\n config.production = true;\n config.measureExecutionTime = cliOptions.measure ?? config.measureExecutionTime;\n\n const app = new App(config, configPath);\n await app.run();\n\n Log.info(`Built in ${chalk.bold.green(Math.round(performance.now() - startTime) / 1000)} seconds.`);\n });\n\n this.addCommand(buildCommand);\n },\n };\n}\n","import { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { globSync } from \"glob\";\nimport * as z from \"zod\";\n\nimport { Log } from \"../../../utilities/logger.ts\";\nimport { basename, join, replaceExtension } from \"../../../utilities/path.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface ConvertFontsCliPluginOptions {\n /**\n * The name of the command.\n *\n * @default \"convert-fonts\"\n */\n command?: string;\n\n /**\n * The aliases of the command.\n *\n * @default [\"woff2\"]\n */\n aliases?: string[];\n\n /**\n * The default value of the `--fonts` option.\n *\n * A glob pattern to match font files.\n */\n fonts?: string;\n\n /**\n * The default value of the `--exclude` option.\n *\n * A glob patterns to exclude input files.\n */\n exclude?: string;\n\n /**\n * The default value of the `--out-dir` option.\n *\n * Where to save the output files.\n */\n outDir?: string;\n}\n\n/**\n * Adds the \"convert-fonts\" command (aliased \"woff2\"): converts the TTF files matched by \"--fonts\" to WOFF2.\n *\n * Notes:\n *\n * - The options given here become the defaults of the matching flags; a flag left without one has to be passed on the command line.\n * - Every font lands directly in \"--out-dir\" under its own name, so the source directory structure is flattened and fonts that\n * share a name overwrite each other.\n */\nexport function convertFontsCliPlugin(options: ConvertFontsCliPluginOptions = {}): Plugin {\n const name = options.command ?? \"convert-fonts\";\n const aliases = options.aliases ?? [\"woff2\"];\n\n return {\n name: \"convert-fonts-cli-plugin\",\n\n cli(config) {\n const convertFontsCommand = this.defineSubcommand({\n name,\n aliases,\n meta: { description: \"Convert TTF fonts to WOFF2 format.\" },\n\n options: {\n fonts: {\n schema: options.fonts ? z.string().default(options.fonts) : z.string(),\n meta: {\n placeholder: \"<pattern>\",\n description: \"A glob pattern to match font files.\",\n },\n },\n exclude: {\n schema: options.exclude ? z.string().default(options.exclude) : z.string().optional(),\n meta: {\n placeholder: \"<pattern>\",\n description: \"A glob patterns to exclude input files.\",\n },\n },\n outDir: {\n aliases: [\"o\"],\n schema: options.outDir ? z.string().default(options.outDir) : z.string(),\n meta: {\n placeholder: \"<path>\",\n description: \"Where to save the output files.\",\n },\n },\n },\n });\n\n convertFontsCommand.onExecute(async ({ options }) => {\n const { default: ttf2woff2 } = await import(\"ttf2woff2\");\n const fontFiles = globSync(options.fonts, { ignore: options.exclude, cwd: config.root });\n\n for (const inputPath of fontFiles) {\n Log.info(`Converting ${inputPath}...`);\n\n const inputBuffer = readFileSync(inputPath);\n const outputBuffer = ttf2woff2(inputBuffer);\n\n mkdirSync(options.outDir, { recursive: true });\n\n const fileName = replaceExtension(basename(inputPath), \".woff2\");\n const outputPath = join(options.outDir, fileName);\n\n writeFileSync(outputPath, outputBuffer);\n }\n });\n\n this.addCommand(convertFontsCommand);\n },\n };\n}\n","import { readFileSync } from \"node:fs\";\nimport * as fontKit from \"fontkit\";\n\nimport { relative, dirname, basename } from \"../../../utilities/path.ts\";\n\ninterface FontFaceOptions {\n /** Absolute or relative path to the font file (.ttf, .otf, .woff, .woff2) */\n fontPath: string;\n\n /** Absolute or relative path to the CSS file that will contain the @font-face rule */\n cssOutputPath: string;\n\n /**\n * Override font-display value\n *\n * @default \"swap\"\n */\n fontDisplay?: \"auto\" | \"block\" | \"swap\" | \"fallback\" | \"optional\";\n\n /** Override the font-family name instead of using the one extracted from the file */\n familyOverride?: string;\n}\n\ninterface FontFaceMeta {\n family: string;\n weight: string | number;\n style: \"normal\" | \"italic\" | \"oblique\";\n format: string;\n relativeSource: string;\n}\n\n// Only 400 and 700 have named CSS keywords; all other usWeightClass values\n// are emitted as plain numbers, which is valid CSS (e.g. font-weight: 300)\nconst WEIGHT_KEYWORDS: Partial<Record<number, string>> = {\n 400: \"normal\",\n 700: \"bold\",\n};\n\nfunction resolveWeight(usWeightClass: number): string | number {\n return WEIGHT_KEYWORDS[usWeightClass] ?? usWeightClass;\n}\n\nconst FORMAT_MAP: Record<string, string> = {\n ttf: \"truetype\",\n otf: \"opentype\",\n woff: \"woff\",\n woff2: \"woff2\",\n eot: \"embedded-opentype\",\n svg: \"svg\",\n};\n\nfunction detectFormat(fontPath: string): string {\n const extension = basename(fontPath).split(\".\").pop()?.toLowerCase() ?? \"\";\n return FORMAT_MAP[extension] ?? extension;\n}\n\nfunction resolveStyle(\n fsSelection: fontKit.Os2Table[\"fsSelection\"],\n macStyle: { italic?: boolean } | undefined\n): FontFaceMeta[\"style\"] {\n // fsSelection (OS/2 table) is the canonical source per the OpenType spec\n if (fsSelection.oblique) {\n return \"oblique\";\n }\n\n if (fsSelection.italic) {\n return \"italic\";\n }\n\n // macStyle (head table) as a fallback for older/legacy fonts\n if (macStyle?.italic) {\n return \"italic\";\n }\n\n return \"normal\";\n}\n\nfunction getPreferredFamilyName(font: fontKit.Font): string {\n return font.getName(\"preferredFamily\", \"en\") ?? font.getName(\"preferredFamily\", \"\") ?? font.familyName;\n}\n/**\n * Reads a font file, extracts metadata from its binary tables, and returns a ready-to-use CSS @font-face rule string plus a\n * structured metadata object.\n */\nexport function generateFontFace(options: FontFaceOptions) {\n const { fontPath, cssOutputPath, fontDisplay = \"swap\", familyOverride } = options;\n\n const buffer = readFileSync(fontPath);\n const font = fontKit.create(buffer) as fontKit.Font;\n\n // Extract metadata\n const family = familyOverride ?? getPreferredFamilyName(font);\n const os2 = font[\"OS/2\"];\n const weight = resolveWeight(os2.usWeightClass);\n\n // head.macStyle is not exposed in @types/fontkit so we cast carefully\n const headTable = (font as unknown as Record<string, unknown>)[\"head\"] as { macStyle?: { italic?: boolean } } | undefined;\n\n const style = resolveStyle(os2.fsSelection, headTable?.macStyle);\n const format = detectFormat(fontPath);\n\n const relativeSource = relative(dirname(cssOutputPath), fontPath);\n\n const css = [\n `@font-face {`,\n ` font-family: ${family.includes(\" \") ? `\"${family}\"` : family};`,\n ` font-style: ${style};`,\n ` font-weight: ${weight};`,\n ` src: url(\"${relativeSource}\") format(\"${format}\");`,\n ` font-display: ${fontDisplay};`,\n `}`,\n ].join(\"\\n\");\n\n return css;\n}\n","import { writeFileSync } from \"node:fs\";\nimport { globSync } from \"glob\";\nimport * as z from \"zod\";\n\nimport { Log } from \"../../../utilities/logger.ts\";\nimport { generateFontFace } from \"./generate-font-face.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface GenerateFontFacesCliPluginOptions {\n /**\n * The name of the command.\n *\n * @default \"fontface\"\n */\n command?: string;\n\n /**\n * The aliases of the command.\n *\n * @default [\"font\"]\n */\n aliases?: string[];\n\n /**\n * The default value of the `fonts` option.\n *\n * A glob pattern to match font files.\n */\n fonts?: string;\n\n /**\n * The default value of the `exclude` option.\n *\n * A glob patterns to exclude input files.\n */\n exclude?: string;\n\n /**\n * The default value of the `cssOut` option.\n *\n * Where to save the output CSS file.\n */\n cssOut?: string;\n\n /**\n * The default value of the `fontDisplay` option.\n *\n * @default \"swap\"\n */\n fontDisplay?: \"auto\" | \"block\" | \"swap\" | \"fallback\" | \"optional\";\n}\n\n/**\n * Adds the \"fontface\" command (aliased \"font\"): writes one stylesheet of \"@font-face\" rules for the fonts matched by \"--fonts\".\n *\n * Notes:\n *\n * - Family, weight and style are read from the font's own tables, not from its file name, and the format comes from the extension.\n * - The \"src\" path of each rule is written relative to \"--css-out\", and the file is overwritten as a whole on every run.\n * - The options given here become the defaults of the matching flags; \"--font-display\" falls back to \"swap\".\n * - Matching no font at all is reported and nothing is written.\n */\nexport function generateFontFacesCliPlugin(options: GenerateFontFacesCliPluginOptions = {}): Plugin {\n const name = options.command ?? \"fontface\";\n const aliases = options.aliases ?? [\"font\"];\n\n return {\n name: \"generate-font-faces-cli-plugin\",\n cli(config) {\n const fontFaceCommand = this.defineSubcommand({\n name,\n aliases,\n meta: {\n description: \"Generate @font-face rules for all fonts and save it to css file.\",\n },\n\n options: {\n fonts: {\n schema: options.fonts ? z.string().default(options.fonts) : z.string(),\n meta: {\n placeholder: \"<pattern>\",\n description: \"A glob pattern to match font files.\",\n },\n },\n exclude: {\n schema: options.exclude ? z.string().default(options.exclude) : z.string().optional(),\n meta: {\n placeholder: \"<pattern>\",\n description: \"A glob patterns to exclude input files.\",\n },\n },\n cssOut: {\n aliases: [\"o\"],\n schema: options.cssOut ? z.string().default(options.cssOut) : z.string(),\n meta: {\n placeholder: \"<path>\",\n description: \"Where to save the output CSS file.\",\n },\n },\n fontDisplay: {\n schema: z\n .union([z.literal(\"auto\"), z.literal(\"block\"), z.literal(\"swap\"), z.literal(\"fallback\"), z.literal(\"optional\")])\n .default(options.fontDisplay ?? \"swap\"),\n meta: {\n placeholder: \"<auto|block|swap|fallback|optional>\",\n description: \"The font display property.\",\n },\n },\n },\n });\n\n fontFaceCommand.onExecute(({ options }) => {\n const fontFiles = globSync(options.fonts, { ignore: options.exclude, cwd: config.root });\n\n if (fontFiles.length === 0) {\n Log.error(\"No font files found.\");\n return;\n }\n\n const cssResults: string[] = [];\n\n for (const fontPath of fontFiles) {\n const fontFace = generateFontFace({\n fontPath,\n cssOutputPath: options.cssOut,\n fontDisplay: options.fontDisplay,\n });\n\n cssResults.push(fontFace);\n }\n\n writeFileSync(options.cssOut, cssResults.join(\"\\n\\n\"));\n\n Log.success(`Generated ${options.cssOut}`);\n });\n\n this.addCommand(fontFaceCommand);\n },\n };\n}\n","const Color = {\n TRANSPARENT: 0,\n\n clampRGB: (value: number) => Color.clamp(Math.round(value), 0, 255),\n clamp: (value: number, min: number, max: number) => Math.max(min, Math.min(value, max)),\n\n // prettier-ignore\n red: (color: number) => (color >> 16) & 0xFF,\n\n green: (color: number) => (color >> 8) & 0xff,\n\n blue: (color: number) => color & 0xff,\n\n rgb(red: number, green: number, blue: number) {\n red = Color.clampRGB(red);\n green = Color.clampRGB(green);\n blue = Color.clampRGB(blue);\n\n return 0xff_00_00_00 | (red << 16) | (green << 8) | blue;\n },\n};\n\nexport default Color;\n","import { Cam } from \"../cam/cam.ts\";\nimport Color from \"./color.ts\";\n\nconst ColorUtilities = {\n XYZ_WHITE_REFERENCE_X: 95.047,\n XYZ_WHITE_REFERENCE_Y: 100,\n XYZ_WHITE_REFERENCE_Z: 108.883,\n\n constrain(amount: number, low: number, high: number) {\n return amount < low ? low : Math.min(amount, high);\n },\n\n /**\n * Converts a color from CIE XYZ to its RGB representation.\n *\n * This method expects the XYZ representation to use the D65 illuminant and the CIE 2° Standard Observer (1931).\n *\n * @param x X component value [0...95.047)\n * @param y Y component value [0...100)\n * @param z Z component value [0...108.883)\n * @returns Int containing the RGB representation\n */\n XYZToColor(x: number, y: number, z: number) {\n x = Color.clamp(x, 0, ColorUtilities.XYZ_WHITE_REFERENCE_X);\n y = Color.clamp(y, 0, ColorUtilities.XYZ_WHITE_REFERENCE_Y);\n z = Color.clamp(z, 0, ColorUtilities.XYZ_WHITE_REFERENCE_Z);\n\n let r = (x * 3.2406 + y * -1.5372 + z * -0.4986) / 100;\n let g = (x * -0.9689 + y * 1.8758 + z * 0.0415) / 100;\n let b = (x * 0.0557 + y * -0.204 + z * 1.057) / 100;\n\n r = r > 0.0031308 ? 1.055 * Math.pow(r, 1 / 2.4) - 0.055 : 12.92 * r;\n g = g > 0.0031308 ? 1.055 * Math.pow(g, 1 / 2.4) - 0.055 : 12.92 * g;\n b = b > 0.0031308 ? 1.055 * Math.pow(b, 1 / 2.4) - 0.055 : 12.92 * b;\n\n return Color.rgb(\n ColorUtilities.constrain(Math.round(r * 255), 0, 255),\n ColorUtilities.constrain(Math.round(g * 255), 0, 255),\n ColorUtilities.constrain(Math.round(b * 255), 0, 255)\n );\n },\n\n /**\n * Convert a color appearance model representation to an ARGB color.\n *\n * Note: the returned color may have a lower chroma than requested. Whether a chroma is available depends on luminance. For\n * example, there's no such thing as a high chroma light red, due to the limitations of our eyes and/or physics. If the\n * requested chroma is unavailable, the highest possible chroma at the requested luminance is returned.\n *\n * @param hue Hue, in degrees, in CAM coordinates\n * @param chroma Chroma in CAM coordinates.\n * @param lstar Perceptual luminance, L* in L_a_b*\n */\n CAMToColor(hue: number, chroma: number, lstar: number) {\n return Cam.getInt(hue, chroma, lstar);\n },\n};\n\nexport default ColorUtilities;\n","const MathUtilities = {\n lerp(start: number, stop: number, amount: number) {\n return start + (stop - start) * amount;\n },\n\n toRadians(degrees: number) {\n return degrees * (Math.PI / 180);\n },\n};\n\nexport default MathUtilities;\n","/*\n * This code was originally written in Java and has been converted to JavaScript.\n *\n * Original Java code source: [https://android.googlesource.com/platform/frameworks/base/+/refs/heads/main/core/java/com/android/internal/graphics/cam]\n *\n * Copyright (C) 2021 The Android Open Source Project.\n * The original code is licensed under the Apache License, Version 2.0.\n *\n * This JavaScript version is licensed under the MIT License.\n *\n * See the respective licenses for the specific terms, permissions, and limitations.\n */\nimport MathUtilities from \"../utils/math-utilities.ts\";\nimport { CamUtilities, Frame } from \"./cam.ts\";\n\n// eslint-disable-next-line unicorn/no-static-only-class\nexport default class HctSolver {\n /** Weights for transforming a set of linear RGB coordinates to Y in XYZ. */\n static Y_FROM_LINRGB: [number, number, number] = [0.2126, 0.7152, 0.0722];\n\n // Matrix used when converting from CAM16 to linear RGB.\n static LINRGB_FROM_SCALED_DISCOUNT: [[number, number, number], [number, number, number], [number, number, number]] = [\n [1373.2198709594231, -1100.4251190754821, -7.278681089101213],\n [-271.815969077903, 559.6580465940733, -32.46047482791194],\n [1.9622899599665666, -57.173814538844006, 308.7233197812385],\n ];\n\n /** Matrix used when converting from linear RGB to CAM16. */\n static SCALED_DISCOUNT_FROM_LINRGB: [[number, number, number], [number, number, number], [number, number, number]] = [\n [0.001200833568784504, 0.002389694492170889, 0.0002795742885861124],\n [0.0005891086651375999, 0.0029785502573438758, 0.0003270666104008398],\n [0.00010146692491640572, 0.0005364214359186694, 0.0032979401770712076],\n ];\n\n /**\n * Lookup table for plane in XYZ's Y axis (relative luminance) that corresponds to a given L* in L_a_b*. HCT's T is L*, and\n * XYZ's Y is directly correlated to linear RGB, this table allows us to thus find the intersection between HCT and RGB, giving\n * a solution to the RGB coordinates that correspond to a given set of HCT coordinates.\n */\n static CRITICAL_PLANES = [\n 0.015176349177441876, 0.045529047532325624, 0.07588174588720938, 0.10623444424209313, 0.13658714259697685,\n 0.16693984095186062, 0.19729253930674434, 0.2276452376616281, 0.2579979360165119, 0.28835063437139563, 0.3188300904430532,\n 0.350925934958123, 0.3848314933096426, 0.42057480301049466, 0.458183274052838, 0.4976837250274023, 0.5391024159806381,\n 0.5824650784040898, 0.6277969426914107, 0.6751227633498623, 0.7244668422128921, 0.775853049866786, 0.829304845476233,\n 0.8848452951698498, 0.942497089126609, 1.0022825574869039, 1.0642236851973577, 1.1283421258858297, 1.1946592148522128,\n 1.2631959812511864, 1.3339731595349034, 1.407011200216447, 1.4823302800086415, 1.5599503113873272, 1.6398909516233677,\n 1.7221716113234105, 1.8068114625156377, 1.8938294463134073, 1.9832442801866852, 2.075074464868551, 2.1693382909216234,\n 2.2660538449872063, 2.36523901573795, 2.4669114995532007, 2.5710888059345764, 2.6777882626779785, 2.7870270208169257,\n 2.898822059350997, 3.0131901897720907, 3.1301480604002863, 3.2497121605402226, 3.3718988244681087, 3.4967242352587946,\n 3.624204428461639, 3.754355295633311, 3.887192587735158, 4.022731918402185, 4.160988767090289, 4.301978482107941,\n 4.445716283538092, 4.592217266055746, 4.741496401646282, 4.893568542229298, 5.048448422192488, 5.20615066083972,\n 5.3666897647573375, 5.5300801301023865, 5.696336044816294, 5.865471690767354, 6.037501145825082, 6.212438385869475,\n 6.390297286737924, 6.571091626112461, 6.7548350853498045, 6.941541251256611, 7.131223617812143, 7.323895587840543,\n 7.5195704746346665, 7.7182615035334345, 7.919981813454504, 8.124744458384042, 8.332562408825165, 8.543448553206703,\n 8.757415699253682, 8.974476575321063, 9.194643831691977, 9.417930041841839, 9.644347703669503, 9.873909240696694,\n 10.106627003236781, 10.342513269534024, 10.58158024687427, 10.8238400726681, 11.069304815507364, 11.317986476196008,\n 11.569896988756009, 11.825048221409341, 12.083451977536606, 12.345119996613247, 12.610063955123938, 12.878295467455942,\n 13.149826086772048, 13.42466730586372, 13.702830557985108, 13.984327217668513, 14.269168601521828, 14.55736596900856,\n 14.848930523210871, 15.143873411576273, 15.44220572664832, 15.743938506781891, 16.04908273684337, 16.35764934889634,\n 16.66964922287304, 16.985093187232053, 17.30399201960269, 17.62635644741625, 17.95219714852476, 18.281524751807332,\n 18.614349837764564, 18.95068293910138, 19.290534541298456, 19.633915083172692, 19.98083495742689, 20.331304511189067,\n 20.685334046541502, 21.042933821039977, 21.404114048223256, 21.76888489811322, 22.137256497705877, 22.50923893145328,\n 22.884842241736916, 23.264076429332462, 23.6469514538663, 24.033477234264016, 24.42366364919083, 24.817520537484558,\n 25.21505769858089, 25.61628489293138, 26.021211842414342, 26.429848230738664, 26.842203703840827, 27.258287870275353,\n 27.678110301598522, 28.10168053274597, 28.529008062403893, 28.96010235337422, 29.39497283293396, 29.83362889318845,\n 30.276079891419332, 30.722335150426627, 31.172403958865512, 31.62629557157785, 32.08401920991837, 32.54558406207592,\n 33.010999283389665, 33.4802739966603, 33.953417292456834, 34.430438229418264, 34.911345834551085, 35.39614910352207,\n 35.88485700094671, 36.37747846067349, 36.87402238606382, 37.37449765026789, 37.87891309649659, 38.38727753828926,\n 38.89959975977785, 39.41588851594697, 39.93615253289054, 40.460400508064545, 40.98864111053629, 41.520882981230194,\n 42.05713473317016, 42.597404951718396, 43.141702194811224, 43.6900349931913, 44.24241185063697, 44.798841244188324,\n 45.35933162437017, 45.92389141541209, 46.49252901546552, 47.065252796817916, 47.64207110610409, 48.22299226451468,\n 48.808024568002054, 49.3971762874833, 49.9904556690408, 50.587870934119984, 51.189430279724725, 51.79514187861014,\n 52.40501387947288, 53.0190544071392, 53.637271562750364, 54.259673423945976, 54.88626804504493, 55.517063457223934,\n 56.15206766869424, 56.79128866487574, 57.43473440856916, 58.08241284012621, 58.734331877617365, 59.39049941699807,\n 60.05092333227251, 60.715611475655585, 61.38457167773311, 62.057811747619894, 62.7353394731159, 63.417162620860914,\n 64.10328893648692, 64.79372614476921, 65.48848194977529, 66.18756403501224, 66.89098006357258, 67.59873767827808,\n 68.31084450182222, 69.02730813691093, 69.74813616640164, 70.47333615344107, 71.20291564160104, 71.93688215501312,\n 72.67524319850172, 73.41800625771542, 74.16517879925733, 74.9167682708136, 75.67278210128072, 76.43322770089146,\n 77.1981124613393, 77.96744375590167, 78.74122893956174, 79.51947534912904, 80.30219030335869, 81.08938110306934,\n 81.88105503125999, 82.67721935322541, 83.4778813166706, 84.28304815182372, 85.09272707154808, 85.90692527145302,\n 86.72564993000343, 87.54890820862819, 88.3767072518277, 89.2090541872801, 90.04595612594655, 90.88742016217518,\n 91.73345337380438, 92.58406282226491, 93.43925555268066, 94.29903859396902, 95.16341895893969, 96.03240364439274,\n 96.9059996312159, 97.78421388448044, 98.6670533535366, 99.55452497210776,\n ];\n\n /**\n * Sanitizes a degree measure as a floating-point number.\n *\n * @returns A degree measure between 0.0 (inclusive) and 360.0 (exclusive).\n */\n static sanitizeDegreesDouble(degrees: number) {\n degrees %= 360;\n if (degrees < 0) {\n degrees += 360;\n }\n return degrees;\n }\n\n /** Equation used in CAM16 conversion that removes the effect of chromatic adaptation. */\n static inverseChromaticAdaptation(adapted: number) {\n const adaptedAbs = Math.abs(adapted);\n const base = Math.max(0, (27.13 * adaptedAbs) / (400 - adaptedAbs));\n\n return CamUtilities.signum(adapted) * Math.pow(base, 1 / 0.42);\n }\n\n /**\n * Finds a color with the given hue, chroma, and Y.\n *\n * @param hueRadians The desired hue in radians.\n * @param chroma The desired chroma.\n * @param y The desired Y.\n * @returns The desired color as a hexadecimal integer, if found; 0 otherwise.\n */\n static findResultByJ(hueRadians: number, chroma: number, y: number) {\n // Initial estimate of j.\n let index = Math.sqrt(y) * 11;\n\n // ===========================================================\n // Operations inlined from Cam16 to avoid repeated calculation\n // ===========================================================\n const viewingConditions = Frame.DEFAULT,\n tInnerCoeff = 1 / Math.pow(1.64 - Math.pow(0.29, viewingConditions.getN()), 0.73),\n ehue = 0.25 * (Math.cos(hueRadians + 2) + 3.8),\n p1 = ehue * (50_000 / 13) * viewingConditions.getNc() * viewingConditions.getNcb(),\n hSin = Math.sin(hueRadians),\n hCos = Math.cos(hueRadians);\n\n for (let iterationRound = 0; iterationRound < 5; iterationRound++) {\n // ===========================================================\n // Operations inlined from Cam16 to avoid repeated calculation\n // ===========================================================\n const indexNormalized = index / 100,\n alpha = chroma === 0 || index === 0 ? 0 : chroma / Math.sqrt(indexNormalized),\n t = Math.pow(alpha * tInnerCoeff, 1 / 0.9),\n acExponent = 1 / viewingConditions.getC() / viewingConditions.getZ(),\n ac = viewingConditions.getAw() * Math.pow(indexNormalized, acExponent),\n p2 = ac / viewingConditions.getNbb(),\n gamma = (23 * (p2 + 0.305) * t) / (23 * p1 + 11 * t * hCos + 108 * t * hSin),\n a = gamma * hCos,\n b = gamma * hSin,\n rA = (460 * p2 + 451 * a + 288 * b) / 1403,\n gA = (460 * p2 - 891 * a - 261 * b) / 1403,\n bA = (460 * p2 - 220 * a - 6300 * b) / 1403,\n rCScaled = this.inverseChromaticAdaptation(rA),\n gCScaled = this.inverseChromaticAdaptation(gA),\n bCScaled = this.inverseChromaticAdaptation(bA),\n matrix = this.LINRGB_FROM_SCALED_DISCOUNT,\n linrgbR = rCScaled * matrix[0][0] + gCScaled * matrix[0][1] + bCScaled * matrix[0][2],\n linrgbG = rCScaled * matrix[1][0] + gCScaled * matrix[1][1] + bCScaled * matrix[1][2],\n linrgbB = rCScaled * matrix[2][0] + gCScaled * matrix[2][1] + bCScaled * matrix[2][2];\n\n // ===========================================================\n // Operations inlined from Cam16 to avoid repeated calculation\n // ===========================================================\n if (linrgbR < 0 || linrgbG < 0 || linrgbB < 0) {\n return 0;\n }\n\n const kR = this.Y_FROM_LINRGB[0],\n kG = this.Y_FROM_LINRGB[1],\n kB = this.Y_FROM_LINRGB[2],\n fnj = kR * linrgbR + kG * linrgbG + kB * linrgbB;\n\n if (fnj <= 0) {\n return 0;\n }\n if (iterationRound === 4 || Math.abs(fnj - y) < 0.002) {\n if (linrgbR > 100.01 || linrgbG > 100.01 || linrgbB > 100.01) {\n return 0;\n }\n return CamUtilities.argbFromLinrgbComponents(linrgbR, linrgbG, linrgbB);\n }\n\n // Iterates with Newton method,\n // Using 2 * fn(j) / j as the approximation of fn'(j)\n index -= ((fnj - y) * index) / (2 * fnj);\n }\n\n return 0;\n }\n\n /**\n * Finds an sRGB color with the given hue, chroma, and L*, if possible.\n *\n * @param hueDegrees The desired hue, in degrees.\n * @param chroma The desired chroma.\n * @param lstar The desired L*.\n * @returns A hexadecimal representing the sRGB color. The color has sufficiently close hue, chroma, and L* to the desired\n * values, if possible; otherwise, the hue and L* will be sufficiently close, and chroma will be maximized.\n */\n static solveToInt(hueDegrees: number, chroma: number, lstar: number) {\n if (chroma < 0.0001 || lstar < 0.0001 || lstar > 99.9999) {\n return CamUtilities.argbFromLstar(lstar);\n }\n\n hueDegrees = this.sanitizeDegreesDouble(hueDegrees);\n const hueRadians = MathUtilities.toRadians(hueDegrees);\n const y = CamUtilities.yFromLstar(lstar);\n\n const exactAnswer = this.findResultByJ(hueRadians, chroma, y);\n\n if (exactAnswer !== 0) {\n return exactAnswer;\n }\n\n return this.bisectToLimit(y, hueRadians);\n }\n\n /** Ensure X is between 0 and 100. */\n static isBounded(x: number) {\n return x >= 0 && x <= 100;\n }\n\n /**\n * Returns the nth possible vertex of the polygonal intersection.\n *\n * @param y The Y value of the plane.\n * @param n The zero-based index of the point. 0 <= n <= 11.\n * @returns The nth possible vertex of the polygonal intersection of the y plane and the RGB cube in linear RGB coordinates, if\n * it exists. If the possible vertex lies outside of the cube, [-1.0, -1.0, -1.0] is returned.\n */\n static nthVertex(y: number, n: number): [number, number, number] {\n const kR = this.Y_FROM_LINRGB[0],\n kG = this.Y_FROM_LINRGB[1],\n kB = this.Y_FROM_LINRGB[2],\n coordA = n % 4 <= 1 ? 0 : 100,\n coordB = n % 2 === 0 ? 0 : 100;\n\n if (n < 4) {\n const g = coordA;\n const b = coordB;\n const r = (y - g * kG - b * kB) / kR;\n return this.isBounded(r) ? [r, g, b] : [-1, -1, -1];\n }\n if (n < 8) {\n const b = coordA;\n const r = coordB;\n const g = (y - r * kR - b * kB) / kG;\n return this.isBounded(g) ? [r, g, b] : [-1, -1, -1];\n }\n\n const r = coordA;\n const g = coordB;\n const b = (y - r * kR - g * kG) / kB;\n return this.isBounded(b) ? [r, g, b] : [-1, -1, -1];\n }\n\n static chromaticAdaptation(component: number) {\n const af = Math.pow(Math.abs(component), 0.42);\n return (CamUtilities.signum(component) * 400 * af) / (af + 27.13);\n }\n\n /**\n * Returns the hue of a linear RGB color in CAM16.\n *\n * @param linrgb The linear RGB coordinates of a color.\n * @returns The hue of the color in CAM16, in radians.\n */\n static hueOf(linrgb: [number, number, number]) {\n // Calculate scaled discount components using in-lined matrix multiplication to avoid\n // an array allocation.\n const matrix = this.SCALED_DISCOUNT_FROM_LINRGB,\n row = linrgb,\n rD = linrgb[0] * matrix[0][0] + row[1] * matrix[0][1] + row[2] * matrix[0][2],\n gD = linrgb[0] * matrix[1][0] + row[1] * matrix[1][1] + row[2] * matrix[1][2],\n bD = linrgb[0] * matrix[2][0] + row[1] * matrix[2][1] + row[2] * matrix[2][2];\n\n const rA = this.chromaticAdaptation(rD),\n gA = this.chromaticAdaptation(gD),\n bA = this.chromaticAdaptation(bD);\n\n // redness-greenness\n const a = (11 * rA + -12 * gA + bA) / 11;\n\n // yellowness-blueness\n const b = (rA + gA - 2 * bA) / 9;\n\n return Math.atan2(b, a);\n }\n\n /**\n * Sanitizes a small enough angle in radians.\n *\n * @param angle An angle in radians; must not deviate too much from 0.\n * @returns A coterminal angle between 0 and 2pi.\n */\n static sanitizeRadians(angle: number) {\n return (angle + Math.PI * 8) % (Math.PI * 2);\n }\n\n /**\n * Cyclic order is the idea that 330° → 5° → 200° is in order, but, 180° → 270° → 210° is not. Visually, A B and C are angles,\n * and they are in cyclic order if travelling from A to C in a way that increases angle (ex. counter-clockwise if +x axis = 0\n * degrees and +y = 90) means you must cross B.\n *\n * @param a First angle in possibly cyclic triplet\n * @param b Second angle in possibly cyclic triplet\n * @param c Third angle in possibly cyclic triplet\n * @returns True if B is between A and C\n */\n static areInCyclicOrder(a: number, b: number, c: number) {\n const deltaAB = this.sanitizeRadians(b - a);\n const deltaAC = this.sanitizeRadians(c - a);\n\n return deltaAB < deltaAC;\n }\n\n /**\n * Finds the segment containing the desired color.\n *\n * @param y The Y value of the color.\n * @param targetHue The hue of the color.\n * @returns A list of two sets of linear RGB coordinates, each corresponding to an endpoint of the segment containing the\n * desired color.\n */\n static bisectToSegment(y: number, targetHue: number) {\n let left: [number, number, number] = [-1, -1, -1],\n right = left,\n leftHue = 0,\n rightHue = 0,\n isInitialized = false,\n isUncut = true;\n\n for (let n = 0; n < 12; n++) {\n const mid = this.nthVertex(y, n);\n if (mid[0] < 0) {\n continue;\n }\n\n const midHue = this.hueOf(mid);\n if (!isInitialized) {\n left = mid;\n right = mid;\n leftHue = midHue;\n rightHue = midHue;\n isInitialized = true;\n continue;\n }\n\n if (isUncut || this.areInCyclicOrder(leftHue, midHue, rightHue)) {\n isUncut = false;\n if (this.areInCyclicOrder(leftHue, targetHue, midHue)) {\n right = mid;\n rightHue = midHue;\n } else {\n left = mid;\n leftHue = midHue;\n }\n }\n }\n\n return [left, right] as [[number, number, number], [number, number, number]];\n }\n\n static criticalPlaneBelow(x: number) {\n return Math.floor(x - 0.5);\n }\n\n static criticalPlaneAbove(x: number) {\n return Math.ceil(x - 0.5);\n }\n\n /**\n * Delinearizes an RGB component, returning a floating-point number.\n *\n * @param rgbComponent 0.0 <= rgb_component <= 100.0, represents linear R/G/B channel\n * @returns 0.0 <= output <= 255.0, color channel converted to regular RGB space\n */\n static trueDelinearized(rgbComponent: number) {\n const normalized = rgbComponent / 100;\n\n const delinearized = normalized <= 0.0031308 ? normalized * 12.92 : 1.055 * Math.pow(normalized, 1 / 2.4) - 0.055;\n\n return delinearized * 255;\n }\n\n /**\n * Find an intercept using linear interpolation.\n *\n * @param source The starting number.\n * @param mid The number in the middle.\n * @param target The ending number.\n * @returns A number t such that lerp(source, target, t) = mid.\n */\n static intercept(source: number, mid: number, target: number) {\n if (target === source) return target;\n\n return (mid - source) / (target - source);\n }\n\n /**\n * Linearly interpolate between two points in three dimensions.\n *\n * @param source Three dimensions representing the starting point\n * @param t The percentage to travel between source and target, from 0 to 1\n * @param target Three dimensions representing the end point\n * @returns Three dimensions representing the point t percent from source to target.\n */\n static lerpPoint(source: [number, number, number], t: number, target: [number, number, number]) {\n return [\n source[0] + (target[0] - source[0]) * t,\n source[1] + (target[1] - source[1]) * t,\n source[2] + (target[2] - source[2]) * t,\n ] as [number, number, number];\n }\n\n /**\n * Intersects a segment with a plane.\n *\n * @param source The coordinates of point A.\n * @param coordinate The R-, G-, or B-coordinate of the plane.\n * @param target The coordinates of point B.\n * @param axis The axis the plane is perpendicular with. (0: R, 1: G, 2: B)\n * @returns The intersection point of the segment AB with the plane R=coordinate, G=coordinate, or B=coordinate\n */\n static setCoordinate(source: [number, number, number], coordinate: number, target: [number, number, number], axis: 0 | 1 | 2) {\n const t = this.intercept(source[axis], coordinate, target[axis]);\n return this.lerpPoint(source, t, target);\n }\n\n /**\n * Finds a color with the given Y and hue on the boundary of the cube.\n *\n * @param y The Y value of the color.\n * @param targetHue The hue of the color.\n * @returns The desired color, in linear RGB coordinates.\n */\n static bisectToLimit(y: number, targetHue: number) {\n const segment = this.bisectToSegment(y, targetHue);\n\n let left = segment[0],\n leftHue = this.hueOf(left),\n right = segment[1];\n\n for (let axis = 0 as 0 | 1 | 2; axis < 3; axis++) {\n if (left[axis] === right[axis]) {\n continue;\n }\n\n let lPlane: number;\n let rPlane: number;\n\n if (left[axis] < right[axis]) {\n lPlane = this.criticalPlaneBelow(this.trueDelinearized(left[axis]));\n rPlane = this.criticalPlaneAbove(this.trueDelinearized(right[axis]));\n } else {\n lPlane = this.criticalPlaneAbove(this.trueDelinearized(left[axis]));\n rPlane = this.criticalPlaneBelow(this.trueDelinearized(right[axis]));\n }\n\n for (let index = 0; index < 8; index++) {\n if (Math.abs(rPlane - lPlane) <= 1) {\n break;\n }\n\n const mPlane = Math.floor((lPlane + rPlane) / 2);\n const midPlaneCoordinate = this.CRITICAL_PLANES[mPlane] ?? 0;\n\n const mid: [number, number, number] = this.setCoordinate(left, midPlaneCoordinate, right, axis);\n const midHue = this.hueOf(mid);\n if (this.areInCyclicOrder(leftHue, targetHue, midHue)) {\n right = mid;\n rPlane = mPlane;\n } else {\n left = mid;\n leftHue = midHue;\n lPlane = mPlane;\n }\n }\n }\n\n return CamUtilities.argbFromLinrgbComponents((left[0] + right[0]) / 2, (left[1] + right[1]) / 2, (left[2] + right[2]) / 2);\n }\n}\n","/*\n * This code was originally written in Java and has been converted to JavaScript.\n *\n * Original Java code source: [https://android.googlesource.com/platform/frameworks/base/+/refs/heads/main/core/java/com/android/internal/graphics/cam]\n *\n * Copyright (C) 2021 The Android Open Source Project.\n * The original code is licensed under the Apache License, Version 2.0.\n *\n * This JavaScript version is licensed under the MIT License.\n *\n * See the respective licenses for the specific terms, permissions, and limitations.\n */\nimport ColorUtilities from \"../utils/color-utilities.ts\";\nimport Color from \"../utils/color.ts\";\nimport MathUtilities from \"../utils/math-utilities.ts\";\nimport HctSolver from \"./hct-solver.ts\";\n\n/**\n * A color appearance model, based on CAM16, extended to use L* as the lightness dimension, and coupled to a gamut mapping\n * algorithm. Creates a color system, enables a digital design system.\n */\nexport class Cam {\n // When the delta between the floor & ceiling of a binary search for chroma is less than this,\n // the binary search terminates.\n static CHROMA_SEARCH_ENDPOINT = 0.4;\n\n // When the delta between the floor & ceiling of a binary search for J, lightness in CAM16,\n // is less than this, the binary search terminates.\n static LIGHTNESS_SEARCH_ENDPOINT = 0.01;\n\n // The maximum difference between the requested L* and the L* returned.\n static DL_MAX = 0.2;\n\n // The maximum color distance, in CAM16-UCS, between a requested color and the color returned.\n static DE_MAX = 1;\n\n /** The maximum difference between the requested L* and the L* returned. */\n DL_MAX = 0.2;\n /** When the delta between the floor & ceiling of a binary search for chroma is less than this, the binary search terminates. */\n CHROMA_SEARCH_ENDPOINT = 0.4;\n /**\n * When the delta between the floor & ceiling of a binary search for J, lightness in CAM16, is less than this, the binary search\n * terminates.\n */\n LIGHTNESS_SEARCH_ENDPOINT = 0.01;\n /**\n * SRGB specification has D65 whitepoint - Stokes, Anderson, Chandrasekar, Motta - A Standard Default Color Space for the\n * Internet: sRGB, 1996\n */\n WHITE_POINT_D65: [number, number, number] = [95.047, 100, 108.883];\n\n // CAM16 color dimensions, see getters for documentation.\n mHue: number;\n mChroma: number;\n mJ: number;\n mQ: number;\n mM: number;\n mS: number;\n\n // Coordinates in UCS space. Used to determine color distance, like delta E equations in L*a*b*.\n mJstar: number;\n mAstar: number;\n mBstar: number;\n\n constructor(\n hue: number,\n chroma: number,\n index: number,\n q: number,\n m: number,\n s: number,\n jstar: number,\n astar: number,\n bstar: number\n ) {\n this.mHue = hue;\n this.mChroma = chroma;\n this.mJ = index;\n this.mQ = q;\n this.mM = m;\n this.mS = s;\n this.mJstar = jstar;\n this.mAstar = astar;\n this.mBstar = bstar;\n }\n\n /** Hue in CAM16 */\n getHue() {\n return this.mHue;\n }\n\n /** Chroma in CAM16 */\n getChroma() {\n return this.mChroma;\n }\n\n /** Lightness in CAM16 */\n getJ() {\n return this.mJ;\n }\n\n /** A* coordinate in CAM16-UCS */\n getAstar() {\n return this.mAstar;\n }\n\n /** Lightness coordinate in CAM16-UCS */\n getJstar() {\n return this.mJstar;\n }\n\n /** B* coordinate in CAM16-UCS */\n getBstar() {\n return this.mBstar;\n }\n\n /**\n * Create a CAM from lightness, chroma, and hue coordinates. It is assumed those coordinates were measured in the sRGB standard\n * frame.\n */\n static fromJch(index: number, c: number, h: number) {\n return this.fromJchInFrame(index, c, h);\n }\n\n /** Create a CAM from lightness, chroma, and hue coordinates, and also specify the frame in which the color is being viewed. */\n static fromJchInFrame(index: number, c: number, h: number) {\n const q = (4 / Frame.DEFAULT.getC()) * Math.sqrt(index / 100) * (Frame.DEFAULT.getAw() + 4) * Frame.DEFAULT.getFlRoot();\n const m = c * Frame.DEFAULT.getFlRoot();\n const alpha = c / Math.sqrt(index / 100);\n const s = 50 * Math.sqrt((alpha * Frame.DEFAULT.getC()) / (Frame.DEFAULT.getAw() + 4));\n\n const hueRadians = (h * Math.PI) / 180;\n const jstar = ((1 + 100 * 0.007) * index) / (1 + 0.007 * index);\n const mstar = (1 / 0.0228) * Math.log(1 + 0.0228 * m);\n const astar = mstar * Math.cos(hueRadians);\n const bstar = mstar * Math.sin(hueRadians);\n return new Cam(h, c, index, q, m, s, jstar, astar, bstar);\n }\n\n /** Returns perceived color as an ARGB integer, as viewed in standard sRGB frame. */\n viewedInSrgb() {\n return this.viewed(Frame.DEFAULT);\n }\n\n /** Returns color perceived in a frame as an ARGB integer. */\n viewed(frame: Frame) {\n const alpha = this.getChroma() === 0 || this.getJ() === 0 ? 0 : this.getChroma() / Math.sqrt(this.getJ() / 100);\n\n const t = Math.pow(alpha / Math.pow(1.64 - Math.pow(0.29, frame.getN()), 0.73), 1 / 0.9),\n hRad = (this.getHue() * Math.PI) / 180;\n\n const ehue = 0.25 * (Math.cos(hRad + 2) + 3.8),\n ac = frame.getAw() * Math.pow(this.getJ() / 100, 1 / frame.getC() / frame.getZ()),\n p1 = ehue * (50_000 / 13) * frame.getNc() * frame.getNcb(),\n p2 = ac / frame.getNbb();\n\n const hSin = Math.sin(hRad),\n hCos = Math.cos(hRad);\n\n const gamma = (23 * (p2 + 0.305) * t) / (23 * p1 + 11 * t * hCos + 108 * t * hSin),\n a = gamma * hCos,\n b = gamma * hSin,\n rA = (460 * p2 + 451 * a + 288 * b) / 1403,\n gA = (460 * p2 - 891 * a - 261 * b) / 1403,\n bA = (460 * p2 - 220 * a - 6300 * b) / 1403;\n\n const rCBase = Math.max(0, (27.13 * Math.abs(rA)) / (400 - Math.abs(rA))),\n rC = Math.sign(rA) * (100 / frame.getFl()) * Math.pow(rCBase, 1 / 0.42),\n gCBase = Math.max(0, (27.13 * Math.abs(gA)) / (400 - Math.abs(gA))),\n gC = Math.sign(gA) * (100 / frame.getFl()) * Math.pow(gCBase, 1 / 0.42),\n bCBase = Math.max(0, (27.13 * Math.abs(bA)) / (400 - Math.abs(bA))),\n bC = Math.sign(bA) * (100 / frame.getFl()) * Math.pow(bCBase, 1 / 0.42),\n rF = rC / frame.getRgbD()[0],\n gF = gC / frame.getRgbD()[1],\n bF = bC / frame.getRgbD()[2];\n\n const matrix = CamUtilities.CAM16RGB_TO_XYZ,\n x = rF * matrix[0][0] + gF * matrix[0][1] + bF * matrix[0][2],\n y = rF * matrix[1][0] + gF * matrix[1][1] + bF * matrix[1][2],\n z = rF * matrix[2][0] + gF * matrix[2][1] + bF * matrix[2][2];\n\n return ColorUtilities.XYZToColor(x, y, z);\n }\n\n /**\n * Distance in CAM16-UCS space between two colors.\n *\n * Much like L_a_b* was designed to measure distance between colors, the CAM16 standard defined a color space called CAM16-UCS\n * to measure distance between CAM16 colors.\n */\n distance(other: Cam) {\n const dJ = this.getJstar() - other.getJstar(),\n dA = this.getAstar() - other.getAstar(),\n dB = this.getBstar() - other.getBstar(),\n dEPrime = Math.hypot(dJ, dA, dB),\n dE = 1.41 * Math.pow(dEPrime, 0.63);\n return dE;\n }\n\n /**\n * Find J, lightness in CAM16 color space, that creates a color with L* = `lstar` in the L_a_b* color space. Returns null if no\n * J could be found that generated a color with L* `lstar`.\n */\n static findCamByJ(hue: number, chroma: number, lstar: number) {\n let low = 0,\n high = 100,\n mid,\n bestdL = 1000,\n bestdE = 1000;\n\n let bestCam: Cam | null = null;\n while (Math.abs(low - high) > this.LIGHTNESS_SEARCH_ENDPOINT) {\n mid = low + (high - low) / 2;\n\n // Create the intended CAM color\n const camBeforeClip = this.fromJch(mid, chroma, hue);\n\n // Convert the CAM color to RGB. If the color didn't fit in RGB, during the conversion,\n // the initial RGB values will be outside 0 to 255. The final RGB values are clipped to\n // 0 to 255, distorting the intended color.\n const clipped = camBeforeClip.viewedInSrgb();\n const clippedLstar = CamUtilities.lstarFromInt(clipped);\n const dL = Math.abs(lstar - clippedLstar);\n\n // If the clipped color's L* is within error margin...\n if (dL < this.DL_MAX) {\n // ...check if the CAM equivalent of the clipped color is far away from intended CAM\n // color. For the intended color, use lightness and chroma from the clipped color,\n // and the intended hue. Callers are wondering what the lightness is, they know\n // chroma may be distorted, so the only concern here is if the hue slipped too far.\n const camClipped = this.fromInt(clipped);\n const dE = camClipped.distance(this.fromJch(camClipped.getJ(), camClipped.getChroma(), hue));\n if (dE <= this.DE_MAX) {\n bestdL = dL;\n bestdE = dE;\n bestCam = camClipped;\n }\n }\n\n // If there's no error at all, there's no need to search more.\n //\n // Note: this happens much more frequently than expected, but this is a very delicate\n // property which relies on extremely precise sRGB <=> XYZ calculations, as well as fine\n // tuning of the constants that determine error margins and when the binary search can\n // terminate.\n if (bestdL === 0 && bestdE === 0) {\n break;\n }\n\n if (clippedLstar < lstar) {\n low = mid;\n } else {\n high = mid;\n }\n }\n\n return bestCam;\n }\n\n /**\n * Given a hue & chroma in CAM16, L* in L_a_b*, return an ARGB integer. The chroma of the color returned may, and frequently\n * will, be lower than requested. Assumes the color is viewed in the frame defined by the sRGB standard.\n */\n static getInt(hue: number, chroma: number, lstar: number) {\n return this.getInt_(hue, chroma, lstar, Frame.DEFAULT);\n }\n\n /**\n * Given a hue & chroma in CAM16, L* in L_a_b*, and the frame in which the color will be viewed, return an ARGB integer.\n *\n * The chroma of the color returned may, and frequently will, be lower than requested. This is a fundamental property of color\n * that cannot be worked around by engineering. For example, a red hue, with high chroma, and high L* does not exist: red hues\n * have a maximum chroma below 10 in light shades, creating pink.\n */\n static getInt_(hue: number, chroma: number, lstar: number, frame: Frame) {\n // This is a crucial routine for building a color system, CAM16 itself is not sufficient.\n //\n // * Why these dimensions?\n // Hue and chroma from CAM16 are used because they're the most accurate measures of those\n // quantities. L* from L*a*b* is used because it correlates with luminance, luminance is\n // used to measure contrast for a11y purposes, thus providing a key constraint on what\n // colors\n // can be used.\n //\n // * Why is this routine required to build a color system?\n // In all perceptually accurate color spaces (i.e. L*a*b* and later), `chroma` may be\n // impossible for a given `hue` and `lstar`.\n // For example, a high chroma light red does not exist - chroma is limited to below 10 at\n // light red shades, we call that pink. High chroma light green does exist, but not dark\n // Also, when converting from another color space to RGB, the color may not be able to be\n // represented in RGB. In those cases, the conversion process ends with RGB values\n // outside 0-255\n // The vast majority of color libraries surveyed simply round to 0 to 255. That is not an\n // option for this library, as it distorts the expected luminance, and thus the expected\n // contrast needed for a11y\n //\n // * What does this routine do?\n // Dealing with colors in one color space not fitting inside RGB is, loosely referred to as\n // gamut mapping or tone mapping. These algorithms are traditionally idiosyncratic, there is\n // no universal answer. However, because the intent of this library is to build a system for\n // digital design, and digital design uses luminance to measure contrast/a11y, we have one\n // very important constraint that leads to an objective algorithm: the L* of the returned\n // color _must_ match the requested L*.\n //\n // Intuitively, if the color must be distorted to fit into the RGB gamut, and the L*\n // requested *must* be fulfilled, than the hue or chroma of the returned color will need\n // to be different from the requested hue/chroma.\n //\n // After exploring both options, it was more intuitive that if the requested chroma could\n // not be reached, it used the highest possible chroma. The alternative was finding the\n // closest hue where the requested chroma could be reached, but that is not nearly as\n // intuitive, as the requested hue is so fundamental to the color description.\n\n // If the color doesn't have meaningful chroma, return a gray with the requested Lstar.\n //\n // Yellows are very chromatic at L = 100, and blues are very chromatic at L = 0. All the\n // other hues are white at L = 100, and black at L = 0. To preserve consistency for users of\n // this system, it is better to simply return white at L* > 99, and black and L* < 0.\n if (frame === Frame.DEFAULT) {\n // If the viewing conditions are the same as the default sRGB-like viewing conditions,\n // skip to using HctSolver: it uses geometrical insights to find the closest in-gamut\n // match to hue/chroma/lstar.\n return HctSolver.solveToInt(hue, chroma, lstar);\n }\n\n if (chroma < 1 || Math.round(lstar) <= 0 || Math.round(lstar) >= 100) {\n return CamUtilities.intFromLstar(lstar);\n }\n\n hue = hue < 0 ? 0 : Math.min(360, hue);\n\n // The highest chroma possible. Updated as binary search proceeds.\n let high = chroma;\n\n // The guess for the current binary search iteration. Starts off at the highest chroma,\n // thus, if a color is possible at the requested chroma, the search can stop after one try.\n let mid = chroma;\n let low = 0;\n let isFirstLoop = true;\n\n let answer: Cam | null = null;\n\n while (Math.abs(low - high) >= this.CHROMA_SEARCH_ENDPOINT) {\n // Given the current chroma guess, mid, and the desired hue, find J, lightness in\n // CAM16 color space, that creates a color with L* = `lstar` in the L*a*b* color space.\n const possibleAnswer = this.findCamByJ(hue, mid, lstar);\n\n if (isFirstLoop) {\n if (possibleAnswer == undefined) {\n // If this binary search iteration was the first iteration, and this point\n // has been reached, it means the requested chroma was not available at the\n // requested hue and L*.\n // Proceed to a traditional binary search that starts at the midpoint between\n // the requested chroma and 0.\n isFirstLoop = false;\n mid = low + (high - low) / 2;\n continue;\n }\n return possibleAnswer.viewed(frame);\n }\n\n if (possibleAnswer == undefined) {\n // There isn't a CAM16 J that creates a color with L* `lstar`. Try a lower chroma.\n high = mid;\n } else {\n answer = possibleAnswer;\n // It is possible to create a color. Try higher chroma.\n low = mid;\n }\n\n mid = low + (high - low) / 2;\n }\n\n // There was no answer: meaning, for the desired hue, there was no chroma low enough to\n // generate a color with the desired L*.\n // All values of L* are possible when there is 0 chroma. Return a color with 0 chroma, i.e.\n // a shade of gray, with the desired L*.\n if (answer == undefined) {\n return CamUtilities.intFromLstar(lstar);\n }\n\n return answer.viewed(frame);\n }\n\n static intFromLstar(lstar: number) {\n if (lstar < 1) {\n return 0xff_00_00_00;\n }\n if (lstar > 99) {\n return 0xff_ff_ff_ff;\n }\n\n // XYZ to LAB conversion routine, assume a and b are 0.\n const fy = (lstar + 16) / 116;\n\n // fz = fx = fy because a and b are 0\n const fz = fy,\n fx = fy;\n\n const kappa = 24_389 / 27,\n epsilon = 216 / 24_389,\n isLExceedsEpsilonKappa = lstar > 8,\n yT = isLExceedsEpsilonKappa ? fy * fy * fy : lstar / kappa,\n isCubeExceedEpsilon = fy * fy * fy > epsilon,\n xT = isCubeExceedEpsilon ? fx * fx * fx : (116 * fx - 16) / kappa,\n zT = isCubeExceedEpsilon ? fz * fz * fz : (116 * fx - 16) / kappa;\n\n return ColorUtilities.XYZToColor(\n xT * CamUtilities.WHITE_POINT_D65[0],\n yT * CamUtilities.WHITE_POINT_D65[1],\n zT * CamUtilities.WHITE_POINT_D65[2]\n );\n }\n\n static fromIntInFrame(argb: number, frame: Frame) {\n // Transform ARGB int to XYZ\n const xyz: [number, number, number] = CamUtilities.xyzFromInt(argb);\n\n // Transform XYZ to 'cone'/'rgb' responses\n const matrix = CamUtilities.XYZ_TO_CAM16RGB,\n rT: number = xyz[0] * matrix[0][0] + xyz[1] * matrix[0][1] + xyz[2] * matrix[0][2],\n gT: number = xyz[0] * matrix[1][0] + xyz[1] * matrix[1][1] + xyz[2] * matrix[1][2],\n bT: number = xyz[0] * matrix[2][0] + xyz[1] * matrix[2][1] + xyz[2] * matrix[2][2];\n\n // Discount illuminant\n const rD = frame.getRgbD()[0] * rT,\n gD = frame.getRgbD()[1] * gT,\n bD = frame.getRgbD()[2] * bT;\n\n // Chromatic adaptation\n const rAF = Math.pow((frame.getFl() * Math.abs(rD)) / 100, 0.42),\n gAF = Math.pow((frame.getFl() * Math.abs(gD)) / 100, 0.42),\n bAF = Math.pow((frame.getFl() * Math.abs(bD)) / 100, 0.42),\n rA = (Math.sign(rD) * 400 * rAF) / (rAF + 27.13),\n gA = (Math.sign(gD) * 400 * gAF) / (gAF + 27.13),\n bA = (Math.sign(bD) * 400 * bAF) / (bAF + 27.13);\n\n // redness-greennes\n const a = (11 * rA + -12 * gA + bA) / 11;\n // yellowness-blueness\n const b = (rA + gA - 2 * bA) / 9;\n\n // auxiliary components\n const u = (20 * rA + 20 * gA + 21 * bA) / 20,\n p2 = (40 * rA + 20 * gA + bA) / 20;\n\n // hue\n const atan2 = Math.atan2(b, a),\n atanDegrees = (atan2 * 180) / Math.PI,\n hue = atanDegrees < 0 ? atanDegrees + 360 : atanDegrees >= 360 ? atanDegrees - 360 : atanDegrees,\n hueRadians = (hue * Math.PI) / 180;\n\n // achromatic response to color\n const ac = p2 * frame.getNbb();\n\n // CAM16 lightness and brightness\n const index = 100 * Math.pow(ac / frame.getAw(), frame.getC() * frame.getZ());\n const q = (4 / frame.getC()) * Math.sqrt(index / 100) * (frame.getAw() + 4) * frame.getFlRoot();\n\n // CAM16 chroma, colorfulness, and saturation.\n const huePrime = hue < 20.14 ? hue + 360 : hue,\n ehue = 0.25 * (Math.cos((huePrime * Math.PI) / 180 + 2) + 3.8),\n p1 = (50_000 / 13) * ehue * frame.getNc() * frame.getNcb(),\n t = (p1 * Math.hypot(a, b)) / (u + 0.305),\n alpha = Math.pow(t, 0.9) * Math.pow(1.64 - Math.pow(0.29, frame.getN()), 0.73);\n\n // CAM16 chroma, colorfulness, saturation\n const c = alpha * Math.sqrt(index / 100),\n m = c * frame.getFlRoot(),\n s = 50 * Math.sqrt((alpha * frame.getC()) / (frame.getAw() + 4));\n\n // CAM16-UCS components\n const jstar = ((1 + 100 * 0.007) * index) / (1 + 0.007 * index),\n mstar = (1 / 0.0228) * Math.log(1 + 0.0228 * m),\n astar = mstar * Math.cos(hueRadians),\n bstar = mstar * Math.sin(hueRadians);\n\n return new Cam(hue, c, index, q, m, s, jstar, astar, bstar);\n }\n\n /**\n * Create a color appearance model from a ARGB integer representing a color. It is assumed the color was viewed in the frame\n * defined in the sRGB standard.\n */\n static fromInt(argb: number) {\n return this.fromIntInFrame(argb, Frame.DEFAULT);\n }\n}\n\n/**\n * Collection of methods for transforming between color spaces.\n *\n * Methods are named $xFrom$Y. For example, lstarFromInt() returns L* from an ARGB integer.\n *\n * These methods, generally, convert colors between the L_a_b*, XYZ, and sRGB spaces.\n *\n * L_a_b* is a perceptually accurate color space. This is particularly important in the L* dimension: it measures luminance and\n * unlike lightness measures traditionally used in UI work via RGB or HSL, this luminance transitions smoothly, permitting\n * creation of pleasing shades of a color, and more pleasing transitions between colors.\n *\n * XYZ is commonly used as an intermediate color space for converting between one color space to another. For example, to convert\n * RGB to L_a_b*, first RGB is converted to XYZ, then XYZ is converted to L_a_b*.\n *\n * SRGB is a \"specification originated from work in 1990s through cooperation by Hewlett-Packard and Microsoft, and it was\n * designed to be a standard definition of RGB for the internet, which it indeed became...The standard is based on a sampling of\n * computer monitors at the time...The whole idea of sRGB is that if everyone assumed that RGB meant the same thing, then the\n * results would be consistent, and reasonably good. It worked.\" - Fairchild, Color Models and Systems: Handbook of Color\n * Psychology, 2015\n */\n// eslint-disable-next-line unicorn/no-static-only-class\nexport class CamUtilities {\n /**\n * This is a more precise sRGB to XYZ transformation matrix than traditionally used. It was derived using Schlomer's technique\n * of transforming the xyY primaries to XYZ, then applying a correction to ensure mapping from sRGB 1, 1, 1 to the reference\n * white point, D65.\n */\n static SRGB_TO_XYZ: [[number, number, number], [number, number, number], [number, number, number]] = [\n [0.41233895, 0.35762064, 0.18051042],\n [0.2126, 0.7152, 0.0722],\n [0.01932141, 0.11916382, 0.95034478],\n ];\n\n /** Transforms XYZ color space coordinates to 'cone'/'RGB' responses in CAM16. */\n static XYZ_TO_CAM16RGB: [[number, number, number], [number, number, number], [number, number, number]] = [\n [0.401288, 0.650173, -0.051461],\n [-0.250268, 1.204414, 0.045854],\n [-0.002079, 0.048952, 0.953127],\n ];\n\n static XYZ_TO_SRGB: [[number, number, number], [number, number, number], [number, number, number]] = [\n [3.2413774792388685, -1.5376652402851851, -0.49885366846268053],\n [-0.9691452513005321, 1.8758853451067872, 0.04156585616912061],\n [0.05562093689691305, -0.20395524564742123, 1.0571799111220335],\n ];\n\n /** Transforms 'cone'/'RGB' responses in CAM16 to XYZ color space coordinates. */\n static CAM16RGB_TO_XYZ: [[number, number, number], [number, number, number], [number, number, number]] = [\n [1.86206786, -1.01125463, 0.14918677],\n [0.38752654, 0.62144744, -0.00897398],\n [-0.0158415, -0.03412294, 1.04996444],\n ];\n\n /**\n * SRGB specification has D65 whitepoint - Stokes, Anderson, Chandrasekar, Motta - A Standard Default Color Space for the\n * Internet: sRGB, 1996\n */\n static WHITE_POINT_D65: [number, number, number] = [95.047, 100, 108.883];\n\n /** Returns L* from L_a_b*, perceptual luminance, from an ARGB integer (ColorInt). */\n static lstarFromInt(argb: number) {\n return this.lstarFromY(this.yFromInt(argb));\n }\n\n static lstarFromY(y: number) {\n y /= 100;\n const element = 216 / 24_389;\n if (y <= element) {\n return (24_389 / 27) * y;\n }\n const yIntermediate = Math.cbrt(y);\n return 116 * yIntermediate - 16;\n }\n\n static yFromInt(argb: number) {\n const r = this.linearized(Color.red(argb)),\n g = this.linearized(Color.green(argb)),\n b = this.linearized(Color.blue(argb)),\n matrix = this.SRGB_TO_XYZ,\n y = r * matrix[1][0] + g * matrix[1][1] + b * matrix[1][2];\n return y;\n }\n\n static xyzFromInt(argb: number): [number, number, number] {\n const r = this.linearized(Color.red(argb)),\n g = this.linearized(Color.green(argb)),\n b = this.linearized(Color.blue(argb));\n\n const matrix = this.SRGB_TO_XYZ,\n x = r * matrix[0][0] + g * matrix[0][1] + b * matrix[0][2],\n y = r * matrix[1][0] + g * matrix[1][1] + b * matrix[1][2],\n z = r * matrix[2][0] + g * matrix[2][1] + b * matrix[2][2];\n\n return [x, y, z];\n }\n\n static linearized(rgbComponent: number): number {\n const normalized = rgbComponent / 255;\n\n return normalized <= 0.04045 ? (normalized / 12.92) * 100 : Math.pow((normalized + 0.055) / 1.055, 2.4) * 100;\n }\n\n /**\n * Converts an L* value to a Y value.\n *\n * L* in L_a_b* and Y in XYZ measure the same quantity, luminance.\n *\n * L* measures perceptual luminance, a linear scale. Y in XYZ measures relative luminance, a logarithmic scale.\n *\n * @param lstar L* in L_a_b*\n * @returns Y in XYZ\n */\n static yFromLstar(lstar: number) {\n const ke = 8;\n return lstar > ke ? Math.pow((lstar + 16) / 116, 3) * 100 : (lstar / (24_389 / 27)) * 100;\n }\n\n /**\n * Clamps an integer between two integers.\n *\n * @returns Input when min <= input <= max, and either min or max otherwise.\n */\n static clampInt(min: number, max: number, input: number) {\n if (input < min) {\n return min;\n }\n if (input > max) {\n return max;\n }\n\n return input;\n }\n\n /**\n * Delinearizes an RGB component.\n *\n * @param rgbComponent 0 <= rgb_component <= 100, represents linear R/G/B channel\n * @returns 0 <= output <= 255, color channel converted to regular RGB space\n */\n static delinearized(rgbComponent: number) {\n const normalized = rgbComponent / 100;\n const delinearized = normalized <= 0.0031308 ? normalized * 12.92 : 1.055 * Math.pow(normalized, 1 / 2.4) - 0.055;\n return this.clampInt(0, 255, Math.round(delinearized * 255));\n }\n\n /** Converts a color from RGB components to ARGB format. */\n static argbFromRgb(red: number, green: number, blue: number) {\n return (255 << 24) | ((red & 255) << 16) | ((green & 255) << 8) | (blue & 255);\n }\n\n /** Converts a color from ARGB to XYZ. */\n static argbFromXyz(x: number, y: number, z: number) {\n const matrix = this.XYZ_TO_SRGB,\n linearR = matrix[0][0] * x + matrix[0][1] * y + matrix[0][2] * z,\n linearG = matrix[1][0] * x + matrix[1][1] * y + matrix[1][2] * z,\n linearB = matrix[2][0] * x + matrix[2][1] * y + matrix[2][2] * z,\n r = this.delinearized(linearR),\n g = this.delinearized(linearG),\n b = this.delinearized(linearB);\n\n return this.argbFromRgb(r, g, b);\n }\n\n /**\n * Convert a color appearance model representation to an ARGB color.\n *\n * Note: the returned color may have a lower chroma than requested. Whether a chroma is available depends on luminance. For\n * example, there's no such thing as a high chroma light red, due to the limitations of our eyes and/or physics. If the\n * requested chroma is unavailable, the highest possible chroma at the requested luminance is returned.\n *\n * @param hue Hue, in degrees, in CAM coordinates\n * @param chroma Chroma in CAM coordinates.\n * @param lstar Perceptual luminance, L* in L_a_b*\n */\n static CAMToColor(hue: number, chroma: number, lstar: number) {\n return Cam.getInt(hue, chroma, lstar);\n }\n\n /**\n * Converts an L* value to an ARGB representation.\n *\n * @param lstar L* in L_a_b*\n * @returns ARGB representation of grayscale color with lightness matching L*\n */\n static argbFromLstar(lstar: number) {\n const fy = (lstar + 16) / 116,\n fz = fy,\n fx = fy,\n kappa = 24_389 / 27,\n epsilon = 216 / 24_389,\n isLExceedsEpsilonKappa = lstar > 8,\n y = isLExceedsEpsilonKappa ? fy * fy * fy : lstar / kappa,\n isCubeExceedEpsilon = fy * fy * fy > epsilon,\n x = isCubeExceedEpsilon ? fx * fx * fx : lstar / kappa,\n z = isCubeExceedEpsilon ? fz * fz * fz : lstar / kappa,\n whitePoint = this.WHITE_POINT_D65;\n\n return this.argbFromXyz(x * whitePoint[0], y * whitePoint[1], z * whitePoint[2]);\n }\n\n /** Converts a color from linear RGB components to ARGB format. */\n static argbFromLinrgbComponents(r: number, g: number, b: number) {\n return this.argbFromRgb(this.delinearized(r), this.delinearized(g), this.delinearized(b));\n }\n\n /**\n * The signum function.\n *\n * @returns 1 if num > 0, -1 if num < 0, and 0 if num = 0\n */\n static signum(number_: number) {\n if (number_ < 0) {\n return -1;\n }\n return number_ === 0 ? 0 : 1;\n }\n\n static intFromLstar(lstar: number) {\n if (lstar < 1) {\n return 0xff_00_00_00;\n }\n if (lstar > 99) {\n return 0xff_ff_ff_ff;\n }\n\n // XYZ to LAB conversion routine, assume a and b are 0.\n const fy = (lstar + 16) / 116;\n\n // fz = fx = fy because a and b are 0\n const fz = fy;\n const fx = fy;\n\n const kappa = 24_389 / 27;\n const epsilon = 216 / 24_389;\n const isLExceedsEpsilonKappa = lstar > 8;\n const yT = isLExceedsEpsilonKappa ? fy * fy * fy : lstar / kappa;\n const isCubeExceedEpsilon = fy * fy * fy > epsilon;\n const xT = isCubeExceedEpsilon ? fx * fx * fx : (116 * fx - 16) / kappa;\n const zT = isCubeExceedEpsilon ? fz * fz * fz : (116 * fx - 16) / kappa;\n\n return ColorUtilities.XYZToColor(xT * this.WHITE_POINT_D65[0], yT * this.WHITE_POINT_D65[1], zT * this.WHITE_POINT_D65[2]);\n }\n}\n\n/**\n * The frame, or viewing conditions, where a color was seen. Used, along with a color, to create a color appearance model\n * representing the color.\n *\n * To convert a traditional color to a color appearance model, it requires knowing what conditions the color was observed in. Our\n * perception of color depends on, for example, the tone of the light illuminating the color, how bright that light was, etc.\n *\n * This class is modelled separately from the color appearance model itself because there are a number of calculations during the\n * color => CAM conversion process that depend only on the viewing conditions. Caching those calculations in a Frame instance\n * saves a significant amount of time.\n */\nexport class Frame {\n mN: number;\n mAw: number;\n mNbb: number;\n mNcb: number;\n mC: number;\n mNc: number;\n mRgbD: [number, number, number];\n mFl: number;\n mFlRoot: number;\n mZ: number;\n\n constructor(\n n: number,\n aw: number,\n nbb: number,\n ncb: number,\n c: number,\n nc: number,\n rgbD: [number, number, number],\n fl: number,\n fLRoot: number,\n z: number\n ) {\n this.mN = n;\n this.mAw = aw;\n this.mNbb = nbb;\n this.mNcb = ncb;\n this.mC = c;\n this.mNc = nc;\n this.mRgbD = rgbD;\n this.mFl = fl;\n this.mFlRoot = fLRoot;\n this.mZ = z;\n }\n\n getRgbD() {\n return this.mRgbD;\n }\n getFl() {\n return this.mFl;\n }\n getNbb() {\n return this.mNbb;\n }\n getAw() {\n return this.mAw;\n }\n getC() {\n return this.mC;\n }\n getFlRoot() {\n return this.mFlRoot;\n }\n getNc() {\n return this.mNc;\n }\n getNcb() {\n return this.mNcb;\n }\n getZ() {\n return this.mZ;\n }\n getN() {\n return this.mN;\n }\n\n static make(\n whitepoint: [number, number, number],\n adaptingLuminance: number,\n backgroundLstar: number,\n surround: number,\n shouldDiscountingIlluminant: boolean\n ) {\n // Transform white point XYZ to 'cone'/'rgb' responses\n const matrix = CamUtilities.XYZ_TO_CAM16RGB,\n xyz = whitepoint,\n rW = xyz[0] * matrix[0][0] + xyz[1] * matrix[0][1] + xyz[2] * matrix[0][2],\n gW = xyz[0] * matrix[1][0] + xyz[1] * matrix[1][1] + xyz[2] * matrix[1][2],\n bW = xyz[0] * matrix[2][0] + xyz[1] * matrix[2][1] + xyz[2] * matrix[2][2];\n\n // Scale input surround, domain (0, 2), to CAM16 surround, domain (0.8, 1)\n const f = 0.8 + surround / 10;\n // \"Exponential non-linearity\"\n const c = f >= 0.9 ? MathUtilities.lerp(0.59, 0.69, (f - 0.9) * 10) : MathUtilities.lerp(0.525, 0.59, (f - 0.8) * 10);\n // Calculate degree of adaptation to illuminant\n let d = shouldDiscountingIlluminant ? 1 : f * (1 - (1 / 3.6) * Math.exp((-adaptingLuminance - 42) / 92));\n // Per Li et al, if D is greater than 1 or less than 0, set it to 1 or 0.\n d = d > 1 ? 1 : Math.max(d, 0);\n // Chromatic induction factor\n const nc = f;\n\n // Cone responses to the whitepoint, adjusted for illuminant discounting.\n //\n // Why use 100 instead of the white point's relative luminance?\n //\n // Some papers and implementations, for both CAM02 and CAM16, use the Y\n // value of the reference white instead of 100. Fairchild's Color Appearance\n // Models (3rd edition) notes that this is in error: it was included in the\n // CIE 2004a report on CIECAM02, but, later parts of the conversion process\n // account for scaling of appearance relative to the white point relative\n // luminance. This part should simply use 100 as luminance.\n const rgbD = [d * (100 / rW) + 1 - d, d * (100 / gW) + 1 - d, d * (100 / bW) + 1 - d] as [number, number, number];\n // Luminance-level adaptation factor\n const k = 1 / (5 * adaptingLuminance + 1);\n const k4 = k * k * k * k;\n const k4F = 1 - k4;\n const fl = k4 * adaptingLuminance + 0.1 * k4F * k4F * Math.cbrt(5 * adaptingLuminance);\n\n // Intermediate factor, ratio of background relative luminance to white relative luminance\n const n = CamUtilities.yFromLstar(backgroundLstar) / whitepoint[1];\n\n // Base exponential nonlinearity\n // note Schlomer 2018 has a typo and uses 1.58, the correct factor is 1.48\n const z = 1.48 + Math.sqrt(n);\n\n // Luminance-level induction factors\n const nbb = 0.725 / Math.pow(n, 0.2);\n const ncb = nbb;\n\n // Discounted cone responses to the white point, adjusted for post-chromatic\n // adaptation perceptual nonlinearities.\n const rgbAFactors = [\n Math.pow((fl * rgbD[0] * rW) / 100, 0.42),\n Math.pow((fl * rgbD[1] * gW) / 100, 0.42),\n Math.pow((fl * rgbD[2] * bW) / 100, 0.42),\n ] as const;\n\n const rgbA = [\n (400 * rgbAFactors[0]) / (rgbAFactors[0] + 27.13),\n (400 * rgbAFactors[1]) / (rgbAFactors[1] + 27.13),\n (400 * rgbAFactors[2]) / (rgbAFactors[2] + 27.13),\n ] as const;\n\n const aw = (2 * rgbA[0] + rgbA[1] + 0.05 * rgbA[2]) * nbb;\n\n return new Frame(n, aw, nbb, ncb, c, nc, rgbD, fl, Math.pow(fl, 0.25), z);\n }\n\n static DEFAULT = Frame.make(CamUtilities.WHITE_POINT_D65, ((200 / Math.PI) * CamUtilities.yFromLstar(50)) / 100, 50, 2, false);\n}\n","/*\n * This code was originally written in Java and has been converted to JavaScript.\n *\n * Original Java code source: [https://android.googlesource.com/platform/frameworks/base/+/6844741fb8351f3aa82b96ce64a1bd83ea7989bd/packages/SystemUI/monet/src/com/android/systemui/monet?autodive=0%2F]\n *\n * Copyright (C) 2021 The Android Open Source Project.\n * The original code is licensed under the Apache License, Version 2.0.\n *\n * This JavaScript version is licensed under the MIT License.\n *\n * See the respective licenses for the specific terms, permissions, and limitations.\n */\nimport ColorUtilities from \"../utils/color-utilities.ts\";\n\nconst Shades = {\n /**\n * Combining the ability to convert between relative luminance and perceptual luminance with contrast leads to a design system\n * that can be based on a linear value to determine contrast, rather than a ratio.\n *\n * This codebase implements a design system that has that property, and as a result, we can guarantee that any shades 5 steps\n * from each other have a contrast ratio of at least 4.5. 4.5 is the requirement for smaller text contrast in WCAG 2.1 and\n * earlier.\n *\n * However, lstar 50 does _not_ have a contrast ratio >= 4.5 with lstar 100. lstar 49.6 is the smallest lstar that will lead to\n * a contrast ratio >= 4.5 with lstar 100, and it also contrasts >= 4.5 with lstar 100.\n */\n MIDDLE_LSTAR: 49.6,\n\n /**\n * Generate shades of a color. Ordered in lightness _descending_. The first shade will be at 95% lightness, the next at 90, 80,\n * etc. through 0.\n *\n * @param hue Hue in CAM16 color space\n * @param chroma Chroma in CAM16 color space\n * @returns Shades of a color, as argb integers. Ordered by lightness descending.\n */\n of(hue: number, chroma: number) {\n const shades: number[] = [];\n\n const shadesLStar = [99, 95, 90, 85, 80, 75, 70, 65, 60, 55, Shades.MIDDLE_LSTAR, 45, 40, 35, 30, 25, 20, 15, 10, 5, 1, 0];\n\n for (const lStar of shadesLStar) {\n if (lStar >= 90) chroma = Math.min(40, chroma);\n shades.push(ColorUtilities.CAMToColor(hue, chroma, lStar));\n }\n\n shades.unshift(16_777_215); // first color is always pure white\n\n return shades;\n },\n};\n\nexport default Shades;\n","/*\n * This code was originally written in Java and has been converted to JavaScript.\n *\n * Original Java code source: [https://android.googlesource.com/platform/frameworks/base/+/6844741fb8351f3aa82b96ce64a1bd83ea7989bd/packages/SystemUI/monet/src/com/android/systemui/monet?autodive=0%2F]\n *\n * Copyright (C) 2021 The Android Open Source Project.\n * The original code is licensed under the Apache License, Version 2.0.\n *\n * This JavaScript version is licensed under the MIT License.\n *\n * See the respective licenses for the specific terms, permissions, and limitations.\n */\nimport { Cam } from \"../cam/cam.ts\";\nimport Color from \"../utils/color.ts\";\nimport Shades from \"./shades.ts\";\n\nimport type { GenerationStyle, MaterialYouPalette } from \"../types.d.ts\";\n\ntype StyleType = Record<GenerationStyle, Record<\"a1\" | \"a2\" | \"a3\" | \"n1\" | \"n2\", [number, number]>>;\n\nconst Palette = {\n ACCENT1_CHROMA: 48,\n ACCENT2_CHROMA: 16,\n ACCENT3_CHROMA: 32,\n ACCENT3_HUE_SHIFT: 60,\n NEUTRAL1_CHROMA: 4,\n NEUTRAL2_CHROMA: 8,\n GOOGLE_BLUE: 0xff_1b_6e_f3,\n\n getStyle(hue: number, chroma: number): StyleType {\n return {\n SPRITZ: {\n a1: [hue, 12],\n a2: [hue, 8],\n a3: [hue, 16],\n n1: [hue, 2],\n n2: [hue, 2],\n },\n TONAL_SPOT: {\n a1: [hue, 36],\n a2: [hue, 16],\n a3: [Palette.HueAdd(hue, 60), 24],\n n1: [hue, 4],\n n2: [hue, 8],\n },\n VIBRANT: {\n a1: [hue, 130],\n a2: [Palette.HueVibrantSecondary(hue), 24],\n a3: [Palette.HueVibrantTertiary(hue), 32],\n n1: [hue, 10],\n n2: [hue, 12],\n },\n EXPRESSIVE: {\n a1: [Palette.HueAdd(hue, 240), 40],\n a2: [Palette.HueExpressiveSecondary(hue), 24],\n a3: [Palette.HueExpressiveTertiary(hue), 32],\n n1: [Palette.HueAdd(hue, 15), 8],\n n2: [Palette.HueAdd(hue, 15), 12],\n },\n RAINBOW: {\n a1: [hue, 48],\n a2: [hue, 16],\n a3: [Palette.HueAdd(hue, 60), 24],\n n1: [hue, 0],\n n2: [hue, 0],\n },\n FRUIT_SALAD: {\n a1: [Palette.HueSubtract(hue, 50), 48],\n a2: [Palette.HueSubtract(hue, 50), 36],\n a3: [hue, 36],\n n1: [hue, 10],\n n2: [hue, 16],\n },\n CONTENT: {\n a1: [hue, chroma],\n a2: [hue, Palette.ChromaMultiple(chroma, 0.33)],\n a3: [hue, Palette.ChromaMultiple(chroma, 0.66)],\n n1: [hue, Palette.ChromaMultiple(chroma, 0.0833)],\n n2: [hue, Palette.ChromaMultiple(chroma, 0.1666)],\n },\n MONOCHROMATIC: {\n a1: [hue, 0],\n a2: [hue, 0],\n a3: [hue, 0],\n n1: [hue, 0],\n n2: [hue, 0],\n },\n };\n },\n\n HueAdd(hue: number, amountDegrees: number): number {\n return Palette.wrapDegreesDouble(hue + amountDegrees);\n },\n\n HueSubtract(hue: number, amountDegrees: number): number {\n return Palette.wrapDegreesDouble(hue - amountDegrees);\n },\n\n ChromaMultiple(chroma: number, multiple: number): number {\n return chroma * multiple;\n },\n\n getHueRotation(sourceHue: number, hueAndRotations: Array<[number, number]>): number {\n const sanitizedSourceHue = sourceHue < 0 || sourceHue >= 360 ? 0 : sourceHue;\n\n for (let index = 0; index < hueAndRotations.length - 1; index++) {\n const thisHue = hueAndRotations[index][0];\n const nextHue = hueAndRotations[index + 1][0];\n\n if (thisHue <= sanitizedSourceHue && sanitizedSourceHue < nextHue) {\n return Palette.wrapDegreesDouble(sanitizedSourceHue + hueAndRotations[index][1]);\n }\n }\n\n // If this statement executes, something is wrong, there should have been a rotation\n // found using the arrays.\n return sourceHue;\n },\n\n HueVibrantSecondary(hue: number) {\n const hueToRotations: Array<[number, number]> = [\n [0, 18],\n [41, 15],\n [61, 10],\n [101, 12],\n [131, 15],\n [181, 18],\n [251, 15],\n [301, 12],\n [360, 12],\n ];\n\n return Palette.getHueRotation(hue, hueToRotations);\n },\n\n HueVibrantTertiary(hue: number) {\n const hueToRotations: Array<[number, number]> = [\n [0, 35],\n [41, 30],\n [61, 20],\n [101, 25],\n [131, 30],\n [181, 35],\n [251, 30],\n [301, 25],\n [360, 25],\n ];\n\n return Palette.getHueRotation(hue, hueToRotations);\n },\n\n HueExpressiveSecondary(hue: number) {\n const hueToRotations: Array<[number, number]> = [\n [0, 45],\n [21, 95],\n [51, 45],\n [121, 20],\n [151, 45],\n [191, 90],\n [271, 45],\n [321, 45],\n [360, 45],\n ];\n\n return Palette.getHueRotation(hue, hueToRotations);\n },\n\n HueExpressiveTertiary(hue: number) {\n const hueToRotations: Array<[number, number]> = [\n [0, 120],\n [21, 120],\n [51, 20],\n [121, 45],\n [151, 20],\n [191, 15],\n [271, 20],\n [321, 120],\n [360, 120],\n ];\n\n return Palette.getHueRotation(hue, hueToRotations);\n },\n\n wrapDegreesDouble(degrees: number): number {\n if (degrees < 0) {\n return (degrees % 360) + 360;\n }\n return degrees >= 360 ? degrees % 360 : degrees;\n },\n\n generate(seed: string, style: GenerationStyle = \"TONAL_SPOT\"): MaterialYouPalette {\n // Parse the HEX seed color string into an integer\n seed = seed.toUpperCase().slice(1, 7);\n const colorInt = Number.parseInt(\"0xff\" + seed, 16);\n\n const seedArgb = colorInt === Color.TRANSPARENT ? Palette.GOOGLE_BLUE : colorInt;\n\n const camSeed = Cam.fromInt(seedArgb),\n hue = camSeed.getHue(),\n chroma = Math.max(camSeed.getChroma(), Palette.ACCENT1_CHROMA);\n\n const { a1, a2, a3, n1, n2 } = Palette.getStyle(hue, chroma)[style];\n\n const accent1 = Shades.of(a1[0], a1[1]),\n accent2 = Shades.of(a2[0], a2[1]),\n accent3 = Shades.of(a3[0], a3[1]),\n neutral1 = Shades.of(n1[0], n1[1]),\n neutral2 = Shades.of(n2[0], n2[1]);\n\n const numberToHexColor = (colorNumber: number) => {\n return \"#\" + (colorNumber & 0xff_ff_ff).toString(16).padStart(6, \"0\");\n };\n\n const results = {\n system_accent1: accent1.map(element => numberToHexColor(element)),\n system_accent2: accent2.map(element => numberToHexColor(element)),\n system_accent3: accent3.map(element => numberToHexColor(element)),\n system_neutral1: neutral1.map(element => numberToHexColor(element)),\n system_neutral2: neutral2.map(element => numberToHexColor(element)),\n };\n\n return results;\n },\n};\n\nexport default Palette;\n","import Palette from \"./monet/palette.ts\";\n\nimport type { GenerationStyle, MaterialYouPalette } from \"./types.d.ts\";\n\nexport function generateMaterialYouPalette(seed: string, style?: GenerationStyle): MaterialYouPalette {\n return Palette.generate(seed, style);\n}\n","import { common, createEmphasize } from \"emphasize\";\nimport * as z from \"zod\";\n\nimport { formatCode } from \"../../../helpers/format-code.ts\";\nimport { join } from \"../../../utilities/path.ts\";\nimport { generateMaterialYouPalette } from \"./material-you/index.ts\";\n\nimport type { GenerationStyle } from \"./material-you/types.d.ts\";\nimport type { Plugin } from \"@staticbolt/core\";\n\nexport interface MaterialYouCliPluginOptions {\n /**\n * Build command name.\n *\n * @default \"palette\"\n */\n command?: string;\n\n /**\n * Build command aliases.\n *\n * @default [\"material-you\"]\n */\n aliases?: string[];\n\n /** The default value for the `--color` option. */\n color?: string;\n\n /**\n * The default value for the `--style` option.\n *\n * @default \"TONAL_SPOT\"\n */\n style?: GenerationStyle;\n\n /**\n * The default value for the `--format` option.\n *\n * @default \"css\"\n */\n format?: \"css\" | \"json\";\n\n /**\n * The default value for the `--raw` option.\n *\n * @default false\n */\n raw?: boolean;\n}\n\n/**\n * Adds the \"palette\" command (aliased \"material-you\"): generates a Material You palette from a seed color and prints it.\n *\n * Notes:\n *\n * - \"--color\" takes a full \"#RRGGBB\" hex; anything else is rejected.\n * - \"--format css\" prints formatted custom properties (\"--clr-*\", with the seed and style recorded), \"--format json\" prints the raw\n * tone arrays. The pure black and white ends are left out of the CSS.\n * - The output is syntax highlighted unless \"--raw\" is passed, which is what you want when redirecting into a file.\n * - Nothing is written to disk; the palette goes to stdout.\n */\nexport function materialYouCliPlugin(options: MaterialYouCliPluginOptions = {}): Plugin {\n const name = options.command ?? \"palette\";\n const aliases = options.aliases ?? [\"material-you\"];\n\n return {\n name: \"material-you-cli-plugin\",\n\n cli(config) {\n const materialYouPaletteCommand = this.defineSubcommand({\n name,\n aliases,\n meta: {\n description: \"Generate and print Material You palette.\",\n example: 'staticbolt palette --color \"#ff0000\" --style SPRITZ --raw > palette.css',\n },\n\n options: {\n color: {\n aliases: [\"c\"],\n schema: options.color ? z.string().default(options.color) : z.string(),\n meta: {\n description: \"The seed color to generate the palette. only `HEX` color is supported.\",\n },\n },\n style: {\n aliases: [\"s\"],\n schema: z\n .enum([\"SPRITZ\", \"TONAL_SPOT\", \"VIBRANT\", \"EXPRESSIVE\", \"RAINBOW\", \"FRUIT_SALAD\", \"CONTENT\", \"MONOCHROMATIC\"])\n .default(options.style ?? \"TONAL_SPOT\"),\n meta: {\n description: \"The style of the palette.\",\n },\n },\n format: {\n aliases: [\"f\"],\n schema: z.enum([\"css\", \"json\"]).default(options.format ?? \"css\"),\n meta: {\n description: \"The output format.\",\n },\n },\n raw: {\n aliases: [\"r\"],\n schema: z.boolean().default(options.raw ?? false),\n coerce: this.coerce.boolean,\n meta: {\n description: \"Print without highlighting.\",\n },\n },\n },\n });\n\n materialYouPaletteCommand.onExecute(async result => {\n const { color, style, format, raw } = result.options;\n\n if (!isHexColor(color)) {\n console.error(`Invalid color: ${color}\\nOnly HEX colors \\`#RRGGBB\\` are supported.`);\n return;\n }\n\n const palette = generateMaterialYouPalette(color, style);\n\n if (format === \"json\") {\n const jsonCode = JSON.stringify(palette, null, 2);\n\n if (raw) {\n console.log(JSON.stringify(palette, null, 2));\n return;\n }\n\n console.log(createEmphasize(common).highlight(\"json\", jsonCode).value);\n\n return;\n }\n\n const shades = [0, 10, ...Array.from({ length: 19 }, (_, index) => (index + 1) * 50), 990, 1000];\n let css = `:root {--clr-seed: ${shortenHexColor(color)};--style: \"${style}\";\\n\\n/* pure */\\n--clr-white: #fff;--clr-black: #000;`;\n\n for (const [shadeName, shadesArray] of Object.entries(palette)) {\n css += `\\n\\n/* ${shadeName.replace(\"system_\", \"\")} */\\n`;\n css += shadesArray\n .map((shade, index) => {\n if (index === 0 || index === shadesArray.length - 1) return \"\";\n return `--${shadeName.replace(\"system\", \"clr\").replace(/_/g, \"-\")}-${shades[index]}: ${shortenHexColor(shade)};`;\n })\n .join(\"\");\n }\n\n css += \"}\";\n\n const virtualPath = join(config.root ?? process.cwd(), \"palette.css\");\n const [formatResult, formatError] = await formatCode(css, virtualPath, \"css\");\n if (formatError) {\n console.error(formatError);\n return;\n }\n\n css = formatResult;\n\n if (raw) {\n console.log(css);\n return;\n }\n\n console.log(createEmphasize(common).highlight(\"css\", css).value);\n });\n\n this.addCommand(materialYouPaletteCommand);\n },\n };\n}\n\nfunction isHexColor(color: string) {\n return /^#([A-Fa-f0-9]{6})$/.test(color);\n}\n\n/** Shortens a hex color code if it can be reduced to a shorthand version. */\nfunction shortenHexColor(hexColor: string): string {\n const r = hexColor[1];\n const g = hexColor[3];\n const b = hexColor[5];\n\n if (hexColor[2] === r && hexColor[4] === g && hexColor[6] === b) {\n return `#${r}${g}${b}`;\n }\n\n return hexColor;\n}\n","import { statSync } from \"node:fs\";\nimport chokidar from \"chokidar\";\nimport * as z from \"zod\";\n\nimport { loadConfigFile } from \"../../../helpers/load-config.ts\";\nimport { App } from \"../../../main.ts\";\nimport { Log } from \"../../../utilities/logger.ts\";\nimport { basename } from \"../../../utilities/path.ts\";\nimport { DEVELOPMENT_SERVER_OVERRIDES } from \"../../core-plugins/development-server/development-server-plugin.ts\";\n\nimport type { DevelopmentServerOverrides } from \"../../core-plugins/development-server/development-server-plugin.ts\";\nimport type { AppConfig, Plugin } from \"@staticbolt/core\";\n\nexport interface ServeCliPluginOptions {\n /**\n * Serve command name.\n *\n * @default \"serve\"\n */\n command?: string;\n\n /**\n * Serve command aliases.\n *\n * @default [\"dev\"]\n */\n aliases?: string[];\n}\n\n/**\n * Adds the \"serve\" command (aliased \"dev\"): runs the pipeline in development mode, which is what starts the dev server.\n *\n * Notes:\n *\n * - The command owns the run. It forces development mode onto the config and creates its own App.\n * - Serving itself belongs to developmentServerPlugin; this only starts the app in the right mode.\n * - The config file is watched. When it changes it is loaded again, the running app is closed and a new one starts from the new\n * config. A config that fails to load leaves the running app alone; a new app that fails to start is closed, so nothing is\n * served until the next save. Plugins have to be created inside the config file: only that file is evaluated again, so plugin\n * objects imported from elsewhere would be the same ones the closed app used, and those are refused.\n */\nexport function serveCliPlugin(options: ServeCliPluginOptions = {}): Plugin {\n const name = options.command ?? \"serve\";\n const aliases = options.aliases ?? [\"dev\"];\n\n return {\n name: \"serve-cli-plugin\",\n\n cli(config, configPath, projectDirectory) {\n const serveCommand = this.defineSubcommand({\n name,\n aliases,\n meta: { description: \"Dev server for staticbolt.\" },\n options: {\n host: {\n schema: z.boolean().optional(),\n coerce: this.coerce.boolean,\n meta: { description: \"Listen on every address, so the site is reachable from other devices on the network.\" },\n },\n },\n });\n\n serveCommand.onExecute(({ options }) =>\n new DevelopmentRun(config, configPath, projectDirectory, { host: options.host }).start()\n );\n\n this.addCommand(serveCommand);\n },\n };\n}\n\n/** The app running in development mode, replaced by a fresh one whenever the config file changes. */\nclass DevelopmentRun {\n #app: App;\n #config: AppConfig;\n\n readonly #configPath: string;\n readonly #configName: string;\n readonly #projectDirectory: string;\n readonly #overrides: DevelopmentServerOverrides;\n\n /** Restarts run one at a time; a change that lands during one waits its turn. */\n #restartQueue = Promise.resolve();\n\n /** The most recent change, so a queued restart can be skipped once a newer change is waiting behind it. */\n #latestChange = 0;\n\n /** When the config file was last written, as of the last time it was loaded. */\n #configModified: number | undefined;\n\n constructor(config: AppConfig, configPath: string, projectDirectory: string, overrides: DevelopmentServerOverrides) {\n config.production = false;\n\n this.#config = config;\n this.#configPath = configPath;\n this.#configName = basename(configPath);\n this.#projectDirectory = projectDirectory;\n this.#overrides = overrides;\n this.#app = this.#createApp(config);\n this.#configModified = this.#modifiedTime();\n }\n\n #createApp(config: AppConfig): App {\n const app = new App(config, this.#configPath);\n app.pluginData[DEVELOPMENT_SERVER_OVERRIDES] = this.#overrides;\n\n return app;\n }\n\n async start() {\n // A save is only picked up once the file has held still, so a half-written config is never loaded\n const watcher = chokidar.watch(this.#configPath, {\n ignoreInitial: true,\n awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 20 },\n });\n\n watcher.on(\"change\", () => this.#queueRestart()).on(\"add\", () => this.#queueRestart());\n\n // A save during the run queues behind it instead of being missed\n this.#restartQueue = this.#app.run().catch(async error => {\n Log.error(\"Failed to start the dev server:\");\n console.error(error instanceof Error && error.cause ? error.message : error);\n\n await watcher.close();\n await this.#app.close();\n process.exitCode = 1;\n });\n\n await this.#restartQueue;\n\n this.#restartIfModified();\n }\n\n #queueRestart() {\n const change = ++this.#latestChange;\n\n this.#restartQueue = this.#restartQueue.then(async () => {\n if (change === this.#latestChange) await this.#restart();\n });\n }\n\n /**\n * The app starting its own watcher makes the file system drop events for a moment (libuv rebuilds its stream), so a save that\n * happened while the app was starting is caught by looking at the file instead.\n */\n #restartIfModified() {\n if (this.#modifiedTime() !== this.#configModified) {\n this.#queueRestart();\n }\n }\n\n #modifiedTime(): number | undefined {\n return statSync(this.#configPath, { throwIfNoEntry: false })?.mtimeMs;\n }\n\n async #restart() {\n Log.info(`Config file \"${this.#configName}\" changed, restarting`);\n\n this.#configModified = this.#modifiedTime();\n\n const nextConfig = await this.#loadNextConfig();\n if (!nextConfig) return;\n\n let nextApp: App;\n try {\n nextApp = this.#createApp(nextConfig);\n } catch (error) {\n Log.error(\"Failed to create the app, keeping the current server:\");\n console.error(error);\n return;\n }\n\n try {\n await this.#app.close();\n this.#app = nextApp;\n this.#config = nextConfig;\n\n await nextApp.run();\n this.#restartIfModified();\n } catch (error) {\n Log.error(`Restart failed, nothing is served until \"${this.#configName}\" is fixed and saved again:`);\n console.error(error);\n await this.#app.close();\n }\n }\n\n /** The config to restart with, or nothing when the current server is to be kept. */\n async #loadNextConfig(): Promise<AppConfig | undefined> {\n const [nextConfig, configError] = await loadConfigFile(this.#configPath, this.#projectDirectory);\n if (configError) {\n Log.error(`Failed to load \"${this.#configName}\", keeping the current server:`);\n console.error(configError);\n return;\n }\n\n const reusedPlugins = this.#reusedPlugins(nextConfig);\n if (reusedPlugins.length > 0) {\n const names = reusedPlugins.map(plugin => `\"${plugin.name}\"`).join(\", \");\n Log.error(\n `Keeping the current server: ${names} are the same plugin objects as before. Create plugins inside \"${this.#configName}\" so a reload gets fresh ones.`\n );\n return;\n }\n\n nextConfig.production = false;\n\n return nextConfig;\n }\n\n /**\n * A plugin object belongs to one app. Plugins imported from another file come back as the same objects, since only the config\n * file itself is evaluated again.\n */\n #reusedPlugins(nextConfig: AppConfig): Plugin[] {\n const currentPlugins = new Set((this.#config.plugins ?? []).flat());\n\n return (nextConfig.plugins ?? []).flat().filter(plugin => currentPlugins.has(plugin));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,IAAa,qBAAb,MAAgC;CAC9B,AAASA,2BAAW,IAAI,IAAyB;CACjD,AAASC,4BAAY,IAAI,IAAY;CACrC,AAASC;CACT,AAASC;CAET,YAAY,KAAU,MAAc;EAClC,KAAKD,OAAO;EACZ,KAAKC,QAAQ;CACf;CAEA,MAAM,SAAS,cAAkD;EAC/D,MAAM,SAAS,KAAKH,SAAS,IAAI,aAAa,QAAQ;EACtD,IAAI,QACF,OAAO;EAGT,IAAI,KAAKE,KAAK,YAAY,IAAI,YAAY,GACxC,uBAAO,IAAI,IAAI;EAGjB,IAAI,KAAKD,UAAU,IAAI,aAAa,QAAQ,GAC1C,uBAAO,IAAI,IAAI;EAGjB,KAAKA,UAAU,IAAI,aAAa,QAAQ;EAExC,MAAM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