@staticbolt/core 1.0.0-beta.16 → 1.0.0-beta.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cli/index.d.mts +1 -1
- package/lib/index.d.mts +5 -13
- package/lib/index.d.mts.map +1 -1
- package/lib/index.mjs +1 -1
- package/lib/plugins/index.d.mts +0 -1
- package/lib/plugins/index.d.mts.map +1 -1
- package/lib/plugins/index.mjs +70 -36
- package/lib/plugins/index.mjs.map +1 -1
- package/lib/{utilities-ubLQ-AAc.mjs → utilities-CdEDdL4I.mjs} +5 -3
- package/lib/{utilities-ubLQ-AAc.mjs.map → utilities-CdEDdL4I.mjs.map} +1 -1
- package/package.json +23 -23
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["#depsMap","#visiting","#app","#root","#collectPackageMetadataDeps","#collect","#resolveSource","c","bundleFunction","traverse","normalizePackageName","generator","resolveStaticValue","resolveStaticValue","c","placeholderRe","executeExpression","parse","placeholderRe","z","parseYaml","swcMinify"],"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/helpers/format-code.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/plugins/write-files/write-files-plugin.ts","../../src/helpers/execute-js-in-vm.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/plugins/html-bundle-style/html-bundle-style-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/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/minify-html.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/plugins/core-plugins/script-metadata/minify-script.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/minify-style.ts","../../src/parsers/css-parser.ts","../../src/plugins/core-plugins/style-metadata/style-loader.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/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\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 // ------ Report missing files ------\n const missingFiles = usedFiles.difference(availableFiles);\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.size > 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 const relativePath = relative(this.outdir, unused);\n\n const isExcluded = isPathMatch(relativePath, { include: exclude, root: this.outdir });\n if (isExcluded) continue;\n\n if (isRemoveUnused) unlinkSync(unused);\n\n unusedFilesLog.push(c.yellow(join(basename(this.outdir), relativePath)));\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\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/**\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 { minify_sync } from \"terser\";\n\nimport { 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 calcPackageOutPath,\n diffSpecifiers,\n generateStdinString,\n getChunkName,\n getCustomPackagePath,\n isNodeModulesPath,\n matchesPackage,\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 * Whether to use Terser for minification to reduce the final bundle size.\n *\n * @default false\n */\n minifyUsingTerser?: boolean;\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 each `node_modules` package and its dependencies into separate files under `packagesDir`. The plugin scans files for\n * imports and uses esbuild's tree-shaking capabilities to generate the bundles.\n */\nexport function bundlePackagesPlugin(options: BundlePackagesOptions = {}): Plugin {\n const packagesOutputDirection = options.packagesDir ?? \"./packages\";\n const shouldMinifyUsingTerser = options.minifyUsingTerser ?? false;\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 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 // For already resolved `node_modules` sources, keep them as is\n if (isNodeModulesPath(join(dirname(filePath), link), this.root)) {\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 }\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 // Already bundled\n const packageMetadataExists = this.findMetadata({ type: METADATA_TYPES.Package, id: chunkName });\n if (packageMetadataExists) 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 const packageOutputPath = calcPackageOutPath(chunkName, packagesOutputDirection);\n\n const packageMetadata: PackageMetadata = {\n type: METADATA_TYPES.Package,\n packageName: chunkName,\n code: \"\",\n filePath: packageOutputPath,\n id: chunkName,\n directDependencies: new Set(),\n };\n\n const [bundledCode, bundleError] = await bundlePackage({\n contents,\n resolveDir: this.root,\n outfile: packageOutputPath,\n packageName: chunkName,\n minify: this.production && !shouldMinifyUsingTerser,\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\n this.addMetadata(packageMetadata);\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: !shouldMinifyUsingTerser && 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: !shouldMinifyUsingTerser,\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 // Minify using terser\n if (!shouldMinifyUsingTerser) return;\n\n const packages = this.filterMetadata<PackageMetadata>({ type: METADATA_TYPES.Package });\n\n for (const packageMetadata of packages) {\n const result = minify_sync(packageMetadata.code);\n if (!result.code) {\n printFormattedError(`Failed to minify package \"${packageMetadata.packageName}\"`);\n continue;\n }\n\n packageMetadata.code = result.code;\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\";\nimport sharp from \"sharp\";\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\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 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\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\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 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 { name, matchStartIndex, matchEndIndex, args } = parseFunctionCall(style, `${cssFunctionPrefix}.+`);\n if (matchStartIndex < 0) return;\n\n const easeFunctionName = name.replace(cssFunctionPrefix, \"\");\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 node.setAttribute(\n \"style\",\n style.slice(0, Math.max(0, matchStartIndex)) + easeFunctionOrString + style.slice(Math.max(0, matchEndIndex))\n );\n\n return;\n }\n\n try {\n const linearFunction = convertEasingFunctionToLinearFN(easeFunctionOrString(...args), samples);\n node.setAttribute(\n \"style\",\n style.slice(0, Math.max(0, matchStartIndex)) + linearFunction + style.slice(Math.max(0, matchEndIndex))\n );\n } catch {\n printFmtError(\"Error generating easing function\", {\n function: customEasePlugin,\n filePath: inputMetadata.id,\n });\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 value = declaration.value;\n\n const { name, matchStartIndex, matchEndIndex, args } = parseFunctionCall(value, `${cssFunctionPrefix}.+`);\n if (matchStartIndex < 0) return;\n\n const easeFunctionName = name.replace(cssFunctionPrefix, \"\");\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 declaration.value =\n value.slice(0, Math.max(0, matchStartIndex)) + easeFunctionOrString + value.slice(Math.max(0, matchEndIndex));\n\n return;\n }\n\n try {\n const linearFunction = convertEasingFunctionToLinearFN(easeFunctionOrString(...args), samples);\n declaration.value =\n value.slice(0, Math.max(0, matchStartIndex)) + linearFunction + value.slice(Math.max(0, matchEndIndex));\n } catch {\n printFmtError(\"Error generating easing function\", {\n function: customEasePlugin,\n filePath: inputMetadata.id,\n });\n }\n });\n }\n }\n },\n };\n}\n\ninterface ParseFunctionCallResult {\n name: string;\n matchStartIndex: number;\n matchEndIndex: number;\n args: unknown[];\n}\n\n/** - Parse a string representing a function call and get its arguments and name */\nfunction parseFunctionCall(code: string, functionNameMatcher: string): ParseFunctionCallResult {\n const re = new RegExp(String.raw`(${functionNameMatcher})\\s*\\(\\s*(.*)\\s*\\)`);\n\n const match = re.exec(code);\n if (!match) {\n return { name: \"\", matchStartIndex: -1, matchEndIndex: -1, args: [] };\n }\n\n const name = match[1];\n if (!name) {\n return { name: \"\", matchStartIndex: -1, matchEndIndex: -1, args: [] };\n }\n\n const argumentsString = match[2];\n if (!argumentsString) {\n return { name, matchStartIndex: match.index, matchEndIndex: match.index + match[0].length, args: [] };\n }\n\n let arguments_: unknown[] = [];\n try {\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n const function_ = new Function(`return [${argumentsString}]`) as () => unknown[];\n arguments_ = function_();\n } catch {\n console.warn(`Failed to parse function call: ${code}`);\n }\n\n return { name, matchStartIndex: match.index, matchEndIndex: match.index + match[0].length, args: arguments_ };\n}\n","import type { ValueOrError } from \"../utilities/value-or-error.ts\";\nimport type { Options } from \"prettier\";\n\ntype Lang = \"js\" | \"html\" | \"css\" | \"markdown\" | \"ts\" | \"json\";\n\nlet prettierConfig: Options | undefined;\n\n/** - Format code using Prettier */\nexport async function formatCode(code: string, filePath: string, lang: Lang): Promise<ValueOrError<string>> {\n const { format } = await import(\"prettier\");\n\n try {\n await loadPrettier(filePath);\n const options = prettierConfig ?? { printWidth: 130 };\n\n const parser = lang === \"js\" ? \"babel\" : lang === \"ts\" ? \"typescript\" : lang;\n const formattedCode = await format(code, { ...options, parser, filepath: filePath });\n\n return [formattedCode, null];\n } catch {\n return [null, new Error(`Prettier formatting failed for '${filePath}'`)];\n }\n}\n\nasync function loadPrettier(filePath: string) {\n if (prettierConfig) {\n return;\n }\n\n const { resolveConfig } = await import(\"prettier\");\n const organizeImports = await import(\"prettier-plugin-organize-imports\");\n\n try {\n const options = (await resolveConfig(filePath)) ?? { printWidth: 130 };\n if (!options.plugins) options.plugins = [];\n\n if (!options.plugins.includes(\"prettier-plugin-jsdoc\")) {\n options.plugins.push(organizeImports.default);\n }\n\n prettierConfig = options;\n } catch {\n return;\n }\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\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\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\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\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: true,\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 = 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\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\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\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\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\";\nimport { generateSW } from \"workbox-build\";\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 * Please don't forget to register the service worker in your HTML file.\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 */\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 { 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\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 { optimize, type Config } from \"svgo\";\n\nimport { valueOrError } from \"../../utilities/value-or-error.ts\";\n\nfunction optimizeSvgUnsafe(svgCode: string, config?: Config) {\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 * Optimize SVG files and SVG tags in HTML using `svgo`.\n *\n * For CSS inlined SVGs, use a PostCSS plugin like `cssnano` instead.\n *\n * **Production Only**\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 return {\n name: \"svgo\",\n\n setup() {\n this.pluginData.optimizedSvgList ??= new Set<string>();\n },\n\n 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 const [svg, error] = optimizeSvg(svgString, svgoConfig);\n if (error) {\n printFmtError(\"Failed to optimize svg using `svgo`\", error, { filePath, node });\n continue;\n }\n\n node.replaceWith(svg);\n }\n\n return;\n }\n },\n\n 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] = 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\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\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 },\n\n async transform(inputMetadata) {\n const allPlugins = [...plugins, ...postcssConfig.plugins];\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\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\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 write(metadata) {\n if (!isWebManifestMetadata(metadata)) return;\n\n await this.rebase(metadata, join(this.root, outfile));\n },\n };\n}\n","import { cpSync, mkdirSync, rmSync, writeFileSync } from \"node:fs\";\n\nimport { isBinaryAssetMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join, isPathMatch } from \"../../utilities/path.ts\";\n\nimport type { 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 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\nexport function writeFilesPlugin(options: WriteFilesOptions): Plugin {\n const include = options.include ?? [\"**/*\"];\n const ignore = options.exclude ?? [];\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 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(metadata) {\n if (!this.production) return;\n\n if (this.emitExclude.has(metadata)) return;\n\n const isIncluded = isPathMatch(metadata.id, { include, ignore, root: this.root });\n if (!isIncluded) return;\n\n if (metadata.filePath.startsWith(\"../\")) {\n this.log.error(`file path \"${metadata.filePath}\" is outside of the output directory \"${this.outdir}\". Skipping...`);\n return;\n }\n\n const shouldMinify = shouldMinifyFile(metadata.id, this.root);\n const shouldFormat = shouldFormatFile(metadata.id, this.root);\n\n if (shouldMinify && shouldFormat) {\n this.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(this.root, metadata.id);\n const copyTo = join(this.outdir, metadata.filePath);\n cpSync(copyFrom, copyTo, { recursive: true });\n return;\n }\n\n // stringify\n const code = await this.stringify(metadata, { format: shouldFormat, minify: shouldMinify });\n if (typeof code !== \"string\") {\n this.log.error(`Failed to stringify \"${metadata.id}\"`);\n return;\n }\n\n if (!code) {\n this.log.warn(`Writing empty file \"${metadata.filePath}\"`);\n }\n\n // write\n const outputFile = join(this.outdir, metadata.filePath);\n mkdirSync(dirname(outputFile), { recursive: true });\n writeFileSync(outputFile, code, \"utf8\");\n },\n };\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport vm from \"node:vm\";\n\nimport { Log } from \"../utilities/logger.ts\";\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 */\n root: string;\n\n /** The entry file, should match the key of the `transformedScripts` */\n entryFile: string;\n\n /** A function to get the code of the entry file */\n getCode(filePath: string): string | void | Promise<string | void>;\n\n /** A plain object to provide global context to the VM */\n context?: Record<string, unknown>;\n\n /** The html content of the `document` API */\n html?: string;\n}\n\ninterface ExecuteJsInVmResult {\n output: Record<string, unknown>;\n exports: { [k: string]: unknown };\n dom: JSDOM | undefined;\n}\n\nasync function executeJsInVmUnsafe(options: ExecuteJsInVmOptions): Promise<ExecuteJsInVmResult> {\n const { root, entryFile, context: contextObject = {}, html } = options;\n\n let dom: JSDOM | undefined;\n if (html) {\n const { JSDOM, VirtualConsole } = await import(\"jsdom\");\n dom = html ? new JSDOM(html, { virtualConsole: new VirtualConsole(), url: \"http://localhost/\" }) : undefined;\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, Object.assign({ ___output: {}, console }, contextObject));\n\n const context = vm.createContext(window);\n\n /** - Save modules in memory to avoid creating a new one for the same file */\n const modules: Record<string, vm.SourceTextModule | vm.SyntheticModule> = {};\n\n // load the entry module\n const script = await options.getCode(entryFile);\n if (!script) {\n Log.error(`[executeJsInVM] can't find the script '${entryFile}'`);\n return { output: context.___output as Record<string, unknown>, exports: {}, dom };\n }\n\n const module = new vm.SourceTextModule(script, {\n context,\n identifier: entryFile,\n importModuleDynamically,\n initializeImportMeta,\n });\n modules[entryFile] = module;\n\n const baseMetaUrl = \"http://localhost:3000\";\n function initializeImportMeta(meta: ImportMeta, referencingModule: vm.Module) {\n let id = referencingModule.identifier;\n\n if (extname(id) === \".html\") {\n id = dirname(id) + \"/\";\n }\n\n meta.resolve = url => {\n return new URL(join(id, url), baseMetaUrl).href;\n };\n\n meta.url = new URL(id, baseMetaUrl).href;\n }\n\n async function importModuleDynamically(specifier: string, referrer: vm.Module): Promise<vm.Module> {\n const m = await linker(specifier, referrer);\n if (m.status === \"unlinked\") await m.link(linker);\n else if (m.status === \"linked\") await m.evaluate();\n return m;\n }\n\n async function linker(specifier: string, referencingModule: vm.Module): Promise<vm.Module> {\n const isNativeModule = specifier.startsWith(\"node:\");\n\n const resolveName = isNativeModule ? specifier : join(dirname(referencingModule.identifier), specifier);\n\n // resolve json files and serialize it\n if (extname(resolveName) === \".json\") {\n const jsonPath = join(root, resolveName);\n if (!existsSync(jsonPath)) {\n throw new Error(`[executeJsInVM] can't find the file '${resolveName}'`);\n }\n\n let jsonString = readFileSync(jsonPath, \"utf8\");\n jsonString = \"const __json = \" + jsonString + \";export default __json;\";\n const module = new vm.SourceTextModule(jsonString, { context, identifier: resolveName });\n modules[resolveName] = module;\n return module;\n }\n\n const isLoaded = Object.hasOwn(modules, resolveName);\n if (isLoaded) {\n return modules[resolveName];\n }\n\n if (isNativeModule) {\n const builtIn = (await import(specifier)) as Record<string, unknown>;\n const exportNames = Object.keys(builtIn);\n\n const module = new vm.SyntheticModule(\n exportNames,\n function () {\n for (const key of exportNames) this.setExport(key, builtIn[key]);\n },\n { context, identifier: resolveName }\n );\n\n modules[resolveName] = module;\n\n return module;\n }\n\n const moduleScript = await options.getCode(resolveName);\n if (!moduleScript) {\n Log.error(`[executeJsInVM] can't find the script '${resolveName}' in the transformed scripts map`);\n throw new Error(`can't resolve module '${specifier}' from '${referencingModule.identifier}'`);\n }\n\n const module = new vm.SourceTextModule(moduleScript, {\n context: referencingModule.context,\n identifier: resolveName,\n importModuleDynamically,\n initializeImportMeta,\n });\n\n modules[resolveName] = module;\n\n return module;\n }\n\n await module.link(linker);\n await module.evaluate();\n\n const exports = Object.fromEntries(Object.entries(module.namespace));\n\n return { output: context.___output as Record<string, unknown>, exports, dom };\n}\n\nconst executeJsInVM = valueOrError(executeJsInVmUnsafe);\n\nexport { executeJsInVM };\n","import vm from \"node:vm\";\n\nimport { executeJsInVM } from \"../../helpers/execute-js-in-vm.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, isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.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 contextAttribute?: string;\n}\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 let isVmEnabled = true;\n\n return {\n name: \"html-build-time-script\",\n\n setup() {\n if (vm.SourceTextModule) {\n return;\n }\n\n isVmEnabled = false;\n printFmtError(\n \"Script execution requires the `node:vm` module, which is currently unavailable.\",\n \"\\nStart Node.js with the `--experimental-vm-modules` flag to enable it.\"\n );\n },\n\n async postTransform() {\n for (const metadata of this.metadataList) {\n if (!isHtmlMetadata(metadata)) {\n continue;\n }\n\n if (!isVmEnabled) {\n for (const node of metadata.ast.querySelectorAll(query)) {\n node.remove();\n }\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 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 });\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\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: \"script\",\n attributes: [\n {\n name: buildAttribute,\n description: \"This attribute is used to mark the script as build-time script.\",\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 },\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}\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 isExternalCheck: (strings: string) => boolean;\n}\n\nexport async function bundleScriptWithEsbuild(this: App, options: Options): Promise<ValueOrError<string>> {\n const { contents, entryPoint, outfile, 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: \"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 { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { isHtmlMetadata, isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { basename, dirname, join, isPathMatch, normalize, relative, replaceExtension } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { bundleScriptWithEsbuild } from \"./esbuild-bundle.ts\";\n\nimport type { MetadataSource, 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 * @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/**\n * A plugin that bundles script tags in HTML files using esbuild.\n *\n * Bundling is opt-in per script tag via the \"bundle\" attribute (configurable via HtmlBundleScriptOptions.bundleAttribute).\n *\n * Inlining vs. separate file\n *\n * - Inline script, no \"bundle-out\" attribute: bundled output replaces the tag content in place.\n * - Inline script, \"bundle-out\" attribute set: tag content is cleared and \"src\" is set to the output file.\n * - \"src\" script, no \"bundle-out\" attribute: bundle is written to \"{filename}.bundle.js\" and \"src\" is updated.\n * - \"src\" script, \"bundle-out\" attribute set: bundle is written to the specified path and \"src\" is updated.\n *\n * Externals resolution\n *\n * Glob patterns in HtmlBundleScriptOptions.externals and HtmlBundleScriptOptions.externalsExclude are matched against each\n * resolved module path. A module is treated as external if it matches \"externals\" and does not match \"externalsExclude\".\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\n const query = `script[${bundleAttribute}]`;\n\n const printFmtError = PrintFormattedError.create({ function: htmlBundleScriptPlugin });\n\n return {\n name: \"html-bundle-script\",\n\n // Collects script tags that declare an explicit output path so the build\n // system can track and rebase those paths when needed.\n sourcesProvider(metadata) {\n if (!this.production || !isHtmlMetadata(metadata)) return;\n\n const sources: MetadataSource[] = [];\n\n // eslint-disable-next-line unicorn/require-css-escape\n const elements = metadata.ast.querySelectorAll(`script[${bundleOutAttribute}]`);\n for (const node of elements) {\n const source = node.attrs[bundleOutAttribute];\n if (!source) continue;\n\n const scriptType = node.getAttribute(\"type\");\n if (!isScriptType(scriptType)) continue;\n\n sources.push({\n node,\n get source() {\n return source;\n },\n set source(newValue) {\n node.setAttribute(bundleOutAttribute, newValue);\n },\n });\n }\n\n // Fixed: was missing the return, so sources were silently dropped.\n return sources;\n },\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 bundleOut = node.getAttribute(bundleOutAttribute);\n const externalsAttributeValue = node.getAttribute(externalsAttribute);\n const externalsExcludeAttributeValue = node.getAttribute(externalsExcludeAttribute);\n\n node.removeAttribute(bundleAttribute);\n node.removeAttribute(bundleOutAttribute);\n node.removeAttribute(externalsAttribute);\n node.removeAttribute(externalsExcludeAttribute);\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\" when no explicit path is given.\n outfile = bundleOut ?? normalize(replaceExtension(basename(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.info(`The entry point \"${entryPoint}\" is already bundled in \"${outfile}\", skipping...`);\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 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 attributes: [\n {\n name: bundleAttribute,\n description: \"Enable script bundling.\",\n },\n {\n name: bundleOutAttribute,\n description:\n \"Specify the output path for bundled scripts relative to the output directory.\" +\n \"\\nIf the script has a `src` attribute, the output path will default to `{filename}.bundle.js`.\" +\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 },\n ],\n };\n },\n };\n}\n\n// Splits a semicolon-separated attribute value into an array of trimmed glob patterns.\n// Returns undefined if the input is not a string, and an empty array for an empty string.\nfunction parsePatterns(string: string | null): string[] | undefined {\n if (typeof string !== \"string\") return;\n\n if (!string) return [];\n\n string = string.trim();\n\n return string.split(\";\").flatMap(p => {\n const trimmed = p.trim();\n return trimmed ? [trimmed] : [];\n });\n}\n","import { readFileSync } from \"node:fs\";\nimport postcssImport from \"postcss-import\";\n\nimport { processCss } from \"../../ast-utilities/postcss-utils/process-css.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, relative, resolve } 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\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 return {\n name: \"html-bundle-style\",\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 [, processError] = await processCss(\n styleMetadata.ast,\n [\n postcssImport({\n load: async absoluteFilePath => {\n const source = relative(this.root, absoluteFilePath);\n\n const metadata = this.findMetadata({ filePath: source });\n if (!metadata) {\n return readFileSync(absoluteFilePath, \"utf8\");\n }\n\n return await this.stringify(metadata);\n },\n }),\n ],\n { from: resolve(this.root, metadata.filePath) }\n );\n\n if (processError !== null) {\n printFmtError(processError, { function: htmlBundleStylePlugin, node, filePath: metadata.id });\n }\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: \"link\",\n attributes: [{ name: bundleAttribute, description: \"Enable style bundling.\" }],\n },\n {\n name: \"style\",\n attributes: [{ name: bundleAttribute, description: \"Enable style bundling.\" }],\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\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 const elements = metadata.ast.querySelectorAll(tag);\n\n for (const node of elements) {\n node.replaceWith(node.innerHTML.trim());\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 { 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\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 && scriptType !== \"module\") {\n printFmtError(\"IIFE should only be used with global scripts.\", { level: \"warning\" });\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 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 },\n ],\n },\n ],\n };\n },\n };\n}\n","import { isScriptType } from \"../../helpers/is-script-type.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\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 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 ],\n },\n ],\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}.css`);\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 { 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\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 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 },\n ],\n },\n ],\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 script metadata\")];\n }\n\n return [metadata, null];\n}\n","import { 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\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 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 },\n ],\n },\n ],\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}.css`);\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 script metadata\")];\n }\n\n return [metadata, null];\n}\n","import { DependencyTracker } from \"../../helpers/dependency-tracker.ts\";\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 { 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\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 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 result.push({\n get source() {\n return source;\n },\n set source(newValue) {\n inlineTag.setAttribute(sourceAttribute, newValue);\n },\n });\n }\n\n return result;\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 sourceRelative = join(dirname(metadata.filePath), source);\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 },\n ],\n },\n ],\n };\n },\n };\n}\n","import { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\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\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 },\n {\n name: whereAttribute,\n description: \"The position of the inserted element.\",\n values: [{ name: \"beforebegin\" }, { name: \"afterbegin\" }, { name: \"beforeend\" }, { name: \"afterend\" }],\n },\n ],\n },\n ],\n };\n },\n };\n}\n","import type { ValueOrError } from \"../../utilities/value-or-error.ts\";\n\n/** (any){{any}} */\nconst placeholderRe = /(\\\\)?{{\\s*([\\s\\S]*?)\\s*}}/g;\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, 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, type HTMLElement } from \"../../types/common.ts\";\nimport { 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\";\n\nimport type { IAttributeData, ITagData, MetadataSource, Plugin } from \"@staticbolt/core\";\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 \"data\"\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\ninterface HtmlLayoutMetadata extends HtmlMetadata {\n hash: string;\n}\n\nexport function htmlLayoutPlugin(options: HtmlLayoutOptions = {}): Plugin {\n const layoutTags = options.tags ?? [\"layout\", \"part\"];\n const sourceAttribute = options.layoutSourceAttribute ?? \"src\";\n const dataSourceAttribute = options.dataSourceAttribute ?? \"dataSource\";\n const dataJsonAttribute = options.dataJsonAttribute ?? \"dataJson\";\n const alwaysIncludeAttribute = options.alwaysIncludeAttribute ?? \"always-include\";\n const addAttributeAttribute = options.addAttributeAttribute ?? \"add-attr\";\n const removeAttributeAttribute = options.removeAttributeAttribute ?? \"remove-attr\";\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 const fileName = basename(path);\n return layoutTags.some(tag => fileName.endsWith(`.${tag}.html`));\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>>(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>>(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 = calculateHash(node, sourceAttribute);\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 // Add and remove attributes\n const addAttributePrefix = `${addAttributeAttribute}-`;\n const removeAttributePrefix = `${removeAttributeAttribute}-`;\n\n const elements = layoutMetadata.ast.querySelectorAll(\"*\");\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(addAttributePrefix)) {\n const targetAttribute = name.slice(addAttributePrefix.length);\n element.removeAttribute(name);\n if (value.trim() && value.trim() !== \"false\") {\n element.setAttribute(targetAttribute, \"\");\n }\n continue;\n }\n\n if (name.startsWith(removeAttributePrefix)) {\n const targetAttribute = name.slice(removeAttributePrefix.length);\n element.removeAttribute(name);\n if (value.trim() && value.trim() !== \"false\") {\n element.removeAttribute(targetAttribute);\n }\n }\n }\n }\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 // When using the layout multiple times in the same file, scripts/styles tags should only be\n // included once — unless the tag carries the always-include attribute, in which case it is\n // included for every layout instance (useful for per-instance build-time scripts).\n const scriptsAndStyles = layoutHtmlMetadata.ast.querySelectorAll(\"script,style\");\n for (const scriptOrStyle of scriptsAndStyles) {\n const id = scriptOrStyle.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!id) continue;\n\n if (scriptOrStyle.hasAttribute(alwaysIncludeAttribute)) {\n scriptOrStyle.removeAttribute(alwaysIncludeAttribute);\n continue;\n }\n\n const isScript = scriptOrStyle.tagName === \"SCRIPT\";\n const exitsMetadata = metadata[isScript ? \"scriptsMetadataList\" : \"stylesMetadataList\"].get(id);\n\n if (exitsMetadata) {\n layoutHtmlMetadata[isScript ? \"scriptsMetadataList\" : \"stylesMetadataList\"].delete(id);\n scriptOrStyle.remove();\n }\n }\n\n // When using the layout multiple times in the same file,\n // include scripts/stylesheets with links only once\n const scriptsAndLinks = layoutHtmlMetadata.ast.querySelectorAll('script[src], link[rel=\"stylesheet\"]');\n for (const scriptOrLink of scriptsAndLinks) {\n if (scriptOrLink.hasAttribute(alwaysIncludeAttribute)) {\n scriptOrLink.removeAttribute(alwaysIncludeAttribute);\n continue;\n }\n\n const isScript = scriptOrLink.tagName === \"SCRIPT\";\n const attribute = isScript ? \"src\" : \"href\";\n\n const layoutSourceRelative = join(dirname(layoutHtmlMetadata.filePath), scriptOrLink.attributes[attribute]);\n const selector = isScript ? \"script[src]\" : 'link[rel=\"stylesheet\"]';\n\n const isAlreadyExists = metadata.ast.querySelectorAll(selector).some(element => {\n const elementSourceRelative = join(dirname(metadata.filePath), element.attributes[attribute]);\n return elementSourceRelative === layoutSourceRelative;\n });\n\n if (isAlreadyExists) {\n scriptOrLink.remove();\n }\n }\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 // Fill slots\n const children = node.querySelectorAll(\":scope > *\");\n for (const element of children) {\n if (element.nodeType !== NodeType.ELEMENT_NODE) continue;\n\n // unnamed slots (default)\n if (!element.hasAttribute(\"slot\")) {\n const defaultSlots = layoutHtmlMetadata.ast.querySelectorAll(`slot:not([name])`);\n if (defaultSlots.length === 0) {\n printFmtError(`No default slot in layout file:`, layoutRelativePath, { node: element });\n continue;\n }\n\n for (const defaultSlot of defaultSlots) {\n defaultSlot.insertAdjacentHTML(\"beforeend\", element.outerHTML);\n }\n\n continue;\n }\n\n // named slots\n const slotName = element.getAttribute(\"slot\");\n if (!slotName) continue;\n\n // eslint-disable-next-line unicorn/require-css-escape\n const namedSlots = layoutHtmlMetadata.ast.querySelectorAll(`slot[name=\"${slotName}\"]`);\n if (namedSlots.length === 0) {\n printFmtError(`No slots with name \"${slotName}\" in layout file:`, layoutRelativePath, {\n node: element,\n });\n continue;\n }\n\n element.removeAttribute(\"slot\");\n\n for (const namedSlot of namedSlots) {\n namedSlot.insertAdjacentHTML(\"beforeend\", element.outerHTML);\n }\n }\n\n // remove slot outerHTML\n for (const slot of layoutHtmlMetadata.ast.querySelectorAll(\"slot\")) {\n slot.replaceWith(slot.innerHTML.trim());\n }\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 const tag = Object.keys(metadata.ast.frontmatter).find(key => layoutTags.includes(key));\n if (!tag) return;\n\n let attributesString = \"\";\n for (const [key, value] of Object.entries(metadata.ast.frontmatter)) {\n attributesString += `${key === tag ? sourceAttribute : key}=\"${value}\" `;\n }\n\n const openTag = `<${tag} ${attributesString}>`;\n const closeTag = `</${tag}>`;\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const oldRender = metadata.ast.render;\n\n metadata.ast.render = async () => {\n const html = await oldRender();\n return openTag + html + closeTag;\n };\n\n return;\n }\n },\n\n lspHtmlData() {\n const attributes: IAttributeData[] = [\n { name: sourceAttribute, description: \"The path to the layout to use.\" },\n { name: dataSourceAttribute, description: \"The path for a JSON file containing data for the layout.\" },\n { name: dataJsonAttribute, description: \"The layout data in JSON format.\" },\n ];\n\n const alwaysInclude = {\n name: alwaysIncludeAttribute,\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 };\n\n const tags: ITagData[] = [\n { name: \"script\", attributes: [alwaysInclude] },\n { name: \"link\", attributes: [alwaysInclude] },\n { name: \"style\", attributes: [alwaysInclude] },\n ];\n\n for (const tag of layoutTags) {\n tags.push({ name: tag, description: `This tag allows inlining a \\`${tag}\\` file.`, attributes });\n }\n\n return {\n version: 1.1,\n tags,\n globalAttributes: [\n {\n name: addAttributeAttribute,\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: removeAttributeAttribute,\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}\n\nfunction calculateHash(node: HTMLElement, sourceAttribute: string): string {\n let hash = \"\";\n\n for (const [attribute, value] of Object.entries(node.attributes)) {\n if (attribute === sourceAttribute) continue;\n hash += `${attribute}=${value}`;\n }\n\n return hash;\n}\n\nfunction isHtmlLayoutMetadata(metadata: MetadataBase | undefined): metadata is HtmlLayoutMetadata {\n return isHtmlMetadata(metadata);\n}\n","import { DependencyTracker } from \"../../helpers/dependency-tracker.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\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.\" }],\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}\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\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 (same approach as postcss-import)\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 { CONFIG_FILE_NAME } from \"../../../types/common.ts\";\nimport { 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\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 setup() {\n this.watcher?.add(CONFIG_FILE_NAME);\n },\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 (basename(filePath) === CONFIG_FILE_NAME) {\n this.log.warn(`Config file \"${CONFIG_FILE_NAME}\" has changed. Please restart the server.`);\n }\n\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\nfunction executeExpression(expressionString: string, data: RouteData): ValueOrError<string> {\n type FunctionType = (parameters: RouteData[\"params\"], properties: Required<RouteData>[\"props\"]) => unknown;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n const function_ = new Function(\"$params\", \"$props\", `return ${expressionString}`) as FunctionType;\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 for (const routeData of routesData) {\n // Fill and populate\n const [pageString, fillError] = fillPlaceholders(await this.stringify(htmlMetadata), 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\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 { 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, relative } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { getPreloadInfo } from \"./get-file-type.ts\";\n\nimport type { 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\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 include = node.getAttribute(includeAttribute) || \"**/*\";\n const ignore = node.getAttribute(excludeAttribute) ?? undefined;\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 return {\n version: 1.1,\n tags: [\n { name: \"link\", attributes },\n { name: \"script\", attributes },\n ],\n };\n },\n };\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[]>();\nconst selectorParts: 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 selectorParts.push(`${tag}[${attribute}]`);\n }\n}\n\n// One big selector: \"img[src],video[src],...,a[href],...\"\nconst combinedSelector = selectorParts.join(\",\");\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\nexport function parseHtmlSources(ast: Document): ParseHtmlLinksResult[] {\n const links: ParseHtmlLinksResult[] = [];\n\n // One tree walk instead of eight\n for (const node of ast.querySelectorAll(combinedSelector)) {\n const tag = node.tagName.toLowerCase();\n\n const attributes = tagAttributeMap.get(tag);\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 links.push({\n node,\n get source() {\n return 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 links.push({\n node,\n get source() {\n return 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 } 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 // Parse HTML to AST (HTML root element)\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 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 htmlTerser from \"html-minifier-terser\";\n\nimport type { ValueOrError } from \"../../../utilities/value-or-error.ts\";\n\nexport async function minifyHtmlTerser(code: string): Promise<ValueOrError<string>> {\n try {\n const minified = await htmlTerser.minify(code, {\n minifyCSS: false,\n minifyJS: false,\n removeComments: true,\n collapseWhitespace: true,\n });\n\n return [minified, null];\n } catch {\n return [null, new Error(\"Failed to minify HTML\")];\n }\n}\n","import { parseHtmlSources } from \"../../../ast-utilities/html-utils/parse-html-sources.ts\";\nimport { formatCode } from \"../../../helpers/format-code.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 { htmlLoader } from \"./html-loader.ts\";\nimport { minifyHtmlTerser } from \"./minify-html.ts\";\n\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\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 }) {\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 [formatted, formatError] = await formatCode(code, join(this.root, metadata.filePath), \"html\");\n if (formatError) {\n this.log.error(\"Failed to format script\", metadata.filePath);\n return;\n }\n\n return formatted;\n }\n\n if (minify) {\n const [minified, minifyError] = await minifyHtmlTerser(code);\n if (minifyError) {\n this.log.error(\"Failed to minify style\", metadata.filePath);\n return;\n }\n\n return minified;\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 // Embedded scripts\n const scripts = metadata.ast.querySelectorAll(\"script\");\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 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 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}\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 { formatCode } from \"../../../helpers/format-code.ts\";\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\";\n\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\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 }) {\n if (!isMarkdownMetadata(metadata)) return;\n\n const code = processor.stringify(metadata.ast.root);\n\n if (format) {\n const [formatted, formatError] = await formatCode(code, join(this.root, metadata.filePath), \"markdown\");\n if (formatError) {\n this.log.error(\"Failed to format markdown\", metadata.filePath);\n return;\n }\n\n return formatted;\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 { minifySync as swcMinify } from \"@swc/core\";\nimport { minify_sync as terserMinify } from \"terser\";\n\nimport type { ValueOrError } from \"../../../utilities/value-or-error.ts\";\n\nexport function minifyScriptTerser(code: string, isModule: boolean): ValueOrError<string> {\n try {\n const minified = terserMinify(code, { module: isModule });\n\n if (!minified.code) {\n return [null, new Error(\"Failed to minify script: empty output\")];\n }\n\n return [minified.code, null];\n } catch (error) {\n return [null, error as Error];\n }\n}\n\nexport function minifyScriptSWC(code: string, isModule: boolean): ValueOrError<string> {\n try {\n const minified = swcMinify(code, { module: isModule });\n\n if (!minified.code) {\n return [null, new Error(\"Failed to minify script: empty output\")];\n }\n\n return [minified.code, null];\n } catch (error) {\n return [null, error as Error];\n }\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 { formatCode } from \"../../../helpers/format-code.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 { minifyScriptSWC } from \"./minify-script.ts\";\nimport { scriptLoader } from \"./script-loader.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nconst generator = typeof _generator === \"function\" ? _generator : _generator.default;\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 }) {\n if (!isScriptMetadata(metadata)) return;\n\n const code = generator(metadata.ast, { jsescOption: { minimal: true } }).code;\n\n if (format) {\n const [formatted, formatError] = await formatCode(code, join(this.root, metadata.filePath), \"js\");\n if (formatError) {\n this.log.error(\"Failed to format script\", metadata.filePath);\n return;\n }\n\n return formatted;\n }\n\n if (minify) {\n const [minified, minifyError] = minifyScriptSWC(code, metadata.module);\n if (minifyError) {\n printFmtError(\"Failed to minify script\", minifyError, { filePath: metadata.filePath });\n return;\n }\n\n return minified;\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 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(atRule => {\n if (atRule.name !== \"import\") return;\n\n for (const match of atRule.params.matchAll(cssUrlRe)) {\n const source = match[2];\n if (!source) continue;\n\n handles.push({\n node: atRule,\n get source() {\n return source;\n },\n set source(newSource) {\n atRule.params = atRule.params.replace(source, () => newSource);\n },\n });\n }\n });\n\n return handles;\n}\n","import cssnanoPlugin from \"cssnano\";\nimport defaultPreset from \"cssnano-preset-default\";\nimport { transform } from \"lightningcss\";\nimport postcss from \"postcss\";\n\nimport type { ValueOrError } from \"../../../utilities/value-or-error.ts\";\nimport type { PostcssAst } from \"@staticbolt/core\";\nimport type { Targets } from \"lightningcss\";\n\n/** @mutate cssRoot */\nexport async function minifyStyleCssNano(ast: PostcssAst, absFilePath: string): Promise<ValueOrError<string>> {\n try {\n const processResults = await postcss([cssnanoPlugin({ preset: defaultPreset() })]).process(ast, {\n from: absFilePath,\n });\n\n return [processResults.root.toString(), null];\n } catch (error) {\n return [null, error as Error];\n }\n}\n\nexport function minifyLightingCss(code: string, filename: string, targets?: Targets): ValueOrError<string> {\n try {\n const results = transform({\n filename,\n code: Buffer.from(code),\n minify: true,\n analyzeDependencies: false,\n targets,\n });\n\n return [results.code.toString(), null];\n } catch (error) {\n return [null, error as Error];\n }\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 { browserslistToTargets } from \"lightningcss\";\n\nimport { parseStyleSources } from \"../../../ast-utilities/postcss-utils/parse-style-srouces.ts\";\nimport { formatCode } from \"../../../helpers/format-code.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 { minifyLightingCss } from \"./minify-style.ts\";\nimport { styleLoader } from \"./style-loader.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\nimport type { Targets } from \"lightningcss\";\n\nexport function coreStylePlugin(): Plugin {\n let targets: Targets | undefined;\n\n return {\n name: \"core-style-metadata\",\n\n setup() {\n targets = browserslistToTargets(this.browserslist);\n },\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 }) {\n if (!isStyleMetadata(metadata)) return;\n\n const code = metadata.ast.toString();\n\n if (format) {\n const [formatted, formatError] = await formatCode(code, join(this.root, metadata.filePath), \"css\");\n if (formatError) {\n this.log.error(\"Failed to format style\", metadata.filePath);\n return;\n }\n\n return formatted;\n }\n\n if (minify) {\n const [minified, minifyError] = minifyLightingCss(code, metadata.filePath, targets);\n if (minifyError) {\n this.log.error(\"Failed to minify style\", metadata.filePath);\n return;\n }\n\n return minified;\n }\n\n return metadata.ast.toString();\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 { formatCode } from \"../../../helpers/format-code.ts\";\nimport { parseHtml } from \"../../../parsers/html-parser.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 { minifyHtmlTerser } from \"../html-metadata/minify-html.ts\";\nimport { svgLoader } from \"./svg-loader.ts\";\n\nimport type { MetadataSource, Plugin, StyleMetadata } from \"@staticbolt/core\";\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 const [rootClone, error] = parseHtml(metadata.ast.toString());\n if (error) {\n throw error;\n }\n\n cloned.ast = rootClone;\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 }) {\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 [formatted, formatError] = await formatCode(code, join(this.root, metadata.filePath), \"html\");\n if (formatError) {\n this.log.error(\"Failed to format style\", metadata.filePath);\n return;\n }\n\n return formatted;\n }\n\n if (minify) {\n const [minified, minifyError] = await minifyHtmlTerser(code);\n if (minifyError) {\n this.log.error(\"Failed to minify style\", metadata.filePath);\n return;\n }\n\n return minified;\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\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 { 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;\n\nfunction connect() {\n const 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\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 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 { extname, join, normalize } from \"../../../utilities/path.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\nexport interface DevelopmentServerOptions {\n /**\n * The dev server host.\n *\n * @default 0.0.0.0\n */\n host?: 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\nexport function developmentServerPlugin(options: DevelopmentServerOptions = {}): Plugin {\n const host = options.host ?? \"0.0.0.0\";\n const port = options.port ?? 3000;\n const entry = options.entry ?? \"/\";\n const publicDirectory = options.publicDirectory ?? \"public\";\n\n let fastify: Fastify.FastifyInstance;\n let websocket: Server;\n const wsClients: Set<WebSocket> = new Set();\n const entryPointAgeMap = new Map<string, number>();\n\n function upgradeWebSocketHandler(request: IncomingMessage, socket: Duplex, head: Buffer) {\n websocket.handleUpgrade(request, socket, head, ws => {\n wsClients.add(ws);\n websocket.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 setup() {\n if (this.production) return;\n\n // Web Socket\n websocket = new WebSocketServer({ noServer: true });\n\n // Web Server\n const fastifyServe: onRequestHookHandler = async (request, reply) => {\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\", upgradeWebSocketHandler);\n fastify.listen({ port, host }, (error, address) => {\n if (error) {\n this.log.error(error.message);\n throw new Error(error.message);\n }\n\n this.log.info(chalk.bold(\"Server listening on\"), chalk.green(address + entry));\n });\n\n websocket.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\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\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","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 { MetadataBase, AppConfig, BoundPlugin, MetadataSource, Plugin, ServerReply, ServerRequest } 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\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. */\n readonly watcher: FSWatcher | undefined;\n\n private isPluginInitialized = false;\n\n private measureExecutionTime = false;\n private executionTime: Record<string, Record<string, number>> = {};\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 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);\n\n // Load plugins\n const pluginsEntries = (options.plugins ?? []).entries();\n for (const [index, pluginOrPlugins] of pluginsEntries) {\n const items = Array.isArray(pluginOrPlugins) ? pluginOrPlugins : [pluginOrPlugins];\n for (const [itemIndex, plugin] of items.entries()) {\n this.plugins.push(this.bindPlugin(plugin, index + itemIndex));\n }\n }\n\n // Base plugin\n this.plugins.push(this.bindPlugin(coreBasePlugin(), this.plugins.length - 1));\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 private bindPlugin(plugin: Plugin, pluginIndex: number): BoundPlugin {\n const emptyFunction = () => {};\n\n const context = Object.create(this) as App & { pluginIndex: number; pluginName: string };\n context.pluginIndex = pluginIndex;\n context.pluginName = plugin.name;\n context.log = createLog(`[${plugin.name}]`);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const bind = (method?: (...arguments_: any[]) => any) => {\n return method ? method.bind(context) : emptyFunction;\n };\n\n plugin.setup = bind(plugin.setup);\n plugin.read = bind(plugin.read);\n plugin.load = bind(plugin.load);\n plugin.resolveSource = bind(plugin.resolveSource);\n plugin.transformSource = bind(plugin.transformSource);\n plugin.preTransform = bind(plugin.preTransform);\n plugin.transform = bind(plugin.transform);\n plugin.postTransform = bind(plugin.postTransform);\n plugin.write = bind(plugin.write);\n plugin.postBuild = bind(plugin.postBuild);\n plugin.clone = bind(plugin.clone);\n plugin.stringify = bind(plugin.stringify);\n plugin.sourcesProvider = bind(plugin.sourcesProvider);\n plugin.rebaseSource = bind(plugin.rebaseSource);\n plugin.onMetadataRebase = bind(plugin.onMetadataRebase);\n\n // Dev server\n plugin.handleRequest = bind(plugin.handleRequest);\n plugin.resolveRequestPath = bind(plugin.resolveRequestPath);\n plugin.onFileEvent = bind(plugin.onFileEvent);\n plugin.resolveCompileList = bind(plugin.resolveCompileList);\n\n return plugin as 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\n const methodFunction = plugin[method] as (...arguments__: unknown[]) => unknown;\n const result = methodFunction(...arguments_) as ReturnType<BoundPlugin[T]>;\n\n this.executionTime[plugin.name][method] += performance.now() - now;\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 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(this.metadataList);\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 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 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 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 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 metadataItem.directDependencies.add(discoveredID);\n\n if (this.entryPoints.has(discoveredID)) continue;\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 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\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 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 await this.callPluginMethod(plugin, \"onMetadataRebase\", metadata, oldAbsolutePath, newAbsolutePath);\n }\n }\n\n async writeFiles(metadataItemOrList: MetadataBase | MetadataBase[]) {\n if (!this.isPluginInitialized) {\n this.log.warn(\"[emit] Plugins are not fully setup yet.\");\n }\n\n const items = Array.isArray(metadataItemOrList) ? metadataItemOrList : [metadataItemOrList];\n\n for (const plugin of this.plugins) {\n for (const metadata of items) {\n await this.callPluginMethod(plugin, \"write\", metadata);\n }\n }\n }\n\n async read(filePath: string) {\n filePath = normalize(filePath);\n\n if (!isAbsolute) {\n filePath = join(this.root, filePath);\n }\n\n for (const plugin of this.plugins) {\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 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 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: { minify?: boolean; format?: boolean } = {}): 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 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 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 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 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 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 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 Object.entries(metadataFilter)) {\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 return this.metadataList.filter(metadata => {\n // Match by reference\n if (metadata === metadataFilter) {\n return true;\n }\n\n for (const [key, value] of Object.entries(metadataFilter)) {\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\";\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\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\n buildCommand.onExecute(async () => {\n const startTime = performance.now();\n\n config.production = true;\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 ttf2woff2 from \"ttf2woff2\";\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\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(({ options }) => {\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 \"auto\"\n */\n fontDisplay?: \"auto\" | \"block\" | \"swap\" | \"fallback\" | \"optional\";\n}\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\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 { App } from \"../../../main.ts\";\n\nimport type { 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\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) {\n const buildCommand = this.defineSubcommand({\n name,\n aliases,\n meta: { description: \"Dev server for static bolt.\" },\n });\n\n buildCommand.onExecute(async () => {\n config.production = false;\n\n const app = new App(config, configPath);\n await app.run();\n });\n\n this.addCommand(buildCommand);\n },\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,S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UAAU,OAAO,GAAG,CAAC,CAAC,KAAK;GACjE,CAAC;GAED,KAAK,WAAW,yBAAyB;EAC3C;CACF;AACF;AAEA,SAAS,WAAW,OAAe;CACjC,OAAO,sBAAsB,KAAK,KAAK;AACzC;;AAGA,SAAS,gBAAgB,UAA0B;CACjD,MAAM,IAAI,SAAS;CACnB,MAAM,IAAI,SAAS;CACnB,MAAM,IAAI,SAAS;CAEnB,IAAI,SAAS,OAAO,KAAK,SAAS,OAAO,KAAK,SAAS,OAAO,GAC5D,OAAO,IAAI,IAAI,IAAI;CAGrB,OAAO;AACT;;;;AC5JA,SAAgB,eAAe,UAAiC,CAAC,GAAW;CAC1E,MAAM,OAAO,QAAQ,WAAW;CAChC,MAAM,UAAU,QAAQ,WAAW,CAAC,KAAK;CAEzC,OAAO;EACL,MAAM;EAEN,IAAI,QAAQ,YAAY;GACtB,MAAM,eAAe,KAAK,iBAAiB;IACzC;IACA;IACA,MAAM,EAAE,aAAa,8BAA8B;GACrD,CAAC;GAED,aAAa,UAAU,YAAY;IACjC,OAAO,aAAa;IAGpB,MAAM,IADU,IAAI,QAAQ,UACpB,CAAC,CAAC,IAAI;GAChB,CAAC;GAED,KAAK,WAAW,YAAY;EAC9B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["#depsMap","#visiting","#app","#root","#collectPackageMetadataDeps","#collect","#resolveSource","c","bundleFunction","traverse","normalizePackageName","generator","resolveStaticValue","resolveStaticValue","c","placeholderRe","executeExpression","parse","placeholderRe","z","parseYaml","swcMinify"],"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/helpers/format-code.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/plugins/write-files/write-files-plugin.ts","../../src/helpers/execute-js-in-vm.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/plugins/html-bundle-style/html-bundle-style-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/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/minify-html.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/plugins/core-plugins/script-metadata/minify-script.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/minify-style.ts","../../src/parsers/css-parser.ts","../../src/plugins/core-plugins/style-metadata/style-loader.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/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\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 // ------ Report missing files ------\n const missingFiles = usedFiles.difference(availableFiles);\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.size > 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 const relativePath = relative(this.outdir, unused);\n\n const isExcluded = isPathMatch(relativePath, { include: exclude, root: this.outdir });\n if (isExcluded) continue;\n\n if (isRemoveUnused) unlinkSync(unused);\n\n unusedFilesLog.push(c.yellow(join(basename(this.outdir), relativePath)));\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\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/**\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 { minify_sync } from \"terser\";\n\nimport { 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 calcPackageOutPath,\n diffSpecifiers,\n generateStdinString,\n getChunkName,\n getCustomPackagePath,\n isNodeModulesPath,\n matchesPackage,\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 * Whether to use Terser for minification to reduce the final bundle size.\n *\n * @default false\n */\n minifyUsingTerser?: boolean;\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 each `node_modules` package and its dependencies into separate files under `packagesDir`. The plugin scans files for\n * imports and uses esbuild's tree-shaking capabilities to generate the bundles.\n */\nexport function bundlePackagesPlugin(options: BundlePackagesOptions = {}): Plugin {\n const packagesOutputDirection = options.packagesDir ?? \"./packages\";\n const shouldMinifyUsingTerser = options.minifyUsingTerser ?? false;\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 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 // For already resolved `node_modules` sources, keep them as is\n if (isNodeModulesPath(join(dirname(filePath), link), this.root)) {\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 }\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 // Already bundled\n const packageMetadataExists = this.findMetadata({ type: METADATA_TYPES.Package, id: chunkName });\n if (packageMetadataExists) 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 const packageOutputPath = calcPackageOutPath(chunkName, packagesOutputDirection);\n\n const packageMetadata: PackageMetadata = {\n type: METADATA_TYPES.Package,\n packageName: chunkName,\n code: \"\",\n filePath: packageOutputPath,\n id: chunkName,\n directDependencies: new Set(),\n };\n\n const [bundledCode, bundleError] = await bundlePackage({\n contents,\n resolveDir: this.root,\n outfile: packageOutputPath,\n packageName: chunkName,\n minify: this.production && !shouldMinifyUsingTerser,\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\n this.addMetadata(packageMetadata);\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: !shouldMinifyUsingTerser && 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: !shouldMinifyUsingTerser,\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 // Minify using terser\n if (!shouldMinifyUsingTerser) return;\n\n const packages = this.filterMetadata<PackageMetadata>({ type: METADATA_TYPES.Package });\n\n for (const packageMetadata of packages) {\n const result = minify_sync(packageMetadata.code);\n if (!result.code) {\n printFormattedError(`Failed to minify package \"${packageMetadata.packageName}\"`);\n continue;\n }\n\n packageMetadata.code = result.code;\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\";\nimport sharp from \"sharp\";\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\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 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\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\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 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 { name, matchStartIndex, matchEndIndex, args } = parseFunctionCall(style, `${cssFunctionPrefix}.+`);\n if (matchStartIndex < 0) return;\n\n const easeFunctionName = name.replace(cssFunctionPrefix, \"\");\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 node.setAttribute(\n \"style\",\n style.slice(0, Math.max(0, matchStartIndex)) + easeFunctionOrString + style.slice(Math.max(0, matchEndIndex))\n );\n\n return;\n }\n\n try {\n const linearFunction = convertEasingFunctionToLinearFN(easeFunctionOrString(...args), samples);\n node.setAttribute(\n \"style\",\n style.slice(0, Math.max(0, matchStartIndex)) + linearFunction + style.slice(Math.max(0, matchEndIndex))\n );\n } catch {\n printFmtError(\"Error generating easing function\", {\n function: customEasePlugin,\n filePath: inputMetadata.id,\n });\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 value = declaration.value;\n\n const { name, matchStartIndex, matchEndIndex, args } = parseFunctionCall(value, `${cssFunctionPrefix}.+`);\n if (matchStartIndex < 0) return;\n\n const easeFunctionName = name.replace(cssFunctionPrefix, \"\");\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 declaration.value =\n value.slice(0, Math.max(0, matchStartIndex)) + easeFunctionOrString + value.slice(Math.max(0, matchEndIndex));\n\n return;\n }\n\n try {\n const linearFunction = convertEasingFunctionToLinearFN(easeFunctionOrString(...args), samples);\n declaration.value =\n value.slice(0, Math.max(0, matchStartIndex)) + linearFunction + value.slice(Math.max(0, matchEndIndex));\n } catch {\n printFmtError(\"Error generating easing function\", {\n function: customEasePlugin,\n filePath: inputMetadata.id,\n });\n }\n });\n }\n }\n },\n };\n}\n\ninterface ParseFunctionCallResult {\n name: string;\n matchStartIndex: number;\n matchEndIndex: number;\n args: unknown[];\n}\n\n/** - Parse a string representing a function call and get its arguments and name */\nfunction parseFunctionCall(code: string, functionNameMatcher: string): ParseFunctionCallResult {\n const re = new RegExp(String.raw`(${functionNameMatcher})\\s*\\(\\s*(.*)\\s*\\)`);\n\n const match = re.exec(code);\n if (!match) {\n return { name: \"\", matchStartIndex: -1, matchEndIndex: -1, args: [] };\n }\n\n const name = match[1];\n if (!name) {\n return { name: \"\", matchStartIndex: -1, matchEndIndex: -1, args: [] };\n }\n\n const argumentsString = match[2];\n if (!argumentsString) {\n return { name, matchStartIndex: match.index, matchEndIndex: match.index + match[0].length, args: [] };\n }\n\n let arguments_: unknown[] = [];\n try {\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n const function_ = new Function(`return [${argumentsString}]`) as () => unknown[];\n arguments_ = function_();\n } catch {\n console.warn(`Failed to parse function call: ${code}`);\n }\n\n return { name, matchStartIndex: match.index, matchEndIndex: match.index + match[0].length, args: arguments_ };\n}\n","import type { ValueOrError } from \"../utilities/value-or-error.ts\";\nimport type { Options } from \"prettier\";\n\ntype Lang = \"js\" | \"html\" | \"css\" | \"markdown\" | \"ts\" | \"json\";\n\nlet prettierConfig: Options | undefined;\n\n/** - Format code using Prettier */\nexport async function formatCode(code: string, filePath: string, lang: Lang): Promise<ValueOrError<string>> {\n const { format } = await import(\"prettier\");\n\n try {\n await loadPrettier(filePath);\n const options = prettierConfig ?? { printWidth: 130 };\n\n const parser = lang === \"js\" ? \"babel\" : lang === \"ts\" ? \"typescript\" : lang;\n const formattedCode = await format(code, { ...options, parser, filepath: filePath });\n\n return [formattedCode, null];\n } catch {\n return [null, new Error(`Prettier formatting failed for '${filePath}'`)];\n }\n}\n\nasync function loadPrettier(filePath: string) {\n if (prettierConfig) {\n return;\n }\n\n const { resolveConfig } = await import(\"prettier\");\n const organizeImports = await import(\"prettier-plugin-organize-imports\");\n\n try {\n const options = (await resolveConfig(filePath)) ?? { printWidth: 130 };\n if (!options.plugins) options.plugins = [];\n\n if (!options.plugins.includes(\"prettier-plugin-jsdoc\")) {\n options.plugins.push(organizeImports.default);\n }\n\n prettierConfig = options;\n } catch {\n return;\n }\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\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\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\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\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: true,\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 = 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\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\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\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\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\";\nimport { generateSW } from \"workbox-build\";\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 * Please don't forget to register the service worker in your HTML file.\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 */\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 { 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\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 { optimize, type Config } from \"svgo\";\n\nimport { valueOrError } from \"../../utilities/value-or-error.ts\";\n\nfunction optimizeSvgUnsafe(svgCode: string, config?: Config) {\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 * Optimize SVG files and SVG tags in HTML using `svgo`.\n *\n * For CSS inlined SVGs, use a PostCSS plugin like `cssnano` instead.\n *\n * **Production Only**\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 return {\n name: \"svgo\",\n\n setup() {\n this.pluginData.optimizedSvgList ??= new Set<string>();\n },\n\n 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 const [svg, error] = optimizeSvg(svgString, svgoConfig);\n if (error) {\n printFmtError(\"Failed to optimize svg using `svgo`\", error, { filePath, node });\n continue;\n }\n\n node.replaceWith(svg);\n }\n\n return;\n }\n },\n\n 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] = 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\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\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 },\n\n async transform(inputMetadata) {\n const allPlugins = [...plugins, ...postcssConfig.plugins];\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\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\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 write(metadata) {\n if (!isWebManifestMetadata(metadata)) return;\n\n await this.rebase(metadata, join(this.root, outfile));\n },\n };\n}\n","import { cpSync, mkdirSync, rmSync, writeFileSync } from \"node:fs\";\n\nimport { isBinaryAssetMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join, isPathMatch } from \"../../utilities/path.ts\";\n\nimport type { 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 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\nexport function writeFilesPlugin(options: WriteFilesOptions): Plugin {\n const include = options.include ?? [\"**/*\"];\n const ignore = options.exclude ?? [];\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 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(metadata) {\n if (!this.production) return;\n\n if (this.emitExclude.has(metadata)) return;\n\n const isIncluded = isPathMatch(metadata.id, { include, ignore, root: this.root });\n if (!isIncluded) return;\n\n if (metadata.filePath.startsWith(\"../\")) {\n this.log.error(`file path \"${metadata.filePath}\" is outside of the output directory \"${this.outdir}\". Skipping...`);\n return;\n }\n\n const shouldMinify = shouldMinifyFile(metadata.id, this.root);\n const shouldFormat = shouldFormatFile(metadata.id, this.root);\n\n if (shouldMinify && shouldFormat) {\n this.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(this.root, metadata.id);\n const copyTo = join(this.outdir, metadata.filePath);\n cpSync(copyFrom, copyTo, { recursive: true });\n return;\n }\n\n // stringify\n const code = await this.stringify(metadata, { format: shouldFormat, minify: shouldMinify });\n if (typeof code !== \"string\") {\n this.log.error(`Failed to stringify \"${metadata.id}\"`);\n return;\n }\n\n if (!code) {\n this.log.warn(`Writing empty file \"${metadata.filePath}\"`);\n }\n\n // write\n const outputFile = join(this.outdir, metadata.filePath);\n mkdirSync(dirname(outputFile), { recursive: true });\n writeFileSync(outputFile, code, \"utf8\");\n },\n };\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport vm from \"node:vm\";\n\nimport { Log } from \"../utilities/logger.ts\";\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 */\n root: string;\n\n /** The entry file, should match the key of the `transformedScripts` */\n entryFile: string;\n\n /** A function to get the code of the entry file */\n getCode(filePath: string): string | void | Promise<string | void>;\n\n /** A plain object to provide global context to the VM */\n context?: Record<string, unknown>;\n\n /** The html content of the `document` API */\n html?: string;\n}\n\ninterface ExecuteJsInVmResult {\n output: Record<string, unknown>;\n exports: { [k: string]: unknown };\n dom: JSDOM | undefined;\n}\n\nasync function executeJsInVmUnsafe(options: ExecuteJsInVmOptions): Promise<ExecuteJsInVmResult> {\n const { root, entryFile, context: contextObject = {}, html } = options;\n\n let dom: JSDOM | undefined;\n if (html) {\n const { JSDOM, VirtualConsole } = await import(\"jsdom\");\n dom = html ? new JSDOM(html, { virtualConsole: new VirtualConsole(), url: \"http://localhost/\" }) : undefined;\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, Object.assign({ ___output: {}, console }, contextObject));\n\n const context = vm.createContext(window);\n\n /** - Save modules in memory to avoid creating a new one for the same file */\n const modules: Record<string, vm.SourceTextModule | vm.SyntheticModule> = {};\n\n // load the entry module\n const script = await options.getCode(entryFile);\n if (!script) {\n Log.error(`[executeJsInVM] can't find the script '${entryFile}'`);\n return { output: context.___output as Record<string, unknown>, exports: {}, dom };\n }\n\n const module = new vm.SourceTextModule(script, {\n context,\n identifier: entryFile,\n importModuleDynamically,\n initializeImportMeta,\n });\n modules[entryFile] = module;\n\n const baseMetaUrl = \"http://localhost:3000\";\n function initializeImportMeta(meta: ImportMeta, referencingModule: vm.Module) {\n let id = referencingModule.identifier;\n\n if (extname(id) === \".html\") {\n id = dirname(id) + \"/\";\n }\n\n meta.resolve = url => {\n return new URL(join(id, url), baseMetaUrl).href;\n };\n\n meta.url = new URL(id, baseMetaUrl).href;\n }\n\n async function importModuleDynamically(specifier: string, referrer: vm.Module): Promise<vm.Module> {\n const m = await linker(specifier, referrer);\n if (m.status === \"unlinked\") await m.link(linker);\n else if (m.status === \"linked\") await m.evaluate();\n return m;\n }\n\n async function linker(specifier: string, referencingModule: vm.Module): Promise<vm.Module> {\n const isNativeModule = specifier.startsWith(\"node:\");\n\n const resolveName = isNativeModule ? specifier : join(dirname(referencingModule.identifier), specifier);\n\n // resolve json files and serialize it\n if (extname(resolveName) === \".json\") {\n const jsonPath = join(root, resolveName);\n if (!existsSync(jsonPath)) {\n throw new Error(`[executeJsInVM] can't find the file '${resolveName}'`);\n }\n\n let jsonString = readFileSync(jsonPath, \"utf8\");\n jsonString = \"const __json = \" + jsonString + \";export default __json;\";\n const module = new vm.SourceTextModule(jsonString, { context, identifier: resolveName });\n modules[resolveName] = module;\n return module;\n }\n\n const isLoaded = Object.hasOwn(modules, resolveName);\n if (isLoaded) {\n return modules[resolveName];\n }\n\n if (isNativeModule) {\n const builtIn = (await import(specifier)) as Record<string, unknown>;\n const exportNames = Object.keys(builtIn);\n\n const module = new vm.SyntheticModule(\n exportNames,\n function () {\n for (const key of exportNames) this.setExport(key, builtIn[key]);\n },\n { context, identifier: resolveName }\n );\n\n modules[resolveName] = module;\n\n return module;\n }\n\n const moduleScript = await options.getCode(resolveName);\n if (!moduleScript) {\n Log.error(`[executeJsInVM] can't find the script '${resolveName}' in the transformed scripts map`);\n throw new Error(`can't resolve module '${specifier}' from '${referencingModule.identifier}'`);\n }\n\n const module = new vm.SourceTextModule(moduleScript, {\n context: referencingModule.context,\n identifier: resolveName,\n importModuleDynamically,\n initializeImportMeta,\n });\n\n modules[resolveName] = module;\n\n return module;\n }\n\n await module.link(linker);\n await module.evaluate();\n\n const exports = Object.fromEntries(Object.entries(module.namespace));\n\n return { output: context.___output as Record<string, unknown>, exports, dom };\n}\n\nconst executeJsInVM = valueOrError(executeJsInVmUnsafe);\n\nexport { executeJsInVM };\n","import vm from \"node:vm\";\n\nimport { executeJsInVM } from \"../../helpers/execute-js-in-vm.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, isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { dirname, join } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.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 contextAttribute?: string;\n}\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 let isVmEnabled = true;\n\n return {\n name: \"html-build-time-script\",\n\n setup() {\n if (vm.SourceTextModule) {\n return;\n }\n\n isVmEnabled = false;\n printFmtError(\n \"Script execution requires the `node:vm` module, which is currently unavailable.\",\n \"\\nStart Node.js with the `--experimental-vm-modules` flag to enable it.\"\n );\n },\n\n async postTransform() {\n for (const metadata of this.metadataList) {\n if (!isHtmlMetadata(metadata)) {\n continue;\n }\n\n if (!isVmEnabled) {\n for (const node of metadata.ast.querySelectorAll(query)) {\n node.remove();\n }\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 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 });\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\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: \"script\",\n attributes: [\n {\n name: buildAttribute,\n description: \"This attribute is used to mark the script as build-time script.\",\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 },\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}\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 isExternalCheck: (strings: string) => boolean;\n}\n\nexport async function bundleScriptWithEsbuild(this: App, options: Options): Promise<ValueOrError<string>> {\n const { contents, entryPoint, outfile, 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: \"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 { CUSTOM_ATTRIBUTES } from \"../../types/common.ts\";\nimport { isHtmlMetadata, isScriptMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { basename, dirname, join, isPathMatch, normalize, relative, replaceExtension } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { bundleScriptWithEsbuild } from \"./esbuild-bundle.ts\";\n\nimport type { MetadataSource, 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 * @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/**\n * A plugin that bundles script tags in HTML files using esbuild.\n *\n * Bundling is opt-in per script tag via the \"bundle\" attribute (configurable via HtmlBundleScriptOptions.bundleAttribute).\n *\n * Inlining vs. separate file\n *\n * - Inline script, no \"bundle-out\" attribute: bundled output replaces the tag content in place.\n * - Inline script, \"bundle-out\" attribute set: tag content is cleared and \"src\" is set to the output file.\n * - \"src\" script, no \"bundle-out\" attribute: bundle is written to \"{filename}.bundle.js\" and \"src\" is updated.\n * - \"src\" script, \"bundle-out\" attribute set: bundle is written to the specified path and \"src\" is updated.\n *\n * Externals resolution\n *\n * Glob patterns in HtmlBundleScriptOptions.externals and HtmlBundleScriptOptions.externalsExclude are matched against each\n * resolved module path. A module is treated as external if it matches \"externals\" and does not match \"externalsExclude\".\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\n const query = `script[${bundleAttribute}]`;\n\n const printFmtError = PrintFormattedError.create({ function: htmlBundleScriptPlugin });\n\n return {\n name: \"html-bundle-script\",\n\n // Collects script tags that declare an explicit output path so the build\n // system can track and rebase those paths when needed.\n sourcesProvider(metadata) {\n if (!this.production || !isHtmlMetadata(metadata)) return;\n\n const sources: MetadataSource[] = [];\n\n // eslint-disable-next-line unicorn/require-css-escape\n const elements = metadata.ast.querySelectorAll(`script[${bundleOutAttribute}]`);\n for (const node of elements) {\n const source = node.attrs[bundleOutAttribute];\n if (!source) continue;\n\n const scriptType = node.getAttribute(\"type\");\n if (!isScriptType(scriptType)) continue;\n\n sources.push({\n node,\n get source() {\n return source;\n },\n set source(newValue) {\n node.setAttribute(bundleOutAttribute, newValue);\n },\n });\n }\n\n // Fixed: was missing the return, so sources were silently dropped.\n return sources;\n },\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 bundleOut = node.getAttribute(bundleOutAttribute);\n const externalsAttributeValue = node.getAttribute(externalsAttribute);\n const externalsExcludeAttributeValue = node.getAttribute(externalsExcludeAttribute);\n\n node.removeAttribute(bundleAttribute);\n node.removeAttribute(bundleOutAttribute);\n node.removeAttribute(externalsAttribute);\n node.removeAttribute(externalsExcludeAttribute);\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\" when no explicit path is given.\n outfile = bundleOut ?? normalize(replaceExtension(basename(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.info(`The entry point \"${entryPoint}\" is already bundled in \"${outfile}\", skipping...`);\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 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 attributes: [\n {\n name: bundleAttribute,\n description: \"Enable script bundling.\",\n },\n {\n name: bundleOutAttribute,\n description:\n \"Specify the output path for bundled scripts relative to the output directory.\" +\n \"\\nIf the script has a `src` attribute, the output path will default to `{filename}.bundle.js`.\" +\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 },\n ],\n };\n },\n };\n}\n\n// Splits a semicolon-separated attribute value into an array of trimmed glob patterns.\n// Returns undefined if the input is not a string, and an empty array for an empty string.\nfunction parsePatterns(string: string | null): string[] | undefined {\n if (typeof string !== \"string\") return;\n\n if (!string) return [];\n\n string = string.trim();\n\n return string.split(\";\").flatMap(p => {\n const trimmed = p.trim();\n return trimmed ? [trimmed] : [];\n });\n}\n","import { readFileSync } from \"node:fs\";\nimport postcssImport from \"postcss-import\";\n\nimport { processCss } from \"../../ast-utilities/postcss-utils/process-css.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, relative, resolve } 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\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 return {\n name: \"html-bundle-style\",\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 [, processError] = await processCss(\n styleMetadata.ast,\n [\n postcssImport({\n load: async absoluteFilePath => {\n const source = relative(this.root, absoluteFilePath);\n\n const metadata = this.findMetadata({ filePath: source });\n if (!metadata) {\n return readFileSync(absoluteFilePath, \"utf8\");\n }\n\n return await this.stringify(metadata);\n },\n }),\n ],\n { from: resolve(this.root, metadata.filePath) }\n );\n\n if (processError !== null) {\n printFmtError(processError, { function: htmlBundleStylePlugin, node, filePath: metadata.id });\n }\n }\n },\n\n lspHtmlData() {\n return {\n version: 1.1,\n tags: [\n {\n name: \"link\",\n attributes: [{ name: bundleAttribute, description: \"Enable style bundling.\" }],\n },\n {\n name: \"style\",\n attributes: [{ name: bundleAttribute, description: \"Enable style bundling.\" }],\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\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 const elements = metadata.ast.querySelectorAll(tag);\n\n for (const node of elements) {\n node.replaceWith(node.innerHTML.trim());\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 { 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\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 && scriptType !== \"module\") {\n printFmtError(\"IIFE should only be used with global scripts.\", { level: \"warning\" });\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 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 },\n ],\n },\n ],\n };\n },\n };\n}\n","import { isScriptType } from \"../../helpers/is-script-type.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\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 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 ],\n },\n ],\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}.css`);\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 { 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\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 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 },\n ],\n },\n ],\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 script metadata\")];\n }\n\n return [metadata, null];\n}\n","import { 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\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 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 },\n ],\n },\n ],\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}.css`);\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 script metadata\")];\n }\n\n return [metadata, null];\n}\n","import { DependencyTracker } from \"../../helpers/dependency-tracker.ts\";\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 { 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\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 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 result.push({\n get source() {\n return source;\n },\n set source(newValue) {\n inlineTag.setAttribute(sourceAttribute, newValue);\n },\n });\n }\n\n return result;\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 sourceRelative = join(dirname(metadata.filePath), source);\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 },\n ],\n },\n ],\n };\n },\n };\n}\n","import { isHtmlMetadata } from \"../../utilities/metadata-utilities.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\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\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 },\n {\n name: whereAttribute,\n description: \"The position of the inserted element.\",\n values: [{ name: \"beforebegin\" }, { name: \"afterbegin\" }, { name: \"beforeend\" }, { name: \"afterend\" }],\n },\n ],\n },\n ],\n };\n },\n };\n}\n","import type { ValueOrError } from \"../../utilities/value-or-error.ts\";\n\n/** (any){{any}} */\nconst placeholderRe = /(\\\\)?{{\\s*([\\s\\S]*?)\\s*}}/g;\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, 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, type HTMLElement } from \"../../types/common.ts\";\nimport { 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\";\n\nimport type { IAttributeData, ITagData, MetadataSource, Plugin } from \"@staticbolt/core\";\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 \"data\"\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\ninterface HtmlLayoutMetadata extends HtmlMetadata {\n hash: string;\n}\n\nexport function htmlLayoutPlugin(options: HtmlLayoutOptions = {}): Plugin {\n const layoutTags = options.tags ?? [\"layout\", \"part\"];\n const sourceAttribute = options.layoutSourceAttribute ?? \"src\";\n const dataSourceAttribute = options.dataSourceAttribute ?? \"dataSource\";\n const dataJsonAttribute = options.dataJsonAttribute ?? \"dataJson\";\n const alwaysIncludeAttribute = options.alwaysIncludeAttribute ?? \"always-include\";\n const addAttributeAttribute = options.addAttributeAttribute ?? \"add-attr\";\n const removeAttributeAttribute = options.removeAttributeAttribute ?? \"remove-attr\";\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 const fileName = basename(path);\n return layoutTags.some(tag => fileName.endsWith(`.${tag}.html`));\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>>(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>>(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 = calculateHash(node, sourceAttribute);\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 // Add and remove attributes\n const addAttributePrefix = `${addAttributeAttribute}-`;\n const removeAttributePrefix = `${removeAttributeAttribute}-`;\n\n const elements = layoutMetadata.ast.querySelectorAll(\"*\");\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(addAttributePrefix)) {\n const targetAttribute = name.slice(addAttributePrefix.length);\n element.removeAttribute(name);\n if (value.trim() && value.trim() !== \"false\") {\n element.setAttribute(targetAttribute, \"\");\n }\n continue;\n }\n\n if (name.startsWith(removeAttributePrefix)) {\n const targetAttribute = name.slice(removeAttributePrefix.length);\n element.removeAttribute(name);\n if (value.trim() && value.trim() !== \"false\") {\n element.removeAttribute(targetAttribute);\n }\n }\n }\n }\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 // When using the layout multiple times in the same file, scripts/styles tags should only be\n // included once — unless the tag carries the always-include attribute, in which case it is\n // included for every layout instance (useful for per-instance build-time scripts).\n const scriptsAndStyles = layoutHtmlMetadata.ast.querySelectorAll(\"script,style\");\n for (const scriptOrStyle of scriptsAndStyles) {\n const id = scriptOrStyle.getAttribute(CUSTOM_ATTRIBUTES.MetadataID);\n if (!id) continue;\n\n if (scriptOrStyle.hasAttribute(alwaysIncludeAttribute)) {\n scriptOrStyle.removeAttribute(alwaysIncludeAttribute);\n continue;\n }\n\n const isScript = scriptOrStyle.tagName === \"SCRIPT\";\n const exitsMetadata = metadata[isScript ? \"scriptsMetadataList\" : \"stylesMetadataList\"].get(id);\n\n if (exitsMetadata) {\n layoutHtmlMetadata[isScript ? \"scriptsMetadataList\" : \"stylesMetadataList\"].delete(id);\n scriptOrStyle.remove();\n }\n }\n\n // When using the layout multiple times in the same file,\n // include scripts/stylesheets with links only once\n const scriptsAndLinks = layoutHtmlMetadata.ast.querySelectorAll('script[src], link[rel=\"stylesheet\"]');\n for (const scriptOrLink of scriptsAndLinks) {\n if (scriptOrLink.hasAttribute(alwaysIncludeAttribute)) {\n scriptOrLink.removeAttribute(alwaysIncludeAttribute);\n continue;\n }\n\n const isScript = scriptOrLink.tagName === \"SCRIPT\";\n const attribute = isScript ? \"src\" : \"href\";\n\n const layoutSourceRelative = join(dirname(layoutHtmlMetadata.filePath), scriptOrLink.attributes[attribute]);\n const selector = isScript ? \"script[src]\" : 'link[rel=\"stylesheet\"]';\n\n const isAlreadyExists = metadata.ast.querySelectorAll(selector).some(element => {\n const elementSourceRelative = join(dirname(metadata.filePath), element.attributes[attribute]);\n return elementSourceRelative === layoutSourceRelative;\n });\n\n if (isAlreadyExists) {\n scriptOrLink.remove();\n }\n }\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 // Fill slots\n const children = node.querySelectorAll(\":scope > *\");\n for (const element of children) {\n if (element.nodeType !== NodeType.ELEMENT_NODE) continue;\n\n // unnamed slots (default)\n if (!element.hasAttribute(\"slot\")) {\n const defaultSlots = layoutHtmlMetadata.ast.querySelectorAll(`slot:not([name])`);\n if (defaultSlots.length === 0) {\n printFmtError(`No default slot in layout file:`, layoutRelativePath, { node: element });\n continue;\n }\n\n for (const defaultSlot of defaultSlots) {\n defaultSlot.insertAdjacentHTML(\"beforeend\", element.outerHTML);\n }\n\n continue;\n }\n\n // named slots\n const slotName = element.getAttribute(\"slot\");\n if (!slotName) continue;\n\n // eslint-disable-next-line unicorn/require-css-escape\n const namedSlots = layoutHtmlMetadata.ast.querySelectorAll(`slot[name=\"${slotName}\"]`);\n if (namedSlots.length === 0) {\n printFmtError(`No slots with name \"${slotName}\" in layout file:`, layoutRelativePath, {\n node: element,\n });\n continue;\n }\n\n element.removeAttribute(\"slot\");\n\n for (const namedSlot of namedSlots) {\n namedSlot.insertAdjacentHTML(\"beforeend\", element.outerHTML);\n }\n }\n\n // remove slot outerHTML\n for (const slot of layoutHtmlMetadata.ast.querySelectorAll(\"slot\")) {\n slot.replaceWith(slot.innerHTML.trim());\n }\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 const tag = Object.keys(metadata.ast.frontmatter).find(key => layoutTags.includes(key));\n if (!tag) return;\n\n let attributesString = \"\";\n for (const [key, value] of Object.entries(metadata.ast.frontmatter)) {\n attributesString += `${key === tag ? sourceAttribute : key}=\"${value}\" `;\n }\n\n const openTag = `<${tag} ${attributesString}>`;\n const closeTag = `</${tag}>`;\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const oldRender = metadata.ast.render;\n\n metadata.ast.render = async () => {\n const html = await oldRender();\n return openTag + html + closeTag;\n };\n\n return;\n }\n },\n\n lspHtmlData() {\n const attributes: IAttributeData[] = [\n { name: sourceAttribute, description: \"The path to the layout to use.\" },\n { name: dataSourceAttribute, description: \"The path for a JSON file containing data for the layout.\" },\n { name: dataJsonAttribute, description: \"The layout data in JSON format.\" },\n ];\n\n const alwaysInclude = {\n name: alwaysIncludeAttribute,\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 };\n\n const tags: ITagData[] = [\n { name: \"script\", attributes: [alwaysInclude] },\n { name: \"link\", attributes: [alwaysInclude] },\n { name: \"style\", attributes: [alwaysInclude] },\n ];\n\n for (const tag of layoutTags) {\n tags.push({ name: tag, description: `This tag allows inlining a \\`${tag}\\` file.`, attributes });\n }\n\n return {\n version: 1.1,\n tags,\n globalAttributes: [\n {\n name: addAttributeAttribute,\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: removeAttributeAttribute,\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}\n\nfunction calculateHash(node: HTMLElement, sourceAttribute: string): string {\n let hash = \"\";\n\n for (const [attribute, value] of Object.entries(node.attributes)) {\n if (attribute === sourceAttribute) continue;\n hash += `${attribute}=${value}`;\n }\n\n return hash;\n}\n\nfunction isHtmlLayoutMetadata(metadata: MetadataBase | undefined): metadata is HtmlLayoutMetadata {\n return isHtmlMetadata(metadata);\n}\n","import { DependencyTracker } from \"../../helpers/dependency-tracker.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\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.\" }],\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}\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\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 (same approach as postcss-import)\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 { CONFIG_FILE_NAME } from \"../../../types/common.ts\";\nimport { 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\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 setup() {\n this.watcher?.add(CONFIG_FILE_NAME);\n },\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 (basename(filePath) === CONFIG_FILE_NAME) {\n this.log.warn(`Config file \"${CONFIG_FILE_NAME}\" has changed. Please restart the server.`);\n }\n\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\nfunction executeExpression(expressionString: string, data: RouteData): ValueOrError<string> {\n type FunctionType = (parameters: RouteData[\"params\"], properties: Required<RouteData>[\"props\"]) => unknown;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n const function_ = new Function(\"$params\", \"$props\", `return ${expressionString}`) as FunctionType;\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 for (const routeData of routesData) {\n // Fill and populate\n const [pageString, fillError] = fillPlaceholders(await this.stringify(htmlMetadata), 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\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 { 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, relative } from \"../../utilities/path.ts\";\nimport { PrintFormattedError } from \"../../utilities/print-formatted-error.ts\";\nimport { getPreloadInfo } from \"./get-file-type.ts\";\n\nimport type { 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\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 include = node.getAttribute(includeAttribute) || \"**/*\";\n const ignore = node.getAttribute(excludeAttribute) ?? undefined;\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 return {\n version: 1.1,\n tags: [\n { name: \"link\", attributes },\n { name: \"script\", attributes },\n ],\n };\n },\n };\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[]>();\nconst selectorParts: 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 selectorParts.push(`${tag}[${attribute}]`);\n }\n}\n\n// One big selector: \"img[src],video[src],...,a[href],...\"\nconst combinedSelector = selectorParts.join(\",\");\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\nexport function parseHtmlSources(ast: Document): ParseHtmlLinksResult[] {\n const links: ParseHtmlLinksResult[] = [];\n\n // One tree walk instead of eight\n for (const node of ast.querySelectorAll(combinedSelector)) {\n const tag = node.tagName.toLowerCase();\n\n const attributes = tagAttributeMap.get(tag);\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 links.push({\n node,\n get source() {\n return 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 links.push({\n node,\n get source() {\n return 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 } 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 // Parse HTML to AST (HTML root element)\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 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 htmlTerser from \"html-minifier-terser\";\n\nimport type { ValueOrError } from \"../../../utilities/value-or-error.ts\";\n\nexport async function minifyHtmlTerser(code: string): Promise<ValueOrError<string>> {\n try {\n const minified = await htmlTerser.minify(code, {\n minifyCSS: false,\n minifyJS: false,\n removeComments: true,\n collapseWhitespace: true,\n });\n\n return [minified, null];\n } catch {\n return [null, new Error(\"Failed to minify HTML\")];\n }\n}\n","import { parseHtmlSources } from \"../../../ast-utilities/html-utils/parse-html-sources.ts\";\nimport { formatCode } from \"../../../helpers/format-code.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 { htmlLoader } from \"./html-loader.ts\";\nimport { minifyHtmlTerser } from \"./minify-html.ts\";\n\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\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 }) {\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 [formatted, formatError] = await formatCode(code, join(this.root, metadata.filePath), \"html\");\n if (formatError) {\n this.log.error(\"Failed to format script\", metadata.filePath);\n return;\n }\n\n return formatted;\n }\n\n if (minify) {\n const [minified, minifyError] = await minifyHtmlTerser(code);\n if (minifyError) {\n this.log.error(\"Failed to minify style\", metadata.filePath);\n return;\n }\n\n return minified;\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 // Embedded scripts\n const scripts = metadata.ast.querySelectorAll(\"script\");\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 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 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}\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 { formatCode } from \"../../../helpers/format-code.ts\";\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\";\n\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\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 }) {\n if (!isMarkdownMetadata(metadata)) return;\n\n const code = processor.stringify(metadata.ast.root);\n\n if (format) {\n const [formatted, formatError] = await formatCode(code, join(this.root, metadata.filePath), \"markdown\");\n if (formatError) {\n this.log.error(\"Failed to format markdown\", metadata.filePath);\n return;\n }\n\n return formatted;\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 { minifySync as swcMinify } from \"@swc/core\";\nimport { minify_sync as terserMinify } from \"terser\";\n\nimport type { ValueOrError } from \"../../../utilities/value-or-error.ts\";\n\nexport function minifyScriptTerser(code: string, isModule: boolean): ValueOrError<string> {\n try {\n const minified = terserMinify(code, { module: isModule });\n\n if (!minified.code) {\n return [null, new Error(\"Failed to minify script: empty output\")];\n }\n\n return [minified.code, null];\n } catch (error) {\n return [null, error as Error];\n }\n}\n\nexport function minifyScriptSWC(code: string, isModule: boolean): ValueOrError<string> {\n try {\n const minified = swcMinify(code, { module: isModule });\n\n if (!minified.code) {\n return [null, new Error(\"Failed to minify script: empty output\")];\n }\n\n return [minified.code, null];\n } catch (error) {\n return [null, error as Error];\n }\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 { formatCode } from \"../../../helpers/format-code.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 { minifyScriptSWC } from \"./minify-script.ts\";\nimport { scriptLoader } from \"./script-loader.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\n\nconst generator = typeof _generator === \"function\" ? _generator : _generator.default;\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 }) {\n if (!isScriptMetadata(metadata)) return;\n\n const code = generator(metadata.ast, { jsescOption: { minimal: true } }).code;\n\n if (format) {\n const [formatted, formatError] = await formatCode(code, join(this.root, metadata.filePath), \"js\");\n if (formatError) {\n this.log.error(\"Failed to format script\", metadata.filePath);\n return;\n }\n\n return formatted;\n }\n\n if (minify) {\n const [minified, minifyError] = minifyScriptSWC(code, metadata.module);\n if (minifyError) {\n printFmtError(\"Failed to minify script\", minifyError, { filePath: metadata.filePath });\n return;\n }\n\n return minified;\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 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(atRule => {\n if (atRule.name !== \"import\") return;\n\n for (const match of atRule.params.matchAll(cssUrlRe)) {\n const source = match[2];\n if (!source) continue;\n\n handles.push({\n node: atRule,\n get source() {\n return source;\n },\n set source(newSource) {\n atRule.params = atRule.params.replace(source, () => newSource);\n },\n });\n }\n });\n\n return handles;\n}\n","import cssnanoPlugin from \"cssnano\";\nimport defaultPreset from \"cssnano-preset-default\";\nimport { transform } from \"lightningcss\";\nimport postcss from \"postcss\";\n\nimport type { ValueOrError } from \"../../../utilities/value-or-error.ts\";\nimport type { PostcssAst } from \"@staticbolt/core\";\nimport type { Targets } from \"lightningcss\";\n\n/** @mutate cssRoot */\nexport async function minifyStyleCssNano(ast: PostcssAst, absFilePath: string): Promise<ValueOrError<string>> {\n try {\n const processResults = await postcss([cssnanoPlugin({ preset: defaultPreset() })]).process(ast, {\n from: absFilePath,\n });\n\n return [processResults.root.toString(), null];\n } catch (error) {\n return [null, error as Error];\n }\n}\n\nexport function minifyLightingCss(code: string, filename: string, targets?: Targets): ValueOrError<string> {\n try {\n const results = transform({\n filename,\n code: Buffer.from(code),\n minify: true,\n analyzeDependencies: false,\n targets,\n });\n\n return [results.code.toString(), null];\n } catch (error) {\n return [null, error as Error];\n }\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 { browserslistToTargets } from \"lightningcss\";\n\nimport { parseStyleSources } from \"../../../ast-utilities/postcss-utils/parse-style-srouces.ts\";\nimport { formatCode } from \"../../../helpers/format-code.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 { minifyLightingCss } from \"./minify-style.ts\";\nimport { styleLoader } from \"./style-loader.ts\";\n\nimport type { Plugin } from \"@staticbolt/core\";\nimport type { Targets } from \"lightningcss\";\n\nexport function coreStylePlugin(): Plugin {\n let targets: Targets | undefined;\n\n return {\n name: \"core-style-metadata\",\n\n setup() {\n targets = browserslistToTargets(this.browserslist);\n },\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 }) {\n if (!isStyleMetadata(metadata)) return;\n\n const code = metadata.ast.toString();\n\n if (format) {\n const [formatted, formatError] = await formatCode(code, join(this.root, metadata.filePath), \"css\");\n if (formatError) {\n this.log.error(\"Failed to format style\", metadata.filePath);\n return;\n }\n\n return formatted;\n }\n\n if (minify) {\n const [minified, minifyError] = minifyLightingCss(code, metadata.filePath, targets);\n if (minifyError) {\n this.log.error(\"Failed to minify style\", metadata.filePath);\n return;\n }\n\n return minified;\n }\n\n return metadata.ast.toString();\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 { formatCode } from \"../../../helpers/format-code.ts\";\nimport { parseHtml } from \"../../../parsers/html-parser.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 { minifyHtmlTerser } from \"../html-metadata/minify-html.ts\";\nimport { svgLoader } from \"./svg-loader.ts\";\n\nimport type { MetadataSource, Plugin, StyleMetadata } from \"@staticbolt/core\";\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 const [rootClone, error] = parseHtml(metadata.ast.toString());\n if (error) {\n throw error;\n }\n\n cloned.ast = rootClone;\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 }) {\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 [formatted, formatError] = await formatCode(code, join(this.root, metadata.filePath), \"html\");\n if (formatError) {\n this.log.error(\"Failed to format style\", metadata.filePath);\n return;\n }\n\n return formatted;\n }\n\n if (minify) {\n const [minified, minifyError] = await minifyHtmlTerser(code);\n if (minifyError) {\n this.log.error(\"Failed to minify style\", metadata.filePath);\n return;\n }\n\n return minified;\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\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 { 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;\n\nfunction connect() {\n const 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\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 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 { extname, join, normalize } from \"../../../utilities/path.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\nexport interface DevelopmentServerOptions {\n /**\n * The dev server host.\n *\n * @default 0.0.0.0\n */\n host?: 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\nexport function developmentServerPlugin(options: DevelopmentServerOptions = {}): Plugin {\n const host = options.host ?? \"0.0.0.0\";\n const port = options.port ?? 3000;\n const entry = options.entry ?? \"/\";\n const publicDirectory = options.publicDirectory ?? \"public\";\n\n let fastify: Fastify.FastifyInstance;\n let websocket: Server;\n const wsClients: Set<WebSocket> = new Set();\n const entryPointAgeMap = new Map<string, number>();\n\n function upgradeWebSocketHandler(request: IncomingMessage, socket: Duplex, head: Buffer) {\n websocket.handleUpgrade(request, socket, head, ws => {\n wsClients.add(ws);\n websocket.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 setup() {\n if (this.production) return;\n\n // Web Socket\n websocket = new WebSocketServer({ noServer: true });\n\n // Web Server\n const fastifyServe: onRequestHookHandler = async (request, reply) => {\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\", upgradeWebSocketHandler);\n fastify.listen({ port, host }, (error, address) => {\n if (error) {\n this.log.error(error.message);\n throw new Error(error.message);\n }\n\n this.log.info(chalk.bold(\"Server listening on\"), chalk.green(address + entry));\n });\n\n websocket.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\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\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","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 { MetadataBase, AppConfig, BoundPlugin, MetadataSource, Plugin, ServerReply, ServerRequest } 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\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. */\n readonly watcher: FSWatcher | undefined;\n\n private isPluginInitialized = false;\n\n private measureExecutionTime = false;\n private executionTime: Record<string, Record<string, number>> = {};\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 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);\n\n // Load plugins\n const pluginsEntries = (options.plugins ?? []).entries();\n for (const [index, pluginOrPlugins] of pluginsEntries) {\n const items = Array.isArray(pluginOrPlugins) ? pluginOrPlugins : [pluginOrPlugins];\n for (const [itemIndex, plugin] of items.entries()) {\n this.plugins.push(this.bindPlugin(plugin, index + itemIndex));\n }\n }\n\n // Base plugin\n this.plugins.push(this.bindPlugin(coreBasePlugin(), this.plugins.length - 1));\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 private bindPlugin(plugin: Plugin, pluginIndex: number): BoundPlugin {\n const emptyFunction = () => {};\n\n const context = Object.create(this) as App & { pluginIndex: number; pluginName: string };\n context.pluginIndex = pluginIndex;\n context.pluginName = plugin.name;\n context.log = createLog(`[${plugin.name}]`);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const bind = (method?: (...arguments_: any[]) => any) => {\n return method ? method.bind(context) : emptyFunction;\n };\n\n plugin.setup = bind(plugin.setup);\n plugin.read = bind(plugin.read);\n plugin.load = bind(plugin.load);\n plugin.resolveSource = bind(plugin.resolveSource);\n plugin.transformSource = bind(plugin.transformSource);\n plugin.preTransform = bind(plugin.preTransform);\n plugin.transform = bind(plugin.transform);\n plugin.postTransform = bind(plugin.postTransform);\n plugin.write = bind(plugin.write);\n plugin.postBuild = bind(plugin.postBuild);\n plugin.clone = bind(plugin.clone);\n plugin.stringify = bind(plugin.stringify);\n plugin.sourcesProvider = bind(plugin.sourcesProvider);\n plugin.rebaseSource = bind(plugin.rebaseSource);\n plugin.onMetadataRebase = bind(plugin.onMetadataRebase);\n\n // Dev server\n plugin.handleRequest = bind(plugin.handleRequest);\n plugin.resolveRequestPath = bind(plugin.resolveRequestPath);\n plugin.onFileEvent = bind(plugin.onFileEvent);\n plugin.resolveCompileList = bind(plugin.resolveCompileList);\n\n return plugin as 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\n const methodFunction = plugin[method] as (...arguments__: unknown[]) => unknown;\n const result = methodFunction(...arguments_) as ReturnType<BoundPlugin[T]>;\n\n this.executionTime[plugin.name][method] += performance.now() - now;\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 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(this.metadataList);\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 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 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 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 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 metadataItem.directDependencies.add(discoveredID);\n\n if (this.entryPoints.has(discoveredID)) continue;\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 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\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 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 await this.callPluginMethod(plugin, \"onMetadataRebase\", metadata, oldAbsolutePath, newAbsolutePath);\n }\n }\n\n async writeFiles(metadataItemOrList: MetadataBase | MetadataBase[]) {\n if (!this.isPluginInitialized) {\n this.log.warn(\"[emit] Plugins are not fully setup yet.\");\n }\n\n const items = Array.isArray(metadataItemOrList) ? metadataItemOrList : [metadataItemOrList];\n\n for (const plugin of this.plugins) {\n for (const metadata of items) {\n await this.callPluginMethod(plugin, \"write\", metadata);\n }\n }\n }\n\n async read(filePath: string) {\n filePath = normalize(filePath);\n\n if (!isAbsolute) {\n filePath = join(this.root, filePath);\n }\n\n for (const plugin of this.plugins) {\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 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 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: { minify?: boolean; format?: boolean } = {}): 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 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 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 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 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 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 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 Object.entries(metadataFilter)) {\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 return this.metadataList.filter(metadata => {\n // Match by reference\n if (metadata === metadataFilter) {\n return true;\n }\n\n for (const [key, value] of Object.entries(metadataFilter)) {\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\";\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\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\n buildCommand.onExecute(async () => {\n const startTime = performance.now();\n\n config.production = true;\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 ttf2woff2 from \"ttf2woff2\";\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\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(({ options }) => {\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 \"auto\"\n */\n fontDisplay?: \"auto\" | \"block\" | \"swap\" | \"fallback\" | \"optional\";\n}\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\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 { App } from \"../../../main.ts\";\n\nimport type { 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\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) {\n const buildCommand = this.defineSubcommand({\n name,\n aliases,\n meta: { description: \"Dev server for static bolt.\" },\n });\n\n buildCommand.onExecute(async () => {\n config.production = false;\n\n const app = new App(config, configPath);\n await app.run();\n });\n\n this.addC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